Lab5
This commit is contained in:
parent
73684e5b85
commit
c781252cb3
@ -1,3 +1,3 @@
|
||||
# Отчёт по лабораторной работе №4
|
||||
# Отчёт по лабораторной работе №5
|
||||
|
||||
Файл отчета: `Отчет лаб4.docx`
|
||||
Файл отчета: `Отчет лаб5.docx`
|
||||
|
259
data.json
Normal file
259
data.json
Normal file
@ -0,0 +1,259 @@
|
||||
{
|
||||
"movies": [
|
||||
{
|
||||
"title": "Бойцовский клуб",
|
||||
"typeId": 1,
|
||||
"requiresSubscription": true,
|
||||
"poster": "src/assets/main-page/posters/FightClub.png",
|
||||
"description": "Сотрудник страховой компании страдает хронической бессонницей и отчаянно пытается вырваться из мучительно скучной жизни. Однажды в очередной командировке он встречает некоего Тайлера Дёрдена — харизматического торговца мылом с извращенной философией. Тайлер уверен, что самосовершенствование — удел слабых, а единственное, ради чего стоит жить, — саморазрушение.<br><br> Проходит немного времени, и вот уже новые друзья лупят друг друга почем зря на стоянке перед баром, и очищающий мордобой доставляет им высшее блаженство. Приобщая других мужчин к простым радостям физической жестокости, они основывают тайный Бойцовский клуб, который начинает пользоваться невероятной популярностью.",
|
||||
"releaseDate": "1999",
|
||||
"country": "США, Германия",
|
||||
"tagline": "Интриги. Хаос. Мыло",
|
||||
"director": "Дэвид Финчер",
|
||||
"ageRatingId": 5,
|
||||
"video": "https://www.youtube.com/embed/dfeUzm6KF4g?si=U2D-2WNsJzkcxlBX",
|
||||
"id": 1
|
||||
},
|
||||
{
|
||||
"title": "Острые козырьки",
|
||||
"typeId": 2,
|
||||
"requiresSubscription": false,
|
||||
"poster": "src/assets/main-page/posters/PeakyBlinders.png",
|
||||
"description": "Сериал рассказывает историю восхождения одной цыганско-ирландской семьи и превращения ее в один из самых могущественных криминальных кланов Великобритании. Речь о семье Шелби, которая живет в начале XX века во втором крупном после Лондона городе Британии — Бирмингеме и набирает свою мощь в период между двумя мировыми войнами.",
|
||||
"releaseDate": "2013",
|
||||
"country": "Великобритания",
|
||||
"tagline": "The streets are theirs",
|
||||
"director": "Энтони Бирн, Колм МакКарти",
|
||||
"ageRatingId": 4,
|
||||
"video": "https://www.youtube.com/embed/7cOfn_sjlXM?si=fxNoZjlUon1SZd70",
|
||||
"id": 2
|
||||
},
|
||||
{
|
||||
"title": "Американский психопат",
|
||||
"typeId": 1,
|
||||
"requiresSubscription": true,
|
||||
"poster": "src/assets/main-page/posters/AmericanPsycho.jpg",
|
||||
"description": "Днем он ничем не отличается от окружающих, и в толпе вы не обратите на него внимания. Но ночью этот благовоспитанный гражданин превращается в изощренного убийцу, терроризирующего спящий город.\n<br><br>\nСовременный дикарь, презирающий законы человечества, питается только испепеляющим пламенем своей ненависти, которая растет с каждым новым преступлением. Лавина ужаса приближается к критической черте. Скоро наступит момент, когда ее уже нельзя будет остановить.",
|
||||
"releaseDate": "2000",
|
||||
"country": "США, Канада",
|
||||
"tagline": "Респектабельная внешность дьявола",
|
||||
"director": "Мэри Хэррон",
|
||||
"ageRatingId": 5,
|
||||
"video": "https://www.youtube.com/embed/PpUWjff_OcM?si=e7tSm4V6qYkz406B",
|
||||
"id": 3
|
||||
},
|
||||
{
|
||||
"title": "Драйв",
|
||||
"typeId": 1,
|
||||
"requiresSubscription": false,
|
||||
"poster": "src/assets/main-page/posters/Drive.jpg",
|
||||
"description": "Великолепный водитель – при свете дня он выполняет каскадерские трюки на съёмочных площадках Голливуда, а по ночам ведет рискованную игру. Но один опасный контракт – и за его жизнь назначена награда. Теперь, чтобы остаться в живых и спасти свою очаровательную соседку, он должен делать то, что умеет лучше всего – виртуозно уходить от погони.",
|
||||
"releaseDate": "2011",
|
||||
"country": "США",
|
||||
"tagline": "Some Heroes Are Real",
|
||||
"director": " Николас Виндинг Рефн",
|
||||
"ageRatingId": 5,
|
||||
"video": "https://www.youtube.com/embed/XRK_wPm_EkI?si=4F8pjXahHsG1Gp5w",
|
||||
"id": 4
|
||||
},
|
||||
{
|
||||
"title": "Джокер",
|
||||
"typeId": 1,
|
||||
"requiresSubscription": true,
|
||||
"poster": "src/assets/main-page/posters/Joker.jpg",
|
||||
"description": "Готэм, начало 1980-х годов. Комик Артур Флек живет с больной матерью, которая с детства учит его «ходить с улыбкой». Пытаясь нести в мир хорошее и дарить людям радость, Артур сталкивается с человеческой жестокостью и постепенно приходит к выводу, что этот мир получит от него не добрую улыбку, а ухмылку злодея Джокера.",
|
||||
"releaseDate": "2019",
|
||||
"country": "США, Канада",
|
||||
"tagline": "Сделай счастливое лицо",
|
||||
"director": "Тодд Филлипс",
|
||||
"ageRatingId": 5,
|
||||
"video": "https://www.youtube.com/embed/zAGVQLHvwOY?si=ecHfyymUUE8A6u2I",
|
||||
"id": 5
|
||||
},
|
||||
{
|
||||
"title": "Старикам здесь не место",
|
||||
"typeId": 1,
|
||||
"requiresSubscription": false,
|
||||
"poster": "src/assets/main-page/posters/NoCountryForOldMen.jpg",
|
||||
"description": "Обычный работяга обнаруживает в пустыне гору трупов, набитый героином грузовик и соблазнительную сумму в два миллиона долларов наличными. Он решает взять деньги себе, и результатом становится волна насилия, которую не может остановить вся полиция Западного Техаса.",
|
||||
"releaseDate": "2007",
|
||||
"country": "США",
|
||||
"tagline": "Из воды сухим не выйти",
|
||||
"director": "Итан Коэн, Джоэл Коэн",
|
||||
"ageRatingId": 5,
|
||||
"video": "https://www.youtube.com/embed/qZL0Ru-55u8?si=OISl2S8ojmJ1Mtqa",
|
||||
"id": 6
|
||||
},
|
||||
{
|
||||
"title": "Дилер",
|
||||
"typeId": 1,
|
||||
"requiresSubscription": true,
|
||||
"poster": "src/assets/main-page/posters/Pusher.png",
|
||||
"description": "У пушера Франка крупные неприятности. Он должен 50 тысяч поставщикам-югославам, а вдобавок к этому во время продажи героина приезжим шведам налетела полиция, и весь взятый в долг товар пришлось выбросить в пруд. Друг Тонни, с которым он вместе работал, во всем признался полиции. Но товар выброшен, улик нет, и Франка выпустили. Теперь его долг поставщику Мило — 180 тысяч.",
|
||||
"releaseDate": "1996",
|
||||
"country": "Дания",
|
||||
"tagline": "You don't have a chance. Seize it!",
|
||||
"director": "Николас Виндинг Рефн",
|
||||
"ageRatingId": 5,
|
||||
"video": "https://www.youtube.com/embed/Mzv1bIsk5nU?si=ois8iG1SNlNQuzRc",
|
||||
"id": 7
|
||||
},
|
||||
{
|
||||
"title": "Лицо со шрамом",
|
||||
"typeId": 1,
|
||||
"requiresSubscription": true,
|
||||
"poster": "src/assets/main-page/posters/Scarface.png",
|
||||
"description": "Весной 1980 года был открыт порт Мэйриэл Харбор, и тысячи кубинских беженцев ринулись в Соединенные Штаты на поиски Американской Мечты. Один из них нашел ее на залитых солнцем улицах Майами. Богатство, власть и страсть превзошли даже самые невероятные его мечты. Его звали Тони Монтана. Мир запомнил его под другим именем — Лицо со шрамом.",
|
||||
"releaseDate": "1983",
|
||||
"country": "США",
|
||||
"tagline": "The World Is Yours",
|
||||
"director": "Брайан Де Пальма",
|
||||
"ageRatingId": 5,
|
||||
"video": "https://www.youtube.com/embed/cv276Wg3e7I?si=sqZS0rQiCjpFjGmX",
|
||||
"id": 8
|
||||
},
|
||||
{
|
||||
"title": "Лучше звоните Солу",
|
||||
"typeId": 2,
|
||||
"requiresSubscription": true,
|
||||
"poster": "src/assets/main-page/posters/BetterCallSaul.png",
|
||||
"description": "История об испытаниях и невзгодах, которые приходится преодолеть Солу Гудману, адвокату по уголовным делам, в тот период, когда он пытается открыть свою собственную адвокатскую контору в Альбукерке, штат Нью-Мексико.",
|
||||
"releaseDate": "2015",
|
||||
"country": "США",
|
||||
"tagline": "Make the call",
|
||||
"director": " Винс Гиллиган, Питер Гулд",
|
||||
"ageRatingId": 4,
|
||||
"video": "https://www.youtube.com/embed/1u29aCWtW_Y?si=x7sqjMAMcbxeeaKb",
|
||||
"id": 9
|
||||
},
|
||||
{
|
||||
"title": "Во все тяжкие",
|
||||
"typeId": 2,
|
||||
"requiresSubscription": true,
|
||||
"poster": "src/assets/main-page/posters/BreakingBad.png",
|
||||
"description": "Школьный учитель химии Уолтер Уайт узнаёт, что болен раком лёгких. Учитывая сложное финансовое состояние дел семьи, а также перспективы, Уолтер решает заняться изготовлением метамфетамина. Для этого он привлекает своего бывшего ученика Джесси Пинкмана, когда-то исключённого из школы при активном содействии Уайта. Пинкман сам занимался варкой мета, но накануне, в ходе рейда УБН, он лишился подельника и лаборатории.",
|
||||
"releaseDate": "2008",
|
||||
"country": "США",
|
||||
"tagline": "Запомните моё имя",
|
||||
"director": " Винс Гиллиган",
|
||||
"ageRatingId": 5,
|
||||
"video": "https://www.youtube.com/embed/I4MCAOd-tmg?si=W65-59QB5PQKsljs",
|
||||
"id": 10
|
||||
},
|
||||
{
|
||||
"title": "Клан Сопрано",
|
||||
"typeId": 2,
|
||||
"requiresSubscription": false,
|
||||
"poster": "src/assets/main-page/posters/Sopranos.png",
|
||||
"description": "Мафиозный босс Северного Джерси Тони Сопрано эффективно решает проблемы «семьи». Но с собственной роднёй ситуация сложнее: дети от рук отбились, брак под угрозой, в отношениях с пожилой матерью сплошное недопонимание. После серии панических атак он решает тайно посещать психотерапевта.",
|
||||
"releaseDate": "1999",
|
||||
"country": "США",
|
||||
"tagline": "Tony's not like other fathers. Tony is a mob boss",
|
||||
"director": "Тимоти Ван Паттен, Джон Паттерсон",
|
||||
"ageRatingId": 5,
|
||||
"video": "https://www.youtube.com/embed/sxc61veiHmw?si=HPf4LJOvG4sEZaux",
|
||||
"id": 11
|
||||
},
|
||||
{
|
||||
"title": "123",
|
||||
"typeId": 1,
|
||||
"requiresSubscription": true,
|
||||
"poster": "src/assets/main-page/posters/BladeRunner2049.jpg",
|
||||
"description": "12313",
|
||||
"releaseDate": "1231231",
|
||||
"country": "США",
|
||||
"tagline": "The streets are theirs",
|
||||
"director": "Энтони Бирн, Колм МакКарти",
|
||||
"ageRatingId": 5,
|
||||
"video": "https://www.youtube.com/embed/zAGVQLHvwOY?si=ecHfyymUUE8A6u2I",
|
||||
"id": 12
|
||||
}
|
||||
],
|
||||
"types": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Фильм"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "Сериал"
|
||||
}
|
||||
],
|
||||
"users": [
|
||||
{
|
||||
"id": 1,
|
||||
"email": "myemail@mail.com",
|
||||
"password": "12345678",
|
||||
"expirationDate": null
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"email": "another@mail.com",
|
||||
"password": "qwerty",
|
||||
"expirationDate": null
|
||||
}
|
||||
],
|
||||
"ageRatings": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "0+"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "6+"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"name": "12+"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"name": "16+"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"name": "18+"
|
||||
}
|
||||
],
|
||||
"pricingPlans": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Большой Шлёппа",
|
||||
"subtitle": "Подписка на неделю",
|
||||
"price": 49.99,
|
||||
"description": "Попробуйте и решите, нравится ли вам наш сервис",
|
||||
"isPrimary": false,
|
||||
"period": {
|
||||
"days": 7,
|
||||
"months": 0,
|
||||
"years": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "Базированный гигачад",
|
||||
"subtitle": "Подписка на месяц",
|
||||
"price": 149.99,
|
||||
"description": "Для тех, кто очень любит смотреть фильмы и сериалы по вечерам",
|
||||
"isPrimary": true,
|
||||
"period": {
|
||||
"days": 0,
|
||||
"months": 1,
|
||||
"years": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "Райан Гослинг",
|
||||
"subtitle": "Подписка на год",
|
||||
"price": 799.99,
|
||||
"description": "Если вдруг захотите остаться с нами подольше",
|
||||
"isPrimary": false,
|
||||
"period": {
|
||||
"days": 0,
|
||||
"months": 0,
|
||||
"years": 1
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
@ -5,7 +5,8 @@
|
||||
"target": "ES2020",
|
||||
"jsx": "react",
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true
|
||||
"strictFunctionTypes": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
|
5
json-server.json
Normal file
5
json-server.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"static": "./node_modules/json-server/public",
|
||||
"port": 8081,
|
||||
"watch": "true"
|
||||
}
|
1626
package-lock.json
generated
1626
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
14
package.json
14
package.json
@ -4,15 +4,18 @@
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
|
||||
"preview": "vite preview"
|
||||
"rest": "json-server data.json",
|
||||
"vite": "vite",
|
||||
"dev": "npm-run-all --parallel rest vite",
|
||||
"prod": "npm-run-all lint 'vite build' --parallel rest 'vite preview'"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.18.0",
|
||||
"react-hot-toast": "^2.4.1",
|
||||
"axios": "^1.6.1",
|
||||
"bootstrap": "^5.3.2",
|
||||
"react-bootstrap": "^2.9.1",
|
||||
"react-bootstrap-icons": "^1.10.3",
|
||||
@ -20,13 +23,16 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.2.15",
|
||||
"@types/react-dom": "^18.2.7",
|
||||
"@types/react-dom": "^18.2.15",
|
||||
"@vitejs/plugin-react": "^4.0.3",
|
||||
"eslint": "^8.45.0",
|
||||
"eslint-config-airbnb-base": "^15.0.0",
|
||||
"eslint-plugin-import": "^2.29.0",
|
||||
"eslint-plugin-react": "^7.32.2",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.3",
|
||||
"json-server": "^0.17.4",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"vite": "^4.4.5"
|
||||
}
|
||||
}
|
24
src/App.jsx
24
src/App.jsx
@ -1,21 +1,31 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Container } from 'react-bootstrap';
|
||||
import { Toaster } from 'react-hot-toast';
|
||||
import { Outlet } from 'react-router-dom';
|
||||
import './App.css';
|
||||
import Footer from './components/footer/Footer.jsx';
|
||||
import Navigation from './components/navigation/Navigation.jsx';
|
||||
import { WishlistProvider } from './components/wishlist/WishlistContext.jsx';
|
||||
import { LoginProvider } from './components/login/LoginContext.jsx';
|
||||
import { SubscriptionProvider } from './components/subscription/SubscriptionContext.jsx';
|
||||
|
||||
const App = ({ routes }) => {
|
||||
return (
|
||||
<>
|
||||
<Navigation routes={ routes }></Navigation>
|
||||
<LoginProvider>
|
||||
<SubscriptionProvider>
|
||||
<WishlistProvider>
|
||||
<Navigation routes={ routes }></Navigation>
|
||||
|
||||
<Container as="main" fluid className="px-0">
|
||||
<Outlet />
|
||||
</Container>
|
||||
<Container as="main" fluid className="px-0">
|
||||
<Outlet />
|
||||
</Container>
|
||||
|
||||
<Footer routes={ routes } />
|
||||
</>
|
||||
<Footer routes={ routes } />
|
||||
|
||||
<Toaster position='top-center' reverseOrder={true} />
|
||||
</WishlistProvider>
|
||||
</SubscriptionProvider>
|
||||
</LoginProvider>
|
||||
);
|
||||
};
|
||||
|
||||
|
BIN
src/assets/200.png
Normal file
BIN
src/assets/200.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 1.5 KiB |
21
src/components/ageRatings/hooks/AgeRatingsHook.js
Normal file
21
src/components/ageRatings/hooks/AgeRatingsHook.js
Normal file
@ -0,0 +1,21 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import AgeRatingsApiService from '../service/AgeRatingsApiService';
|
||||
|
||||
const useAgeRatings = () => {
|
||||
const [ageRatings, setAgeRatings] = useState([]);
|
||||
|
||||
const getAgeRatings = async () => {
|
||||
const data = await AgeRatingsApiService.getAll();
|
||||
setAgeRatings(data ?? []);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getAgeRatings();
|
||||
}, []);
|
||||
|
||||
return {
|
||||
ageRatings,
|
||||
};
|
||||
};
|
||||
|
||||
export default useAgeRatings;
|
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const AgeRatingsApiService = new ApiService('ageRatings');
|
||||
|
||||
export default AgeRatingsApiService;
|
40
src/components/api/ApiClient.js
Normal file
40
src/components/api/ApiClient.js
Normal file
@ -0,0 +1,40 @@
|
||||
import axios from 'axios';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
export class HttpError extends Error {
|
||||
constructor(message = '') {
|
||||
super(message);
|
||||
this.name = 'HttpError';
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
toast.error(message, { id: 'HttpError' });
|
||||
}
|
||||
}
|
||||
|
||||
function responseHandler(response) {
|
||||
if (response.status === 200 || response.status === 201) {
|
||||
const data = response?.data;
|
||||
if (!data) {
|
||||
throw new HttpError('API Error. No data!');
|
||||
}
|
||||
return data;
|
||||
}
|
||||
throw new HttpError(`API Error! Invalid status code ${response.status}!`);
|
||||
}
|
||||
|
||||
function responseErrorHandler(error) {
|
||||
if (error === null) {
|
||||
throw new Error('Unrecoverable error!! Error is null!');
|
||||
}
|
||||
toast.error(error.message, { id: 'AxiosError' });
|
||||
return Promise.reject(error.message);
|
||||
}
|
||||
|
||||
export const ApiClient = axios.create({
|
||||
baseURL: 'http://localhost:8081/',
|
||||
timeout: '3000',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
ApiClient.interceptors.response.use(responseHandler, responseErrorHandler);
|
29
src/components/api/ApiService.js
Normal file
29
src/components/api/ApiService.js
Normal file
@ -0,0 +1,29 @@
|
||||
import { ApiClient } from './ApiClient';
|
||||
|
||||
class ApiService {
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
async getAll(expand) {
|
||||
return ApiClient.get(`${this.url}${expand || ''}`);
|
||||
}
|
||||
|
||||
async get(id, expand) {
|
||||
return ApiClient.get(`${this.url}/${id}${expand || ''}`);
|
||||
}
|
||||
|
||||
async create(body) {
|
||||
return ApiClient.post(this.url, body);
|
||||
}
|
||||
|
||||
async update(id, body) {
|
||||
return ApiClient.put(`${this.url}/${id}`, body);
|
||||
}
|
||||
|
||||
async delete(id) {
|
||||
return ApiClient.delete(`${this.url}/${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
export default ApiService;
|
70
src/components/authentification/hooks/UserLoginFormHook.js
Normal file
70
src/components/authentification/hooks/UserLoginFormHook.js
Normal file
@ -0,0 +1,70 @@
|
||||
import { useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import UsersApiService from '../service/UsersApiService';
|
||||
import useLogin from '../../login/LoginHook';
|
||||
|
||||
const useUserLoginForm = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { loginAuthorize } = useLogin();
|
||||
|
||||
const [currentInput, setCurrentInput] = useState({});
|
||||
const [validated, setValidated] = useState(false);
|
||||
|
||||
const resetValidity = () => {
|
||||
setValidated(false);
|
||||
};
|
||||
|
||||
const handleChange = (event) => {
|
||||
const inputName = event.target.name;
|
||||
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
|
||||
|
||||
setCurrentInput({
|
||||
...currentInput,
|
||||
[inputName]: inputValue,
|
||||
});
|
||||
};
|
||||
|
||||
const checkCredentials = async () => {
|
||||
let correspondingUser;
|
||||
|
||||
const allUsers = await UsersApiService.getAll();
|
||||
allUsers.forEach((user) => {
|
||||
if (user.email === currentInput.email && user.password === currentInput.password) {
|
||||
correspondingUser = user;
|
||||
}
|
||||
});
|
||||
|
||||
if (!correspondingUser) {
|
||||
toast.error('Введены неверные логин и пароль');
|
||||
return;
|
||||
}
|
||||
|
||||
loginAuthorize(correspondingUser);
|
||||
navigate('/');
|
||||
};
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
const form = event.currentTarget;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
if (form.checkValidity()) {
|
||||
await checkCredentials();
|
||||
return true;
|
||||
}
|
||||
|
||||
setValidated(true);
|
||||
return false;
|
||||
};
|
||||
|
||||
return {
|
||||
validated,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
resetValidity,
|
||||
};
|
||||
};
|
||||
|
||||
export default useUserLoginForm;
|
@ -0,0 +1,38 @@
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
import {
|
||||
Form, Button, Modal,
|
||||
} from 'react-bootstrap';
|
||||
|
||||
const ForgotPasswordModal = ({ shouldShowModal, hideModal }) => {
|
||||
return (
|
||||
<Modal show={shouldShowModal} onHide={() => hideModal()}>
|
||||
<Modal.Header closeButton>
|
||||
<Modal.Title>Восстановление пароля</Modal.Title>
|
||||
</Modal.Header>
|
||||
|
||||
<Modal.Body className="mb-3">
|
||||
<p>В поле ниже напишите адрес электроннной почты, с которой была совершена
|
||||
регистрация. На этот адрес придёт письмо с дальнейшеми указаниями.</p>
|
||||
|
||||
<Form.Group>
|
||||
<Form.Label>Адрес электронной почты:</Form.Label>
|
||||
<Form.Control type="email" placeholder="myemail@mail.com" />
|
||||
</Form.Group>
|
||||
</Modal.Body>
|
||||
|
||||
<Modal.Footer>
|
||||
<Button variant="primary" onClick={() => hideModal()}>
|
||||
Отправить
|
||||
</Button>
|
||||
</Modal.Footer>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
ForgotPasswordModal.propTypes = {
|
||||
shouldShowModal: PropTypes.bool,
|
||||
hideModal: PropTypes.func,
|
||||
};
|
||||
|
||||
export default ForgotPasswordModal;
|
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const UsersApiService = new ApiService('users');
|
||||
|
||||
export default UsersApiService;
|
27
src/components/input/Checkbox.jsx
Normal file
27
src/components/input/Checkbox.jsx
Normal file
@ -0,0 +1,27 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Form } from 'react-bootstrap';
|
||||
|
||||
const Checkbox = ({
|
||||
name, label, value, onChange, className, ...rest
|
||||
}) => {
|
||||
return (
|
||||
<Form.Check
|
||||
name={ name || '' }
|
||||
checked={ value }
|
||||
className={ `mb-2 ${className || ''}` }
|
||||
label={ label }
|
||||
onChange={ onChange }
|
||||
{ ...rest }
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
Checkbox.propTypes = {
|
||||
name: PropTypes.string,
|
||||
label: PropTypes.string,
|
||||
value: PropTypes.bool,
|
||||
onChange: PropTypes.func,
|
||||
className: PropTypes.string,
|
||||
};
|
||||
|
||||
export default Checkbox;
|
23
src/components/input/Input.jsx
Normal file
23
src/components/input/Input.jsx
Normal file
@ -0,0 +1,23 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Form } from 'react-bootstrap';
|
||||
|
||||
const Input = ({
|
||||
name, label, value, onChange, className, ...rest
|
||||
}) => {
|
||||
return (
|
||||
<Form.Group className={`mb-2 ${className || ''}`} controlId={name}>
|
||||
<Form.Label>{label}</Form.Label>
|
||||
<Form.Control name={name || ''} value={value || ''} onChange={onChange} {...rest} />
|
||||
</Form.Group>
|
||||
);
|
||||
};
|
||||
|
||||
Input.propTypes = {
|
||||
name: PropTypes.string,
|
||||
label: PropTypes.string,
|
||||
value: PropTypes.string,
|
||||
onChange: PropTypes.func,
|
||||
className: PropTypes.string,
|
||||
};
|
||||
|
||||
export default Input;
|
29
src/components/input/Select.jsx
Normal file
29
src/components/input/Select.jsx
Normal file
@ -0,0 +1,29 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Form } from 'react-bootstrap';
|
||||
|
||||
const Select = ({
|
||||
values, name, label, value, onChange, className, ...rest
|
||||
}) => {
|
||||
return (
|
||||
<Form.Group className={`mb-2 ${className || ''}`} controlId={name}>
|
||||
<Form.Label className='form-label'>{label}</Form.Label>
|
||||
<Form.Select name={name || ''} value={value || ''} onChange={onChange} {...rest}>
|
||||
<option value=''>Выберите значение</option>
|
||||
{
|
||||
values.map((type) => <option key={type.id} value={type.id}>{type.name}</option>)
|
||||
}
|
||||
</Form.Select>
|
||||
</Form.Group>
|
||||
);
|
||||
};
|
||||
|
||||
Select.propTypes = {
|
||||
values: PropTypes.array,
|
||||
name: PropTypes.string,
|
||||
label: PropTypes.string,
|
||||
value: PropTypes.number,
|
||||
onChange: PropTypes.func,
|
||||
className: PropTypes.string,
|
||||
};
|
||||
|
||||
export default Select;
|
23
src/components/input/Textarea.jsx
Normal file
23
src/components/input/Textarea.jsx
Normal file
@ -0,0 +1,23 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Form } from 'react-bootstrap';
|
||||
|
||||
const Textarea = ({
|
||||
name, label, value, onChange, className, ...rest
|
||||
}) => {
|
||||
return (
|
||||
<Form.Group className={`mb-2 ${className || ''}`} controlId={name}>
|
||||
<Form.Label>{ label }</Form.Label>
|
||||
<Form.Control as='textarea' rows={ 4 } name={ name || '' } value={ value || '' } onChange={ onChange } {...rest} />
|
||||
</Form.Group>
|
||||
);
|
||||
};
|
||||
|
||||
Textarea.propTypes = {
|
||||
name: PropTypes.string,
|
||||
label: PropTypes.string,
|
||||
value: PropTypes.string,
|
||||
onChange: PropTypes.func,
|
||||
className: PropTypes.string,
|
||||
};
|
||||
|
||||
export default Textarea;
|
48
src/components/lines/form/LinesForm.jsx
Normal file
48
src/components/lines/form/LinesForm.jsx
Normal file
@ -0,0 +1,48 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Button, Form } from 'react-bootstrap';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import useLinesItemForm from '../hooks/LinesItemFormHook';
|
||||
import LinesItemForm from './LinesItemForm.jsx';
|
||||
|
||||
const LinesForm = ({ id }) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const {
|
||||
item,
|
||||
validated,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
} = useLinesItemForm(id);
|
||||
|
||||
const onBack = () => {
|
||||
navigate(-1);
|
||||
};
|
||||
|
||||
const onSubmit = async (event) => {
|
||||
if (await handleSubmit(event)) {
|
||||
onBack();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form className='m-0 p-2' noValidate validated={validated} onSubmit={onSubmit}>
|
||||
<LinesItemForm item={item} handleChange={handleChange} />
|
||||
<Form.Group className='row justify-content-center m-0 mt-3'>
|
||||
<Button className='col-5 col-lg-2 m-0 me-2' variant='secondary' onClick={() => onBack()}>
|
||||
Назад
|
||||
</Button>
|
||||
<Button className='col-5 col-lg-2 m-0 ms-2' type='submit' variant='primary'>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Form.Group>
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
LinesForm.propTypes = {
|
||||
id: PropTypes.string,
|
||||
};
|
||||
|
||||
export default LinesForm;
|
5
src/components/lines/form/LinesItemForm.css
Normal file
5
src/components/lines/form/LinesItemForm.css
Normal file
@ -0,0 +1,5 @@
|
||||
#image-preview {
|
||||
border-radius: 20px;
|
||||
max-width: 200px;
|
||||
height: auto;
|
||||
}
|
66
src/components/lines/form/LinesItemForm.jsx
Normal file
66
src/components/lines/form/LinesItemForm.jsx
Normal file
@ -0,0 +1,66 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import imgPlaceholder from '../../../assets/200.png';
|
||||
import Input from '../../input/Input.jsx';
|
||||
import Select from '../../input/Select.jsx';
|
||||
import Checkbox from '../../input/Checkbox.jsx';
|
||||
import Textarea from '../../input/Textarea.jsx';
|
||||
import useTypes from '../../types/hooks/TypesHook';
|
||||
import './LinesItemForm.css';
|
||||
import useAgeRatings from '../../ageRatings/hooks/AgeRatingsHook';
|
||||
|
||||
const LinesItemForm = ({ item, handleChange }) => {
|
||||
const { types } = useTypes();
|
||||
const { ageRatings } = useAgeRatings();
|
||||
|
||||
console.log(types);
|
||||
console.log(ageRatings);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='text-center'>
|
||||
<img id='image-preview' className='rounded' alt='placeholder'
|
||||
src={item.poster || imgPlaceholder} />
|
||||
</div>
|
||||
|
||||
<Input name='title' label='Название' value={item.title} onChange={handleChange}
|
||||
type='text' required />
|
||||
|
||||
<Select values={types} name='typeId' label='Тип' value={item.typeId} onChange={handleChange}
|
||||
required />
|
||||
|
||||
<Checkbox name='requiresSubscription' label='Требуется подписка'
|
||||
value={item.requiresSubscription} onChange={handleChange} />
|
||||
|
||||
<Input name='poster' label='Постер' onChange={handleChange}
|
||||
type='file' accept='image/*' />
|
||||
|
||||
<Textarea name='description' label='Описание' value={item.description} onChange={handleChange}
|
||||
required />
|
||||
|
||||
<Input name='releaseDate' label='Год производства' value={item.releaseDate} onChange={handleChange}
|
||||
type='number' min='1900' step='1' required />
|
||||
|
||||
<Input name='country' label='Страна' value={item.country} onChange={handleChange}
|
||||
type='text' required />
|
||||
|
||||
<Input name='tagline' label='Слоган' value={item.tagline} onChange={handleChange}
|
||||
type='text' required />
|
||||
|
||||
<Input name='director' label='Режиссер' value={item.director} onChange={handleChange}
|
||||
type='text' required />
|
||||
|
||||
<Select values={ageRatings} name='ageRatingId' label='Возрастное ограничение' value={item.ageRatingId} onChange={handleChange}
|
||||
required />
|
||||
|
||||
<Input name='video' label='URL видео' value={item.video} onChange={handleChange}
|
||||
type='text' required />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
LinesItemForm.propTypes = {
|
||||
item: PropTypes.object,
|
||||
handleChange: PropTypes.func,
|
||||
};
|
||||
|
||||
export default LinesItemForm;
|
34
src/components/lines/hooks/LinesDeleteModalHook.js
Normal file
34
src/components/lines/hooks/LinesDeleteModalHook.js
Normal file
@ -0,0 +1,34 @@
|
||||
import { useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import useModal from '../../modal/ModalHook';
|
||||
import LinesApiService from '../service/LinesApiService';
|
||||
|
||||
const useLinesDeleteModal = (linesChangeHandle) => {
|
||||
const { isModalShow, showModal, hideModal } = useModal();
|
||||
const [currentId, setCurrentId] = useState(0);
|
||||
|
||||
const showModalDialog = (id) => {
|
||||
showModal();
|
||||
setCurrentId(id);
|
||||
};
|
||||
|
||||
const onClose = () => {
|
||||
hideModal();
|
||||
};
|
||||
|
||||
const onDelete = async () => {
|
||||
await LinesApiService.delete(currentId);
|
||||
linesChangeHandle();
|
||||
toast.success('Элемент успешно удален', { id: 'LinesTable' });
|
||||
onClose();
|
||||
};
|
||||
|
||||
return {
|
||||
isDeleteModalShow: isModalShow,
|
||||
showDeleteModal: showModalDialog,
|
||||
handleDeleteConfirm: onDelete,
|
||||
handleDeleteCancel: onClose,
|
||||
};
|
||||
};
|
||||
|
||||
export default useLinesDeleteModal;
|
28
src/components/lines/hooks/LinesFilterHook.js
Normal file
28
src/components/lines/hooks/LinesFilterHook.js
Normal file
@ -0,0 +1,28 @@
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import useTypes from '../../types/hooks/TypesHook';
|
||||
|
||||
const useTypeFilter = () => {
|
||||
const filterName = 'type';
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const { types } = useTypes();
|
||||
|
||||
const handleFilterChange = (event) => {
|
||||
const type = event.target.value;
|
||||
if (type) {
|
||||
searchParams.set(filterName, event.target.value);
|
||||
} else {
|
||||
searchParams.delete(filterName);
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
};
|
||||
|
||||
return {
|
||||
types,
|
||||
currentFilter: searchParams.get(filterName) || '',
|
||||
handleFilterChange,
|
||||
};
|
||||
};
|
||||
|
||||
export default useTypeFilter;
|
45
src/components/lines/hooks/LinesFormModalHook.js
Normal file
45
src/components/lines/hooks/LinesFormModalHook.js
Normal file
@ -0,0 +1,45 @@
|
||||
import { useState } from 'react';
|
||||
import useModal from '../../modal/ModalHook';
|
||||
import useLinesItemForm from './LinesItemFormHook';
|
||||
|
||||
const useLinesFormModal = (linesChangeHandle) => {
|
||||
const { isModalShow, showModal, hideModal } = useModal();
|
||||
const [currentId, setCurrentId] = useState(0);
|
||||
|
||||
const {
|
||||
item,
|
||||
validated,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
resetValidity,
|
||||
} = useLinesItemForm(currentId, linesChangeHandle);
|
||||
|
||||
const showModalDialog = (id) => {
|
||||
setCurrentId(id);
|
||||
resetValidity();
|
||||
showModal();
|
||||
};
|
||||
|
||||
const onClose = () => {
|
||||
setCurrentId(-1);
|
||||
hideModal();
|
||||
};
|
||||
|
||||
const onSubmit = async (event) => {
|
||||
if (await handleSubmit(event)) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
isFormModalShow: isModalShow,
|
||||
isFormValidated: validated,
|
||||
showFormModal: showModalDialog,
|
||||
currentItem: item,
|
||||
handleItemChange: handleChange,
|
||||
handleFormSubmit: onSubmit,
|
||||
handleFormClose: onClose,
|
||||
};
|
||||
};
|
||||
|
||||
export default useLinesFormModal;
|
30
src/components/lines/hooks/LinesHook.js
Normal file
30
src/components/lines/hooks/LinesHook.js
Normal file
@ -0,0 +1,30 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import LinesApiService from '../service/LinesApiService';
|
||||
|
||||
const useLines = (typeFilter) => {
|
||||
const [linesRefresh, setLinesRefresh] = useState(false);
|
||||
const [lines, setLines] = useState([]);
|
||||
const handleLinesChange = () => setLinesRefresh(!linesRefresh);
|
||||
|
||||
const getLines = async () => {
|
||||
let expand = '?_expand=type&_expand=ageRating';
|
||||
if (typeFilter) {
|
||||
expand = `${expand}&typeId=${typeFilter}`;
|
||||
}
|
||||
|
||||
const data = await LinesApiService.getAll(expand);
|
||||
setLines(data ?? []);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getLines();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [linesRefresh, typeFilter]);
|
||||
|
||||
return {
|
||||
lines,
|
||||
handleLinesChange,
|
||||
};
|
||||
};
|
||||
|
||||
export default useLines;
|
94
src/components/lines/hooks/LinesItemFormHook.js
Normal file
94
src/components/lines/hooks/LinesItemFormHook.js
Normal file
@ -0,0 +1,94 @@
|
||||
import { useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import getBase64FromFile from '../../utils/Base64';
|
||||
import LinesApiService from '../service/LinesApiService';
|
||||
import useLinesItem from './LinesItemHook';
|
||||
|
||||
const useLinesItemForm = (id, linesChangeHandle) => {
|
||||
const { item, setItem } = useLinesItem(id);
|
||||
|
||||
const [validated, setValidated] = useState(false);
|
||||
|
||||
const resetValidity = () => {
|
||||
setValidated(false);
|
||||
};
|
||||
|
||||
const getLineObject = (formData) => {
|
||||
const typeId = parseInt(formData.typeId, 10);
|
||||
const ageRatingId = parseInt(formData.ageRatingId, 10);
|
||||
const requiresSubscription = formData.requiresSubscription === true;
|
||||
const poster = formData.poster.startsWith('data:image') ? formData.poster : '';
|
||||
|
||||
return {
|
||||
title: formData.title,
|
||||
typeId,
|
||||
requiresSubscription,
|
||||
poster,
|
||||
description: formData.description,
|
||||
releaseDate: formData.releaseDate.toString(),
|
||||
country: formData.country,
|
||||
tagline: formData.tagline,
|
||||
director: formData.director,
|
||||
ageRatingId,
|
||||
video: formData.video,
|
||||
};
|
||||
};
|
||||
|
||||
const handleImageChange = async (event) => {
|
||||
const { files } = event.target;
|
||||
const file = await getBase64FromFile(files.item(0));
|
||||
setItem({
|
||||
...item,
|
||||
poster: file,
|
||||
});
|
||||
};
|
||||
|
||||
const handleChange = (event) => {
|
||||
if (event.target.type === 'file') {
|
||||
handleImageChange(event);
|
||||
return;
|
||||
}
|
||||
|
||||
const inputName = event.target.name;
|
||||
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
|
||||
|
||||
setItem({
|
||||
...item,
|
||||
[inputName]: inputValue,
|
||||
});
|
||||
};
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
const form = event.currentTarget;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const body = getLineObject(item);
|
||||
|
||||
if (form.checkValidity()) {
|
||||
if (id === undefined) {
|
||||
await LinesApiService.create(body);
|
||||
} else {
|
||||
await LinesApiService.update(id, body);
|
||||
}
|
||||
|
||||
if (linesChangeHandle) linesChangeHandle();
|
||||
toast.success('Элемент успешно сохранен', { id: 'LinesTable' });
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
setValidated(true);
|
||||
return false;
|
||||
};
|
||||
|
||||
return {
|
||||
item,
|
||||
validated,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
resetValidity,
|
||||
};
|
||||
};
|
||||
|
||||
export default useLinesItemForm;
|
42
src/components/lines/hooks/LinesItemHook.js
Normal file
42
src/components/lines/hooks/LinesItemHook.js
Normal file
@ -0,0 +1,42 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import LinesApiService from '../service/LinesApiService';
|
||||
|
||||
const useLinesItem = (id) => {
|
||||
const emptyItem = {
|
||||
id: '',
|
||||
title: '',
|
||||
typeId: 0,
|
||||
requiresSubscription: false,
|
||||
poster: '',
|
||||
description: '',
|
||||
releaseDate: '',
|
||||
country: '',
|
||||
tagline: '',
|
||||
director: '',
|
||||
ageRatingId: 0,
|
||||
video: '',
|
||||
};
|
||||
|
||||
const [item, setItem] = useState({ ...emptyItem });
|
||||
|
||||
const getItem = async (itemId = undefined) => {
|
||||
if (itemId && itemId > 0) {
|
||||
const data = await LinesApiService.get(itemId);
|
||||
setItem(data);
|
||||
} else {
|
||||
setItem({ ...emptyItem });
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getItem(id);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [id]);
|
||||
|
||||
return {
|
||||
item,
|
||||
setItem,
|
||||
};
|
||||
};
|
||||
|
||||
export default useLinesItem;
|
5
src/components/lines/service/LinesApiService.js
Normal file
5
src/components/lines/service/LinesApiService.js
Normal file
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const LinesApiService = new ApiService('movies');
|
||||
|
||||
export default LinesApiService;
|
72
src/components/lines/table/Lines.jsx
Normal file
72
src/components/lines/table/Lines.jsx
Normal file
@ -0,0 +1,72 @@
|
||||
import { Button } from 'react-bootstrap';
|
||||
import Select from '../../input/Select.jsx';
|
||||
import ModalConfirm from '../../modal/ModalConfirm.jsx';
|
||||
import ModalForm from '../../modal/ModalForm.jsx';
|
||||
import LinesItemForm from '../form/LinesItemForm.jsx';
|
||||
import useLinesDeleteModal from '../hooks/LinesDeleteModalHook';
|
||||
import useTypeFilter from '../hooks/LinesFilterHook';
|
||||
import useLinesFormModal from '../hooks/LinesFormModalHook';
|
||||
import useLines from '../hooks/LinesHook';
|
||||
import LinesTable from './LinesTable.jsx';
|
||||
import LinesTableRow from './LinesTableRow.jsx';
|
||||
|
||||
const Lines = () => {
|
||||
const { types, currentFilter, handleFilterChange } = useTypeFilter();
|
||||
|
||||
const { lines: movies, handleLinesChange } = useLines(currentFilter);
|
||||
|
||||
const {
|
||||
isDeleteModalShow,
|
||||
showDeleteModal,
|
||||
handleDeleteConfirm,
|
||||
handleDeleteCancel,
|
||||
} = useLinesDeleteModal(handleLinesChange);
|
||||
|
||||
const {
|
||||
isFormModalShow,
|
||||
isFormValidated,
|
||||
showFormModal,
|
||||
currentItem,
|
||||
handleItemChange,
|
||||
handleFormSubmit,
|
||||
handleFormClose,
|
||||
} = useLinesFormModal(handleLinesChange);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button className='mb-4' onClick={() => showFormModal()}>
|
||||
Добавить запись
|
||||
</Button>
|
||||
|
||||
<Select className='mt-2' values={types} label='Фильтр по типу'
|
||||
value={ parseInt(currentFilter, 10) } onChange={handleFilterChange} />
|
||||
|
||||
<LinesTable>
|
||||
{
|
||||
movies.map((movie, index) =>
|
||||
<LinesTableRow
|
||||
key={ movie.id }
|
||||
index={ index }
|
||||
line={ movie }
|
||||
onDelete={ () => showDeleteModal(movie.id) }
|
||||
onEdit={ () => showFormModal(movie.id) }
|
||||
/>)
|
||||
}
|
||||
</LinesTable>
|
||||
|
||||
<ModalConfirm show={isDeleteModalShow}
|
||||
onConfirm={handleDeleteConfirm} onClose={handleDeleteCancel}
|
||||
title='Удаление' message='Удалить элемент?' />
|
||||
|
||||
<ModalForm show={isFormModalShow} validated={isFormValidated}
|
||||
onSubmit={handleFormSubmit} onClose={handleFormClose}
|
||||
title='Редактирование'>
|
||||
|
||||
<LinesItemForm item={currentItem} handleChange={handleItemChange} />
|
||||
|
||||
</ModalForm>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Lines;
|
30
src/components/lines/table/LinesTable.jsx
Normal file
30
src/components/lines/table/LinesTable.jsx
Normal file
@ -0,0 +1,30 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Table } from 'react-bootstrap';
|
||||
|
||||
const LinesTable = ({ children }) => {
|
||||
return (
|
||||
<Table striped responsive>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">№</th>
|
||||
<th scope="col" className="w-25">Название</th>
|
||||
<th scope="col" className="w-25">Категория</th>
|
||||
<th scope="col" className="w-25">Требуется подписка</th>
|
||||
<th scope="col" className="w-25">Год производства</th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{children}
|
||||
</tbody >
|
||||
</Table >
|
||||
);
|
||||
};
|
||||
|
||||
LinesTable.propTypes = {
|
||||
children: PropTypes.node,
|
||||
};
|
||||
|
||||
export default LinesTable;
|
33
src/components/lines/table/LinesTableRow.jsx
Normal file
33
src/components/lines/table/LinesTableRow.jsx
Normal file
@ -0,0 +1,33 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { PencilFill, TrashFill } from 'react-bootstrap-icons';
|
||||
|
||||
const LinesTableRow = ({
|
||||
index, line, onDelete, onEdit,
|
||||
}) => {
|
||||
const handleAnchorClick = (event, action) => {
|
||||
event.preventDefault();
|
||||
action();
|
||||
};
|
||||
|
||||
return (
|
||||
<tr>
|
||||
<th scope="row">{index + 1}</th>
|
||||
<td>{ line.title }</td>
|
||||
<td>{ line.type.name }</td>
|
||||
<td>{ line.requiresSubscription ? '+' : '-' }</td>
|
||||
<td>{ line.releaseDate }</td>
|
||||
<td><a href="#" onClick={(event) => handleAnchorClick(event, onEdit)}><PencilFill /></a></td>
|
||||
<td><a href="#" onClick={(event) => handleAnchorClick(event, onDelete)}><TrashFill /></a></td>
|
||||
</tr>
|
||||
);
|
||||
};
|
||||
|
||||
LinesTableRow.propTypes = {
|
||||
index: PropTypes.number,
|
||||
line: PropTypes.object,
|
||||
onDelete: PropTypes.func,
|
||||
onEdit: PropTypes.func,
|
||||
onEditInPage: PropTypes.func,
|
||||
};
|
||||
|
||||
export default LinesTableRow;
|
25
src/components/login/LoginContext.jsx
Normal file
25
src/components/login/LoginContext.jsx
Normal file
@ -0,0 +1,25 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { createContext, useEffect, useReducer } from 'react';
|
||||
import { loadLoginData, loginReducer, saveLoginData } from './LoginReducer';
|
||||
|
||||
const LoginContext = createContext(null);
|
||||
|
||||
export const LoginProvider = ({ children }) => {
|
||||
const [loginData, dispatch] = useReducer(loginReducer, null, loadLoginData);
|
||||
|
||||
useEffect(() => {
|
||||
saveLoginData(loginData || null);
|
||||
}, [loginData]);
|
||||
|
||||
return (
|
||||
<LoginContext.Provider value={{ loginData, dispatch }}>
|
||||
{ children }
|
||||
</LoginContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
LoginProvider.propTypes = {
|
||||
children: PropTypes.node,
|
||||
};
|
||||
|
||||
export default LoginContext;
|
26
src/components/login/LoginHook.js
Normal file
26
src/components/login/LoginHook.js
Normal file
@ -0,0 +1,26 @@
|
||||
import { useContext } from 'react';
|
||||
import LoginContext from './LoginContext.jsx';
|
||||
import { loginAuthorize, loginLogout, loginUpdate } from './LoginReducer';
|
||||
import UsersApiService from '../authentification/service/UsersApiService';
|
||||
|
||||
const useLogin = () => {
|
||||
const { loginData, dispatch } = useContext(LoginContext);
|
||||
|
||||
const updateServerData = async (updatedLoginData) => {
|
||||
if (!loginData) {
|
||||
return;
|
||||
}
|
||||
|
||||
await UsersApiService.update(loginData.id, updatedLoginData);
|
||||
dispatch(loginUpdate(updatedLoginData));
|
||||
};
|
||||
|
||||
return {
|
||||
loginData,
|
||||
loginAuthorize: (login) => dispatch(loginAuthorize(login)),
|
||||
loginLogout: () => dispatch(loginLogout()),
|
||||
updateServerData,
|
||||
};
|
||||
};
|
||||
|
||||
export default useLogin;
|
46
src/components/login/LoginReducer.js
Normal file
46
src/components/login/LoginReducer.js
Normal file
@ -0,0 +1,46 @@
|
||||
const LOGIN_KEY = 'localLogin';
|
||||
const LOGIN_AUTHORIZE = 'login/authorize';
|
||||
const LOGIN_LOGOUT = 'login/logout';
|
||||
const LOGIN_UPDATE = 'login/update';
|
||||
|
||||
export const saveLoginData = (login) => {
|
||||
localStorage.setItem(LOGIN_KEY, JSON.stringify(login));
|
||||
};
|
||||
|
||||
export const loadLoginData = () => {
|
||||
const loginData = localStorage.getItem(LOGIN_KEY);
|
||||
if (loginData) {
|
||||
return JSON.parse(loginData);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export const loginReducer = (state, action) => {
|
||||
switch (action.type) {
|
||||
case LOGIN_AUTHORIZE: {
|
||||
return action.userData;
|
||||
}
|
||||
case LOGIN_UPDATE: {
|
||||
return action.userData;
|
||||
}
|
||||
case LOGIN_LOGOUT: {
|
||||
return null;
|
||||
}
|
||||
default: {
|
||||
throw Error(`Unknown action: ${action.type}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const loginAuthorize = (userData) => ({
|
||||
type: LOGIN_AUTHORIZE, userData,
|
||||
});
|
||||
|
||||
export const loginUpdate = (userData) => ({
|
||||
type: LOGIN_AUTHORIZE, userData,
|
||||
});
|
||||
|
||||
export const loginLogout = () => ({
|
||||
type: LOGIN_LOGOUT,
|
||||
});
|
41
src/components/modal/ModalConfirm.jsx
Normal file
41
src/components/modal/ModalConfirm.jsx
Normal file
@ -0,0 +1,41 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Button, Modal } from 'react-bootstrap';
|
||||
import { createPortal } from 'react-dom';
|
||||
|
||||
const ModalConfirm = ({
|
||||
show, title, message, onConfirm, onClose,
|
||||
}) => {
|
||||
return createPortal(
|
||||
<Modal show={show} backdrop='static' onHide={() => onClose()}>
|
||||
<Modal.Header className='pt-2 pb-2 ps-3 pe-3' closeButton>
|
||||
<Modal.Title>{title}</Modal.Title>
|
||||
</Modal.Header>
|
||||
|
||||
<Modal.Body>
|
||||
{message}
|
||||
</Modal.Body>
|
||||
|
||||
<Modal.Footer className='m-0 pt-2 pb-2 ps-3 pe-3 row justify-content-center'>
|
||||
<Button variant='secondary' className='col-5 m-0 me-2'
|
||||
onClick={() => onClose()}>
|
||||
Нет
|
||||
</Button>
|
||||
<Button variant='primary' className='col-5 m-0 ms-2'
|
||||
onClick={() => onConfirm()}>
|
||||
Да
|
||||
</Button>
|
||||
</Modal.Footer>
|
||||
</Modal>,
|
||||
document.body,
|
||||
);
|
||||
};
|
||||
|
||||
ModalConfirm.propTypes = {
|
||||
show: PropTypes.bool,
|
||||
title: PropTypes.string,
|
||||
message: PropTypes.string,
|
||||
onConfirm: PropTypes.func,
|
||||
onClose: PropTypes.func,
|
||||
};
|
||||
|
||||
export default ModalConfirm;
|
8
src/components/modal/ModalForm.css
Normal file
8
src/components/modal/ModalForm.css
Normal file
@ -0,0 +1,8 @@
|
||||
.modal-dialog {
|
||||
overflow-y: initial !important
|
||||
}
|
||||
|
||||
.form-modal-body {
|
||||
height: 80vh;
|
||||
overflow-y: auto;
|
||||
}
|
43
src/components/modal/ModalForm.jsx
Normal file
43
src/components/modal/ModalForm.jsx
Normal file
@ -0,0 +1,43 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Button, Form, Modal } from 'react-bootstrap';
|
||||
import { createPortal } from 'react-dom';
|
||||
import './ModalForm.css';
|
||||
|
||||
const ModalForm = ({
|
||||
show, title, validated, onSubmit, onClose, children,
|
||||
}) => {
|
||||
return createPortal(
|
||||
<Modal show={show} backdrop='static' onHide={() => onClose()}>
|
||||
<Modal.Header className='pt-2 pb-2 ps-3 pe-3' closeButton>
|
||||
<Modal.Title>{title}</Modal.Title>
|
||||
</Modal.Header>
|
||||
<Form className='m-0' noValidate validated={validated} onSubmit={onSubmit}>
|
||||
<Modal.Body className='form-modal-body'>
|
||||
{children}
|
||||
</Modal.Body>
|
||||
|
||||
<Modal.Footer className='m-0 pt-2 pb-2 ps-3 pe-3 row justify-content-center'>
|
||||
<Button variant='secondary' className='col-5 m-0 me-2'
|
||||
onClick={() => onClose()}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button variant='primary' className='col-5 m-0 ms-2' type='submit'>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Modal.Footer>
|
||||
</Form>
|
||||
</Modal>,
|
||||
document.body,
|
||||
);
|
||||
};
|
||||
|
||||
ModalForm.propTypes = {
|
||||
show: PropTypes.bool,
|
||||
title: PropTypes.string,
|
||||
validated: PropTypes.bool,
|
||||
onSubmit: PropTypes.func,
|
||||
onClose: PropTypes.func,
|
||||
children: PropTypes.node,
|
||||
};
|
||||
|
||||
export default ModalForm;
|
21
src/components/modal/ModalHook.js
Normal file
21
src/components/modal/ModalHook.js
Normal file
@ -0,0 +1,21 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
const useModal = () => {
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
|
||||
const showModalDialog = () => {
|
||||
setShowModal(true);
|
||||
};
|
||||
|
||||
const hideModalDialog = () => {
|
||||
setShowModal(false);
|
||||
};
|
||||
|
||||
return {
|
||||
isModalShow: showModal,
|
||||
showModal: showModalDialog,
|
||||
hideModal: hideModalDialog,
|
||||
};
|
||||
};
|
||||
|
||||
export default useModal;
|
@ -2,25 +2,22 @@ import { Col } from 'react-bootstrap';
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
const MovieBookmark = ({
|
||||
id, imageSrc, title, requiresSubscription, deleteCallback,
|
||||
movieData, deleteCallback,
|
||||
}) => {
|
||||
return (
|
||||
<Col xs={ 6 } sm={ 4 } lg={ 3 }>
|
||||
<a href={ `/videoplayer?id=${id}` } className="text-decoration-none">
|
||||
<img src={ imageSrc } className="img-fluid film-poster" alt="" />
|
||||
<h5 className="text-black mt-3">{ title }</h5>
|
||||
<h6 className="text-secondary">{ requiresSubscription ? 'По подписке' : 'Бесплатно' }</h6>
|
||||
<a href={ `/videoplayer/${movieData.id}` } className="text-decoration-none">
|
||||
<img src={ movieData.poster } className="img-fluid film-poster" alt="" />
|
||||
<h5 className="text-black mt-3">{ movieData.title }</h5>
|
||||
<h6 className="text-secondary">{ movieData.requiresSubscription ? 'По подписке' : 'Бесплатно' }</h6>
|
||||
</a>
|
||||
<button className="btn btn-outline-info" onClick={ () => deleteCallback(id) }>Удалить</button>
|
||||
<button className="btn btn-outline-info" onClick={ () => deleteCallback(movieData) }>Удалить</button>
|
||||
</Col>
|
||||
);
|
||||
};
|
||||
|
||||
MovieBookmark.propTypes = {
|
||||
id: PropTypes.number,
|
||||
imageSrc: PropTypes.string,
|
||||
title: PropTypes.string,
|
||||
requiresSubscription: PropTypes.bool,
|
||||
movieData: PropTypes.object,
|
||||
deleteCallback: PropTypes.func,
|
||||
};
|
||||
|
||||
|
15
src/components/movies/MovieDataHook.js
Normal file
15
src/components/movies/MovieDataHook.js
Normal file
@ -0,0 +1,15 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import LinesApiService from '../lines/service/LinesApiService';
|
||||
|
||||
const useMovieData = (movieId) => {
|
||||
const [movieData, setMovieData] = useState({ ageRating: {} });
|
||||
|
||||
useEffect(() => {
|
||||
LinesApiService.get(movieId, '?_expand=ageRating')
|
||||
.then((data) => setMovieData(data));
|
||||
});
|
||||
|
||||
return { movieData };
|
||||
};
|
||||
|
||||
export default useMovieData;
|
@ -4,11 +4,11 @@ import PropTypes from 'prop-types';
|
||||
import './MovieItem.css';
|
||||
|
||||
const MovieItem = ({
|
||||
id, imageSrc, title, requiresSubscription,
|
||||
id, imageSrc, title, requiresSubscription, handleClick,
|
||||
}) => {
|
||||
return (
|
||||
<Col xs={ 6 } sm={ 4 } lg={ 3 }>
|
||||
<a href={ `/videoplayer?id=${id}` } className="text-decoration-none">
|
||||
<a href='#' className="text-decoration-none" onClick={ (e) => handleClick(e, id) }>
|
||||
<img src={ imageSrc } className="img-fluid film-poster" alt="" />
|
||||
<h5 className="text-black mt-3">{ title }</h5>
|
||||
<h6 className="text-secondary">{ requiresSubscription ? 'По подписке' : 'Бесплатно' }</h6>
|
||||
@ -22,6 +22,7 @@ MovieItem.propTypes = {
|
||||
imageSrc: PropTypes.string,
|
||||
title: PropTypes.string,
|
||||
requiresSubscription: PropTypes.bool,
|
||||
handleClick: PropTypes.func,
|
||||
};
|
||||
|
||||
export default MovieItem;
|
||||
|
@ -2,3 +2,7 @@
|
||||
align-items: center;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.fixed-height {
|
||||
height: 62px;
|
||||
}
|
||||
|
@ -5,7 +5,11 @@ import {
|
||||
import PropTypes from 'prop-types';
|
||||
import { Film } from 'react-bootstrap-icons';
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
import { useContext, useEffect, useState } from 'react';
|
||||
|
||||
import './Navigation.css';
|
||||
import useLogin from '../login/LoginHook';
|
||||
import SubscriptionContext from '../subscription/SubscriptionContext.jsx';
|
||||
|
||||
const Navigation = ({ routes }) => {
|
||||
const location = useLocation();
|
||||
@ -17,9 +21,48 @@ const Navigation = ({ routes }) => {
|
||||
const pageProfile = routes.find((page) => { return page.title === 'Профиль'; });
|
||||
const pagePricing = routes.find((page) => { return page.title === 'Подписка'; });
|
||||
|
||||
const { loginData } = useLogin();
|
||||
let ProfileButton = (
|
||||
<>
|
||||
Ожидание...
|
||||
</>
|
||||
);
|
||||
|
||||
const [subscriptionActive2, setSubscriptionActive2] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (loginData === null) {
|
||||
setSubscriptionActive2(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (loginData.expirationDate === null) {
|
||||
setSubscriptionActive2(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setSubscriptionActive2(true);
|
||||
}, [loginData]);
|
||||
|
||||
if (loginData === null) {
|
||||
ProfileButton = (
|
||||
<Nav.Link className='me-3 my-nav-link' as={ Link } key={ pageLogin.path } eventKey={ pageLogin.path } to={ pageLogin.path ?? '/' }>
|
||||
Вход в аккаунт
|
||||
</Nav.Link>
|
||||
);
|
||||
} else {
|
||||
ProfileButton = (
|
||||
<Nav.Link className='me-3 my-nav-link' as={ Link } key={ pageProfile.path } eventKey={ pageProfile.path } to={ pageProfile.path ?? '/' }>
|
||||
Профиль
|
||||
</Nav.Link>
|
||||
);
|
||||
}
|
||||
|
||||
const { subscriptionActive } = useContext(SubscriptionContext);
|
||||
|
||||
return (
|
||||
<header>
|
||||
<Navbar fixed='top' expand='lg' bg='dark' data-bs-theme='dark' className='py-1'>
|
||||
<Navbar fixed='top' expand='lg' bg='dark' data-bs-theme='dark' className='py-1 fixed-height'>
|
||||
<Container fluid='md'>
|
||||
<Navbar.Brand as={ Link } to={indexPageLink?.path ?? '/'} className='align-items-center'>
|
||||
<Film className='d-inline-block align-middle pb-1' width="25" height="25"/>
|
||||
@ -35,19 +78,17 @@ const Navigation = ({ routes }) => {
|
||||
<Nav.Link className='me-3 my-nav-link' as={ Link } key={ pageAboutUs.path } eventKey={ pageAboutUs.path } to={ pageAboutUs.path ?? '/' }>
|
||||
Справка
|
||||
</Nav.Link>
|
||||
<Nav.Link className='me-3 my-nav-link' as={ Link } key={ pageLogin.path } eventKey={ pageLogin.path } to={ pageLogin.path ?? '/' }>
|
||||
Вход в аккаунт
|
||||
</Nav.Link>
|
||||
<Nav.Link className='me-3 my-nav-link' as={ Link } key={ pageProfile.path } eventKey={ pageProfile.path } to={ pageProfile.path ?? '/' }>
|
||||
Профиль
|
||||
</Nav.Link>
|
||||
<Nav.Link className='d-lg-none' as={ Link } key={ pagePricing.path } eventKey={ pagePricing.path } to={ pagePricing.path ?? '/' }>
|
||||
Купить подписку
|
||||
</Nav.Link>
|
||||
<Nav.Link className='d-none d-lg-inline' as={ Link } eventKey={ pagePricing.path } to={ pagePricing.path ?? '/' }>
|
||||
<Button variant='light'>Купить подписку</Button>
|
||||
</Nav.Link>
|
||||
|
||||
{ ProfileButton }
|
||||
{ !subscriptionActive2
|
||||
&& <Nav.Link className='d-lg-none' as={ Link } eventKey={ pagePricing.path } to={ pagePricing.path ?? '/' }>
|
||||
Купить подписку
|
||||
</Nav.Link>
|
||||
}
|
||||
{ !subscriptionActive2
|
||||
&& <Nav.Link className='d-none d-lg-inline' as={ Link } eventKey={ pagePricing.path } to={ pagePricing.path ?? '/' }>
|
||||
<Button variant='light'>Купить подписку</Button>
|
||||
</Nav.Link>
|
||||
}
|
||||
</Nav>
|
||||
</Navbar.Collapse>
|
||||
</Container>
|
||||
|
@ -1,33 +1,41 @@
|
||||
import { Col, Card } from 'react-bootstrap';
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
const PricingPlan = ({
|
||||
title, subtitle, price, description, isPrimary,
|
||||
}) => {
|
||||
const borderStyling = isPrimary ? 'border-primary border-3 pb-3' : 'border-1';
|
||||
const PricingPlan = ({ pricingPlanData, onBuySubscription }) => {
|
||||
const borderStyling = pricingPlanData.isPrimary ? 'border-primary border-3 pb-3' : 'border-1';
|
||||
|
||||
return (
|
||||
<Col xs={ isPrimary ? 9 : 8 } lg={ 4 } xl={ isPrimary ? 4 : 3 }>
|
||||
<Col xs={pricingPlanData.isPrimary ? 9 : 8} lg={4} xl={pricingPlanData.isPrimary ? 4 : 3}>
|
||||
<Card className={ borderStyling }>
|
||||
{ isPrimary && <Card.Header className="text-center text-primary">Самый популярный</Card.Header> }
|
||||
<Card.Body className={ `text-center ${isPrimary ? 'py-5' : 'py-4'}` }>
|
||||
<h4 className="card-title">{ title }</h4>
|
||||
<p className="lead card-subtitle">{ subtitle }</p>
|
||||
<p className={ `${isPrimary ? 'display-4' : 'display-5'} my-4 text-primary fw-bold` }>{ price } ₽</p>
|
||||
<p className="card-text mx-5 text-muted d-none d-lg-block">{ description }</p>
|
||||
<a href="#" className={ `btn btn-outline-primary btn-lg ${isPrimary ? 'mt-4' : 'mt-3'}` }>Купить</a>
|
||||
{ pricingPlanData.isPrimary && <Card.Header className="text-center text-primary">Самый популярный</Card.Header> }
|
||||
|
||||
<Card.Body className={ `text-center ${pricingPlanData.isPrimary ? 'py-5' : 'py-4'}` }>
|
||||
<h4 className="card-title">{ pricingPlanData.title }</h4>
|
||||
<p className="lead card-subtitle">{ pricingPlanData.subtitle }</p>
|
||||
<p className={ `${pricingPlanData.isPrimary ? 'display-4' : 'display-5'} my-4 text-primary fw-bold` }>{ pricingPlanData.price } ₽</p>
|
||||
<p className="card-text mx-5 text-muted d-none d-lg-block">{ pricingPlanData.description }</p>
|
||||
<a
|
||||
href="#"
|
||||
className={ `btn btn-outline-primary btn-lg ${pricingPlanData.isPrimary ? 'mt-4' : 'mt-3'}`}
|
||||
onClick={ (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
onBuySubscription(pricingPlanData.period);
|
||||
}}
|
||||
>
|
||||
Купить
|
||||
</a>
|
||||
</Card.Body>
|
||||
|
||||
</Card>
|
||||
</Col>
|
||||
);
|
||||
};
|
||||
|
||||
PricingPlan.propTypes = {
|
||||
title: PropTypes.string,
|
||||
subtitle: PropTypes.string,
|
||||
price: PropTypes.string,
|
||||
description: PropTypes.string,
|
||||
isPrimary: PropTypes.bool,
|
||||
pricingPlanData: PropTypes.object,
|
||||
onBuySubscription: PropTypes.func,
|
||||
};
|
||||
|
||||
export default PricingPlan;
|
||||
|
25
src/components/pricing/hooks/PricingPlansHook.js
Normal file
25
src/components/pricing/hooks/PricingPlansHook.js
Normal file
@ -0,0 +1,25 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import PricingApiService from '../service/PricingApiService';
|
||||
|
||||
const usePricingPlans = () => {
|
||||
const [pricingPlans, setPricingPlans] = useState([]);
|
||||
const [isPending, setIsPending] = useState(true);
|
||||
|
||||
const getPricing = async () => {
|
||||
const data = await PricingApiService.getAll();
|
||||
setPricingPlans(data ?? []);
|
||||
|
||||
setIsPending(false);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getPricing();
|
||||
}, []);
|
||||
|
||||
return {
|
||||
pricingPlans,
|
||||
isPending,
|
||||
};
|
||||
};
|
||||
|
||||
export default usePricingPlans;
|
5
src/components/pricing/service/PricingApiService.js
Normal file
5
src/components/pricing/service/PricingApiService.js
Normal file
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const PricingApiService = new ApiService('pricingPlans');
|
||||
|
||||
export default PricingApiService;
|
20
src/components/subscription/SubscriptionContext.jsx
Normal file
20
src/components/subscription/SubscriptionContext.jsx
Normal file
@ -0,0 +1,20 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { createContext, useState } from 'react';
|
||||
|
||||
const SubscriptionContext = createContext(false);
|
||||
|
||||
export const SubscriptionProvider = ({ children }) => {
|
||||
const [subscriptionActive, setSubscriptionActive] = useState(false);
|
||||
|
||||
return (
|
||||
<SubscriptionContext.Provider value={{ subscriptionActive, setSubscriptionActive }}>
|
||||
{ children }
|
||||
</SubscriptionContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
SubscriptionProvider.propTypes = {
|
||||
children: PropTypes.node,
|
||||
};
|
||||
|
||||
export default SubscriptionContext;
|
70
src/components/subscription/SubscriptionHook.js
Normal file
70
src/components/subscription/SubscriptionHook.js
Normal file
@ -0,0 +1,70 @@
|
||||
import { useContext, useEffect } from 'react';
|
||||
import SubscriptionContext from './SubscriptionContext.jsx';
|
||||
import useLogin from '../login/LoginHook';
|
||||
|
||||
const useSubscription = () => {
|
||||
const { subscriptionActive, setSubscriptionActive } = useContext(SubscriptionContext);
|
||||
const { loginData, updateServerData } = useLogin();
|
||||
|
||||
useEffect(() => {
|
||||
if (loginData === null) {
|
||||
setSubscriptionActive(false);
|
||||
return;
|
||||
}
|
||||
if (loginData.expirationDate === null) {
|
||||
setSubscriptionActive(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const currentDate = new Date().getTime();
|
||||
const expirationDate = Date.parse(loginData.expirationDate);
|
||||
|
||||
setSubscriptionActive(currentDate <= expirationDate);
|
||||
console.log(`subscriptionActive set to ${currentDate <= expirationDate}`);
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [loginData]);
|
||||
|
||||
const getExpirationDateFormatted = () => {
|
||||
if (!loginData) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (loginData.expirationDate === null) {
|
||||
return 'идёт отмена...';
|
||||
}
|
||||
|
||||
const timestamp = Date.parse(loginData.expirationDate);
|
||||
const expirationDate = new Date(timestamp);
|
||||
|
||||
return expirationDate.toLocaleString('ru-RU').split(', ')[0];
|
||||
};
|
||||
|
||||
const activateSubscription = (expirationDate) => {
|
||||
updateServerData({
|
||||
...loginData,
|
||||
expirationDate: expirationDate.toISOString(),
|
||||
});
|
||||
console.log('server data updated');
|
||||
};
|
||||
|
||||
const cancelSubscription = () => {
|
||||
if (!loginData) {
|
||||
return;
|
||||
}
|
||||
|
||||
updateServerData({
|
||||
...loginData,
|
||||
expirationDate: null,
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
subscriptionActive,
|
||||
getExpirationDateFormatted,
|
||||
activateSubscription,
|
||||
cancelSubscription,
|
||||
};
|
||||
};
|
||||
|
||||
export default useSubscription;
|
21
src/components/types/hooks/TypesHook.js
Normal file
21
src/components/types/hooks/TypesHook.js
Normal file
@ -0,0 +1,21 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import TypesApiService from '../service/TypesApiService';
|
||||
|
||||
const useTypes = () => {
|
||||
const [types, setTypes] = useState([]);
|
||||
|
||||
const getTypes = async () => {
|
||||
const data = await TypesApiService.getAll();
|
||||
setTypes(data ?? []);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getTypes();
|
||||
}, []);
|
||||
|
||||
return {
|
||||
types,
|
||||
};
|
||||
};
|
||||
|
||||
export default useTypes;
|
5
src/components/types/service/TypesApiService.js
Normal file
5
src/components/types/service/TypesApiService.js
Normal file
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const TypesApiService = new ApiService('types');
|
||||
|
||||
export default TypesApiService;
|
97
src/components/user/hooks/UserSubscriptionHook.js
Normal file
97
src/components/user/hooks/UserSubscriptionHook.js
Normal file
@ -0,0 +1,97 @@
|
||||
import toast from 'react-hot-toast';
|
||||
import { useEffect, useState } from 'react';
|
||||
import UsersApiService from '../../authentification/service/UsersApiService';
|
||||
|
||||
const useUserSubscription = (userId) => {
|
||||
const [subscriptionRefresh, setSubscriptionRefresh] = useState(false);
|
||||
const [subscriptionInitialized, setSubscriptionInitialized] = useState(false);
|
||||
const [currentUser, setCurrentUser] = useState({});
|
||||
const [isSubscriptionActive, setIsSubscriptionActive] = useState(false);
|
||||
const handleSubscriptionChange = () => setSubscriptionRefresh(!subscriptionRefresh);
|
||||
|
||||
const handleChange = async (userObject) => {
|
||||
if (userId === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
await UsersApiService.update(userId, userObject);
|
||||
|
||||
handleSubscriptionChange();
|
||||
toast.success('Статус подписки успешно обновлен');
|
||||
};
|
||||
|
||||
const getExpirationDate = () => {
|
||||
return currentUser.expirationDate;
|
||||
};
|
||||
|
||||
const getExpirationDateFormatted = () => {
|
||||
if (currentUser.expirationDate === null) {
|
||||
return 'идёт отмена...';
|
||||
}
|
||||
|
||||
const timestamp = Date.parse(currentUser.expirationDate);
|
||||
const expirationDate = new Date(timestamp);
|
||||
|
||||
return expirationDate.toLocaleString('ru-RU').split(', ')[0];
|
||||
};
|
||||
|
||||
const hasActiveSubscription = () => {
|
||||
if (currentUser.expirationDate === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const currentDate = new Date().getTime();
|
||||
const expirationDate = Date.parse(getExpirationDate());
|
||||
|
||||
return currentDate <= expirationDate;
|
||||
};
|
||||
|
||||
const setSubscription = (newExpirationDate) => {
|
||||
currentUser.expirationDate = newExpirationDate.toISOString();
|
||||
handleChange(currentUser);
|
||||
};
|
||||
|
||||
const cancelSubscription = () => {
|
||||
currentUser.expirationDate = null;
|
||||
|
||||
handleChange(currentUser);
|
||||
};
|
||||
|
||||
const refreshUserData = async (id) => {
|
||||
if (id === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await UsersApiService.get(id);
|
||||
|
||||
localStorage.setItem('currentUser', JSON.stringify(data));
|
||||
setCurrentUser(data);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
refreshUserData(userId);
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [subscriptionRefresh]);
|
||||
|
||||
useEffect(() => {
|
||||
if (Object.keys(currentUser).length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubscriptionActive(hasActiveSubscription());
|
||||
setSubscriptionInitialized(true);
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [currentUser]);
|
||||
|
||||
return {
|
||||
subscriptionInitialized,
|
||||
isSubscriptionActive,
|
||||
getExpirationDateFormatted,
|
||||
cancelSubscription,
|
||||
setSubscription,
|
||||
};
|
||||
};
|
||||
|
||||
export default useUserSubscription;
|
15
src/components/utils/Base64.js
Normal file
15
src/components/utils/Base64.js
Normal file
@ -0,0 +1,15 @@
|
||||
const getBase64FromFile = async (file) => {
|
||||
const reader = new FileReader();
|
||||
return new Promise((resolve, reject) => {
|
||||
reader.onloadend = () => {
|
||||
const fileContent = reader.result;
|
||||
resolve(fileContent);
|
||||
};
|
||||
reader.onerror = () => {
|
||||
reject(new Error('Oops, something went wrong with the file reader.'));
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
};
|
||||
|
||||
export default getBase64FromFile;
|
42
src/components/wishlist/Wishlist.jsx
Normal file
42
src/components/wishlist/Wishlist.jsx
Normal file
@ -0,0 +1,42 @@
|
||||
import { Container, Row, Button } from 'react-bootstrap';
|
||||
import useWishlist from './WishlistHook';
|
||||
import MovieBookmark from '../movies/MovieBookmark.jsx';
|
||||
|
||||
const Wishlist = () => {
|
||||
const {
|
||||
wishlist,
|
||||
removeFromWishlist,
|
||||
clearWishlist,
|
||||
} = useWishlist();
|
||||
|
||||
return (
|
||||
<Container fluid="md" className="py-4 mb-4">
|
||||
|
||||
<div className="text-center">
|
||||
<h2>Избранное</h2>
|
||||
<p className="lead text-muted">Фильмы и сериары, отмеченные как `посмотреть позже`</p>
|
||||
</div>
|
||||
|
||||
<Row className="gx-5 gy-5 my-3">
|
||||
{
|
||||
wishlist.map((wishlistItem) =>
|
||||
<MovieBookmark
|
||||
key={ wishlistItem.id }
|
||||
movieData={ wishlistItem }
|
||||
deleteCallback={ removeFromWishlist }
|
||||
/>)
|
||||
}
|
||||
</Row>
|
||||
|
||||
{ wishlist.length !== 0
|
||||
? <Button className='mb-4' onClick={() => clearWishlist()}>
|
||||
Очистить список избранного
|
||||
</Button>
|
||||
: <p className="display-5 my-5">Список желаемого пуст</p>
|
||||
}
|
||||
|
||||
</Container>
|
||||
);
|
||||
};
|
||||
|
||||
export default Wishlist;
|
30
src/components/wishlist/WishlistContext.jsx
Normal file
30
src/components/wishlist/WishlistContext.jsx
Normal file
@ -0,0 +1,30 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import {
|
||||
createContext,
|
||||
useEffect,
|
||||
useReducer,
|
||||
} from 'react';
|
||||
|
||||
import { wishlistReducer, loadWishlist, saveWishlist } from './WishlistReducer';
|
||||
|
||||
const WishlistContext = createContext(null);
|
||||
|
||||
export const WishlistProvider = ({ children }) => {
|
||||
const [wishlist, dispatch] = useReducer(wishlistReducer, [], loadWishlist);
|
||||
|
||||
useEffect(() => {
|
||||
saveWishlist(wishlist || []);
|
||||
}, [wishlist]);
|
||||
|
||||
return (
|
||||
<WishlistContext.Provider value={{ wishlist, dispatch }}>
|
||||
{children}
|
||||
</WishlistContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
WishlistProvider.propTypes = {
|
||||
children: PropTypes.node,
|
||||
};
|
||||
|
||||
export default WishlistContext;
|
16
src/components/wishlist/WishlistHook.js
Normal file
16
src/components/wishlist/WishlistHook.js
Normal file
@ -0,0 +1,16 @@
|
||||
import { useContext } from 'react';
|
||||
import { wishlistAdd, wishlistClear, wishlistRemove } from './WishlistReducer';
|
||||
import WishlistContext from './WishlistContext.jsx';
|
||||
|
||||
const useWishlist = () => {
|
||||
const { wishlist, dispatch } = useContext(WishlistContext);
|
||||
|
||||
return {
|
||||
wishlist,
|
||||
addToWishlist: (item) => dispatch(wishlistAdd(item)),
|
||||
removeFromWishlist: (item) => dispatch(wishlistRemove(item)),
|
||||
clearWishlist: () => dispatch(wishlistClear()),
|
||||
};
|
||||
};
|
||||
|
||||
export default useWishlist;
|
60
src/components/wishlist/WishlistReducer.js
Normal file
60
src/components/wishlist/WishlistReducer.js
Normal file
@ -0,0 +1,60 @@
|
||||
const addToWishlist = (wishlist, movie) => {
|
||||
const existsMovie = wishlist.find((wishlistItem) => wishlistItem.id === movie.id);
|
||||
if (existsMovie !== undefined) {
|
||||
return wishlist;
|
||||
}
|
||||
|
||||
return [...wishlist, movie];
|
||||
};
|
||||
|
||||
const removeFromWishlist = (wishlist, movie) => {
|
||||
return wishlist.filter((wishlistItem) => wishlistItem.id !== movie.id);
|
||||
};
|
||||
|
||||
const WISHLIST_KEY = 'localWishlist';
|
||||
const WISHLIST_ADD = 'wishlist/add';
|
||||
const WISHLIST_REMOVE = 'wishlist/remove';
|
||||
const WISHLIST_CLEAR = 'wishlist/clear';
|
||||
|
||||
export const saveWishlist = (wishlist) => {
|
||||
localStorage.setItem(WISHLIST_KEY, JSON.stringify(wishlist));
|
||||
};
|
||||
|
||||
export const loadWishlist = (initialValue = []) => {
|
||||
const wishlistData = localStorage.getItem(WISHLIST_KEY);
|
||||
if (wishlistData) {
|
||||
return JSON.parse(wishlistData);
|
||||
}
|
||||
|
||||
return initialValue;
|
||||
};
|
||||
|
||||
export const wishlistReducer = (wishlist, action) => {
|
||||
const { movie } = action;
|
||||
switch (action.type) {
|
||||
case WISHLIST_ADD: {
|
||||
return addToWishlist(wishlist, movie);
|
||||
}
|
||||
case WISHLIST_REMOVE: {
|
||||
return removeFromWishlist(wishlist, movie);
|
||||
}
|
||||
case WISHLIST_CLEAR: {
|
||||
return [];
|
||||
}
|
||||
default: {
|
||||
throw Error(`Unknown action: ${action.type}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const wishlistAdd = (movie) => ({
|
||||
type: WISHLIST_ADD, movie,
|
||||
});
|
||||
|
||||
export const wishlistRemove = (movie) => ({
|
||||
type: WISHLIST_REMOVE, movie,
|
||||
});
|
||||
|
||||
export const wishlistClear = () => ({
|
||||
type: WISHLIST_CLEAR,
|
||||
});
|
@ -37,7 +37,7 @@ const routes = [
|
||||
title: 'Вход в аккаунт',
|
||||
},
|
||||
{
|
||||
path: '/videoplayer',
|
||||
path: '/videoplayer/:id?',
|
||||
element: <PageVideoplayer />,
|
||||
title: 'Просмотр',
|
||||
},
|
||||
|
@ -1,172 +1,19 @@
|
||||
import {
|
||||
Container, Button, Table, Form, Modal,
|
||||
} from 'react-bootstrap';
|
||||
|
||||
import {
|
||||
PencilFill, TrashFill,
|
||||
} from 'react-bootstrap-icons';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Container } from 'react-bootstrap';
|
||||
import Lines from '../components/lines/table/Lines.jsx';
|
||||
|
||||
const PageAdminPanel = () => {
|
||||
const [shouldShowModal, setShowModal] = useState(false);
|
||||
|
||||
const addMovieHandler = (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
setShowModal(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<section id="administration">
|
||||
<Container fluid="md" className="py-4 mb-4">
|
||||
<div className="text-center">
|
||||
<h2>Страница администратора</h2>
|
||||
<p className="lead text-muted">Выполнение CRUD-операций над фильмами или сериалами</p>
|
||||
</div>
|
||||
<section id="administration">
|
||||
<Container fluid="md" className="py-4 mb-4">
|
||||
<div className="text-center">
|
||||
<h2>Страница администратора</h2>
|
||||
<p className="lead text-muted">Выполнение CRUD-операций над фильмами или сериалами</p>
|
||||
</div>
|
||||
|
||||
<Button id="addMovie" className="mb-4" onClick={ addMovieHandler }>Добавить запись</Button>
|
||||
<Lines />
|
||||
|
||||
<Table id="items-table" striped>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">№</th>
|
||||
<th scope="col" className="w-25">Название</th>
|
||||
<th scope="col" className="w-25">Категория</th>
|
||||
<th scope="col" className="w-25 d-none d-sm-table-cell">Требуется подписка</th>
|
||||
<th scope="col" className="w-25 d-none d-sm-table-cell">Год производства</th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</tr></thead>
|
||||
|
||||
<tbody>
|
||||
<tr id="line-1">
|
||||
<th scope="row">1</th>
|
||||
<td>Американский психопат</td>
|
||||
<td>Фильм</td>
|
||||
<td className="d-none d-sm-table-cell">+</td>
|
||||
<td className="d-none d-sm-table-cell">1999</td>
|
||||
<td><a href="#"><PencilFill /></a></td>
|
||||
<td><a href="#"><TrashFill /></a></td>
|
||||
</tr>
|
||||
|
||||
<tr id="line-2">
|
||||
<th scope="row">2</th>
|
||||
<td>Драйв</td>
|
||||
<td>Фильм</td>
|
||||
<td className="d-none d-sm-table-cell">-</td>
|
||||
<td className="d-none d-sm-table-cell">1999</td>
|
||||
<td><a href="#"><PencilFill /></a></td>
|
||||
<td><a href="#"><TrashFill /></a></td>
|
||||
</tr>
|
||||
|
||||
<tr id="line-3">
|
||||
<th scope="row">3</th>
|
||||
<td>Острые козырьки</td>
|
||||
<td>Сериал</td>
|
||||
<td className="d-none d-sm-table-cell">-</td>
|
||||
<td className="d-none d-sm-table-cell">1999</td>
|
||||
<td><a href="#"><PencilFill /></a></td>
|
||||
<td><a href="#"><TrashFill /></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</Table>
|
||||
|
||||
</Container>
|
||||
</section>
|
||||
|
||||
<Modal id="items-update" show={ shouldShowModal } onHide={ () => setShowModal(false) }>
|
||||
<Form id="items-form">
|
||||
<Modal.Header closeButton>
|
||||
<Modal.Title className="fs-5" id="items-update-title"><h1></h1></Modal.Title>
|
||||
</Modal.Header>
|
||||
|
||||
<Modal.Body>
|
||||
<div className="text-center">
|
||||
<img id="image-preview" src="https://via.placeholder.com/200" className="image-preview"
|
||||
alt="placeholder" />
|
||||
</div>
|
||||
|
||||
<Form.Control id="items-line-id" type="number" hidden />
|
||||
|
||||
<Form.Group className="mb-2">
|
||||
<Form.Label>Название</Form.Label>
|
||||
<Form.Control type="text" id="title" required />
|
||||
</Form.Group>
|
||||
|
||||
<Form.Group className="mb-3">
|
||||
<Form.Label>Тип</Form.Label>
|
||||
<Form.Select id="type" required>
|
||||
<option value="Фильм" selected>Фильм</option>
|
||||
<option value="Сериал">Сериал</option>
|
||||
</Form.Select>
|
||||
</Form.Group>
|
||||
|
||||
<Form.Group className="mb-3">
|
||||
<Form.Check type="checkbox" id="requiresSubscription" label="Требуется подписка" />
|
||||
</Form.Group>
|
||||
|
||||
<Form.Group className="mb-2">
|
||||
<Form.Label>Постер</Form.Label>
|
||||
<Form.Control type="file" id="image" accept="image/*" />
|
||||
</Form.Group>
|
||||
|
||||
<Form.Group className="mb-2">
|
||||
<Form.Label>Описание</Form.Label>
|
||||
<Form.Control id="description" as="textarea" rows={ 4 } />
|
||||
</Form.Group>
|
||||
|
||||
<Form.Group className="mb-2">
|
||||
<Form.Label>Год производства</Form.Label>
|
||||
<Form.Control type="number" id="releaseDate" min="1900" step="1" required />
|
||||
</Form.Group>
|
||||
|
||||
<Form.Group className="mb-2">
|
||||
<Form.Label>Страна</Form.Label>
|
||||
<Form.Control type="text" id="country" required />
|
||||
</Form.Group>
|
||||
|
||||
<Form.Group className="mb-2">
|
||||
<Form.Label>Слоган</Form.Label>
|
||||
<Form.Control type="text" id="tagline" required />
|
||||
</Form.Group>
|
||||
|
||||
<Form.Group className="mb-2">
|
||||
<Form.Label>Режиссер</Form.Label>
|
||||
<Form.Control type="text" id="director" required />
|
||||
</Form.Group>
|
||||
|
||||
<Form.Group className="mb-3">
|
||||
<Form.Label>Возрастное ограничение</Form.Label>
|
||||
<Form.Select id="ageRating" required>
|
||||
<option value="0+" selected>0+</option>
|
||||
<option value="6+">6+</option>
|
||||
<option value="12+">12+</option>
|
||||
<option value="16+">16+</option>
|
||||
<option value="18+">18+</option>
|
||||
</Form.Select>
|
||||
</Form.Group>
|
||||
|
||||
<Form.Group className="mb-2">
|
||||
<Form.Label>URL видео</Form.Label>
|
||||
<Form.Control type="text" id="video" required />
|
||||
</Form.Group>
|
||||
</Modal.Body>
|
||||
|
||||
<Modal.Footer>
|
||||
<Button variant="secondary" onClick={ () => setShowModal(false) }>
|
||||
Закрыть
|
||||
</Button>
|
||||
|
||||
<Button variant="primary" onClick={ () => setShowModal(false) }>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Modal.Footer>
|
||||
</Form>
|
||||
</Modal>
|
||||
</>
|
||||
</Container>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
|
@ -1,21 +1,30 @@
|
||||
import { Container, Row } from 'react-bootstrap';
|
||||
|
||||
import logoAmericanPsycho from '../assets/main-page/posters/AmericanPsycho.jpg';
|
||||
import logoDrive from '../assets/main-page/posters/Drive.jpg';
|
||||
import logoFightClub from '../assets/main-page/posters/FightClub.png';
|
||||
import logoJoker from '../assets/main-page/posters/Joker.jpg';
|
||||
import logoNoCountryForOldMen from '../assets/main-page/posters/NoCountryForOldMen.jpg';
|
||||
import logoPusher from '../assets/main-page/posters/Pusher.png';
|
||||
import logoScarface from '../assets/main-page/posters/Scarface.png';
|
||||
import logoBladeRunner2049 from '../assets/main-page/posters/BladeRunner2049.jpg';
|
||||
import logoBetterCallSaul from '../assets/main-page/posters/BetterCallSaul.png';
|
||||
import logoPeakyBlinders from '../assets/main-page/posters/PeakyBlinders.png';
|
||||
import logoBreakingBad from '../assets/main-page/posters/BreakingBad.png';
|
||||
import logoSopranos from '../assets/main-page/posters/Sopranos.png';
|
||||
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import toast from 'react-hot-toast';
|
||||
import useLines from '../components/lines/hooks/LinesHook';
|
||||
import MovieItem from '../components/movies/MovieItem.jsx';
|
||||
import useLogin from '../components/login/LoginHook';
|
||||
|
||||
const PageIndex = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { loginData } = useLogin();
|
||||
|
||||
const showMoviePage = (event, movieId) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
if (!loginData) {
|
||||
toast.error('Для просмотра фильма необходимо войти в аккаунт');
|
||||
navigate('/login');
|
||||
return;
|
||||
}
|
||||
|
||||
navigate(`/videoplayer/${movieId}`);
|
||||
};
|
||||
|
||||
const { lines: movies } = useLines();
|
||||
|
||||
return (
|
||||
<>
|
||||
<section id="movies">
|
||||
@ -27,14 +36,17 @@ const PageIndex = () => {
|
||||
</div>
|
||||
|
||||
<Row className="gx-5 gy-5 my-3">
|
||||
<MovieItem id={ 1 } imageSrc={ logoAmericanPsycho } title="Американский психопат" requiresSubscription={ true } />
|
||||
<MovieItem id={ 2 } imageSrc={ logoDrive } title="Драйв" requiresSubscription={ false } />
|
||||
<MovieItem id={ 3 } imageSrc={ logoFightClub } title="Бойцовский клуб" requiresSubscription={ true } />
|
||||
<MovieItem id={ 4 } imageSrc={ logoJoker } title="Джокер" requiresSubscription={ true } />
|
||||
<MovieItem id={ 5 } imageSrc={ logoNoCountryForOldMen } title="Старикам здесь не место" requiresSubscription={ false } />
|
||||
<MovieItem id={ 6 } imageSrc={ logoPusher } title="Дилер" requiresSubscription={ true } />
|
||||
<MovieItem id={ 7 } imageSrc={ logoScarface } title="Лицо со шрамом" requiresSubscription={ true } />
|
||||
<MovieItem id={ 8 } imageSrc={ logoBladeRunner2049 } title="Бегущий по лезвию - 2049" requiresSubscription={ false } />
|
||||
{
|
||||
movies.filter((item) => item.type.name === 'Фильм').map((movie) =>
|
||||
<MovieItem
|
||||
key = { movie.id }
|
||||
id={ movie.id }
|
||||
imageSrc={ movie.poster }
|
||||
title={ movie.title }
|
||||
requiresSubscription={ movie.requiresSubscription }
|
||||
handleClick={ showMoviePage }
|
||||
/>)
|
||||
}
|
||||
</Row>
|
||||
|
||||
</Container>
|
||||
@ -49,10 +61,17 @@ const PageIndex = () => {
|
||||
</div>
|
||||
|
||||
<Row className="gx-5 gy-5 mt-3 mb-5">
|
||||
<MovieItem id={ 1 } imageSrc={ logoBetterCallSaul } title="Лучше звоните Солу" requiresSubscription={ true } />
|
||||
<MovieItem id={ 1 } imageSrc={ logoPeakyBlinders } title="Острые козырьки" requiresSubscription={ false } />
|
||||
<MovieItem id={ 1 } imageSrc={ logoBreakingBad } title="Во все тяжкие" requiresSubscription={ true } />
|
||||
<MovieItem id={ 1 } imageSrc={ logoSopranos } title="Клан Сопрано" requiresSubscription={ false } />
|
||||
{
|
||||
movies.filter((item) => item.type.name === 'Сериал').map((movie) =>
|
||||
<MovieItem
|
||||
key = { movie.id }
|
||||
id={ movie.id }
|
||||
imageSrc={ movie.poster }
|
||||
title={ movie.title }
|
||||
requiresSubscription={ movie.requiresSubscription }
|
||||
handleClick={ showMoviePage }
|
||||
/>)
|
||||
}
|
||||
</Row>
|
||||
</Container>
|
||||
</section>
|
||||
|
@ -1,5 +1,5 @@
|
||||
import {
|
||||
Container, Row, Col, Form, InputGroup, Button, Card, Modal,
|
||||
Container, Row, Col, Form, InputGroup, Button, Card,
|
||||
} from 'react-bootstrap';
|
||||
|
||||
import {
|
||||
@ -7,17 +7,27 @@ import {
|
||||
} from 'react-bootstrap-icons';
|
||||
|
||||
import { useState } from 'react';
|
||||
import ForgotPasswordModal from '../components/authentification/modals/ForgotPasswordModal.jsx';
|
||||
import useUserLoginForm from '../components/authentification/hooks/UserLoginFormHook';
|
||||
|
||||
const PageLogin = () => {
|
||||
const [shouldShowForgotModal, setShowForgotModal] = useState(false);
|
||||
|
||||
const forgotPasswordHandler = (e) => {
|
||||
const { validated, handleSubmit, handleChange } = useUserLoginForm();
|
||||
|
||||
const handleForgotPassword = (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
setShowForgotModal(true);
|
||||
};
|
||||
|
||||
const handleLogin = async (event) => {
|
||||
await handleSubmit(event);
|
||||
};
|
||||
|
||||
// <InputGroup.Text><EyeFill /></InputGroup.Text>
|
||||
|
||||
return (
|
||||
<>
|
||||
<section id="login">
|
||||
@ -36,12 +46,12 @@ const PageLogin = () => {
|
||||
<p className="lead my-auto ms-3 text-primary">Вход</p>
|
||||
</div>
|
||||
|
||||
<Form className="my-3">
|
||||
<Form className="my-3" noValidate validated={ validated } onSubmit={ handleLogin }>
|
||||
<Form.Group>
|
||||
<Form.Label>Электронная почта</Form.Label>
|
||||
<InputGroup className="mb-3">
|
||||
<InputGroup.Text><EnvelopeFill /></InputGroup.Text>
|
||||
<Form.Control type="email" id="email" placeholder="myemail@mail.com" />
|
||||
<Form.Control name="email" type="email" placeholder="myemail@mail.com" onChange={handleChange} required/>
|
||||
</InputGroup>
|
||||
</Form.Group>
|
||||
|
||||
@ -49,8 +59,8 @@ const PageLogin = () => {
|
||||
<Form.Label>Пароль</Form.Label>
|
||||
<InputGroup className="mb-3">
|
||||
<InputGroup.Text><LockFill /></InputGroup.Text>
|
||||
<Form.Control type="password" id="password" />
|
||||
<InputGroup.Text><EyeFill /></InputGroup.Text>
|
||||
<Form.Control name="password" type="password" onChange={handleChange} required />
|
||||
|
||||
</InputGroup>
|
||||
</Form.Group>
|
||||
|
||||
@ -61,14 +71,14 @@ const PageLogin = () => {
|
||||
</div>
|
||||
|
||||
<div className="forgot">
|
||||
<a onClick={ forgotPasswordHandler } href='/' id="forgotPassword" className="text-decoration-none">
|
||||
<a onClick={ handleForgotPassword } href='/' id="forgotPassword" className="text-decoration-none">
|
||||
<small>Забыли пароль?</small>
|
||||
</a>
|
||||
</div>
|
||||
</Form.Group>
|
||||
|
||||
<div className="text-center mt-5">
|
||||
<Button variant="primary">Войти</Button>
|
||||
<Button variant="primary" type='submit'>Войти</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</Card.Body>
|
||||
@ -78,27 +88,10 @@ const PageLogin = () => {
|
||||
</Container>
|
||||
</section>
|
||||
|
||||
<Modal show={ shouldShowForgotModal } onHide={ () => setShowForgotModal(false) }>
|
||||
<Modal.Header closeButton>
|
||||
<Modal.Title>Восстановление пароля</Modal.Title>
|
||||
</Modal.Header>
|
||||
|
||||
<Modal.Body className="mb-3">
|
||||
<p>В поле ниже напишите адрес электроннной почты, с которой была совершена
|
||||
регистрация. На этот адрес придёт письмо с дальнейшеми указаниями.</p>
|
||||
|
||||
<Form.Group>
|
||||
<Form.Label>Адрес электронной почты:</Form.Label>
|
||||
<Form.Control type="email" placeholder="myemail@mail.com" />
|
||||
</Form.Group>
|
||||
</Modal.Body>
|
||||
|
||||
<Modal.Footer>
|
||||
<Button variant="primary" onClick={ () => setShowForgotModal(false) }>
|
||||
Отправить
|
||||
</Button>
|
||||
</Modal.Footer>
|
||||
</Modal>
|
||||
<ForgotPasswordModal
|
||||
shouldShowModal={ shouldShowForgotModal }
|
||||
hideModal={ () => setShowForgotModal(false) }
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
@ -2,13 +2,52 @@ import {
|
||||
Container, Row,
|
||||
} from 'react-bootstrap';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
import diamondIcon from '../assets/pricing/diamond.png';
|
||||
import noAdsIcon from '../assets/pricing/no-ads.png';
|
||||
|
||||
import Priveledge from '../components/pricing/Priveledge.jsx';
|
||||
import PricingPlan from '../components/pricing/PricingPlan.jsx';
|
||||
import usePricingPlans from '../components/pricing/hooks/PricingPlansHook';
|
||||
import useLogin from '../components/login/LoginHook';
|
||||
import useSubscription from '../components/subscription/SubscriptionHook';
|
||||
|
||||
const PagePricing = () => {
|
||||
const { pricingPlans, isPending } = usePricingPlans();
|
||||
|
||||
const { loginData } = useLogin();
|
||||
const { subscriptionActive, activateSubscription } = useSubscription();
|
||||
|
||||
const handleBuySubscription = (period) => {
|
||||
const expirationDate = new Date();
|
||||
|
||||
expirationDate.setDate(expirationDate.getDate() + period.days);
|
||||
expirationDate.setMonth(expirationDate.getMonth() + period.months);
|
||||
expirationDate.setFullYear(expirationDate.getFullYear() + period.years);
|
||||
|
||||
activateSubscription(expirationDate);
|
||||
};
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (!loginData) {
|
||||
navigate('/Login');
|
||||
}
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [loginData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (subscriptionActive) {
|
||||
navigate('/Profile');
|
||||
}
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [subscriptionActive]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<section id="subscription-features">
|
||||
@ -33,14 +72,15 @@ const PagePricing = () => {
|
||||
</div>
|
||||
|
||||
<Row className="my-5 justify-content-center align-items-center gy-3">
|
||||
<PricingPlan title="Большой Шлёппа" subtitle="Подписка на неделю" price="49,99"
|
||||
description="Попробуйте и решите, нравится ли вам наш сервис" isPrimary={ false } />
|
||||
{ isPending && <p className="display-1 my-5">Загрузка...</p> }
|
||||
|
||||
<PricingPlan title="Базированный гигачад" subtitle="Подписка на месяц" price="149,99"
|
||||
description="Для тех, кто очень любит смотреть фильмы и сериалы по вечерам" isPrimary={ true } />
|
||||
|
||||
<PricingPlan title="Райан Гослинг" subtitle="Подписка на год" price="799,99"
|
||||
description="Если вдруг захотите остаться с нами подольше" isPrimary={ false } />
|
||||
{pricingPlans.map((pricingPlan) => (
|
||||
<PricingPlan
|
||||
key={pricingPlan.id}
|
||||
pricingPlanData={pricingPlan}
|
||||
onBuySubscription={handleBuySubscription}
|
||||
/>
|
||||
))}
|
||||
</Row>
|
||||
</Container>
|
||||
</section>
|
||||
|
@ -1,11 +1,46 @@
|
||||
import { Container, Row } from 'react-bootstrap';
|
||||
import MovieBookmark from '../components/movies/MovieBookmark.jsx';
|
||||
|
||||
import logoAmericanPsycho from '../assets/main-page/posters/AmericanPsycho.jpg';
|
||||
import logoDrive from '../assets/main-page/posters/Drive.jpg';
|
||||
import logoPeakyBlinders from '../assets/main-page/posters/PeakyBlinders.png';
|
||||
import { Container } from 'react-bootstrap';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useEffect } from 'react';
|
||||
import Wishlist from '../components/wishlist/Wishlist.jsx';
|
||||
import useWishlist from '../components/wishlist/WishlistHook';
|
||||
import useLogin from '../components/login/LoginHook';
|
||||
import useSubscription from '../components/subscription/SubscriptionHook';
|
||||
|
||||
const PageProfile = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { loginData, loginLogout } = useLogin();
|
||||
|
||||
const {
|
||||
subscriptionActive,
|
||||
getExpirationDateFormatted,
|
||||
cancelSubscription,
|
||||
} = useSubscription();
|
||||
|
||||
useEffect(() => {
|
||||
if (loginData === null) {
|
||||
navigate('/login');
|
||||
}
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [loginData]);
|
||||
|
||||
const { clearWishlist } = useWishlist();
|
||||
|
||||
const handleLogout = () => {
|
||||
loginLogout();
|
||||
|
||||
navigate('/login');
|
||||
clearWishlist();
|
||||
};
|
||||
|
||||
let subscriptionStatus;
|
||||
if (subscriptionActive) {
|
||||
subscriptionStatus = <span className="text-success">активна</span>;
|
||||
} else {
|
||||
subscriptionStatus = <span className="text-danger">неактивна</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<section id="subscriptionStatus">
|
||||
@ -16,33 +51,27 @@ const PageProfile = () => {
|
||||
<p className="lead text-muted">Здесь отображается статус текущей подписки</p>
|
||||
</div>
|
||||
|
||||
<p className="display-1 my-5">Статус: <span className="text-success">активна</span></p>
|
||||
<h3 className="fw-normal">Действует до: <span className="fw-bold">20.12.2023</span></h3>
|
||||
<button className="btn btn-outline-danger mt-4">Отменить подписку</button>
|
||||
<p className="display-1 my-5">Статус: {subscriptionStatus}</p>
|
||||
|
||||
{ subscriptionActive === true
|
||||
&& <div>
|
||||
<h3 className="fw-normal">Действует до: <span className="fw-bold">{ getExpirationDateFormatted() }</span></h3>
|
||||
<button className="btn btn-outline-danger mt-4" onClick={() => {
|
||||
cancelSubscription();
|
||||
}}>Отменить подписку</button>
|
||||
</div>
|
||||
}
|
||||
|
||||
</Container>
|
||||
</section>
|
||||
|
||||
<section id="watchLater" className="bg-light">
|
||||
<Container fluid="md" className="py-4 mb-4">
|
||||
|
||||
<div className="text-center">
|
||||
<h2>Избранное</h2>
|
||||
<p className="lead text-muted">Фильмы и сериары, отмеченные как `посмотреть позже`</p>
|
||||
</div>
|
||||
|
||||
<Row className="gx-5 gy-5 my-3">
|
||||
<MovieBookmark id={ 1 } imageSrc={ logoAmericanPsycho } title="Американский психопат" requiresSubscription={ true } />
|
||||
<MovieBookmark id={ 2 } imageSrc={ logoPeakyBlinders } title="Острые козырьки" requiresSubscription={ false } />
|
||||
<MovieBookmark id={ 3 } imageSrc={ logoDrive } title="Драйв" requiresSubscription={ false } />
|
||||
</Row>
|
||||
|
||||
</Container>
|
||||
<Wishlist />
|
||||
</section>
|
||||
|
||||
<section id="logout">
|
||||
<div className="text-center py-4">
|
||||
<button className="btn btn-lg btn-danger">Выйти из аккаунта</button>
|
||||
<button className="btn btn-lg btn-danger" onClick={handleLogout}>Выйти из аккаунта</button>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
|
@ -2,50 +2,86 @@ import {
|
||||
Container, Row, Col, Button,
|
||||
} from 'react-bootstrap';
|
||||
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import toast from 'react-hot-toast';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
import useMovieData from '../components/movies/MovieDataHook';
|
||||
import useWishlist from '../components/wishlist/WishlistHook';
|
||||
import useLogin from '../components/login/LoginHook';
|
||||
import useSubscription from '../components/subscription/SubscriptionHook';
|
||||
|
||||
const PageVideoplayer = () => {
|
||||
const { id } = useParams();
|
||||
const { movieData } = useMovieData(id);
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { loginData } = useLogin();
|
||||
const { subscriptionActive } = useSubscription();
|
||||
|
||||
const { addToWishlist } = useWishlist();
|
||||
|
||||
useEffect(() => {
|
||||
if (movieData.id) {
|
||||
if (movieData.requiresSubscription && !subscriptionActive) {
|
||||
toast.error('Для просмотра этого фильма необходима подписка');
|
||||
navigate('/Pricing');
|
||||
}
|
||||
}
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [movieData]);
|
||||
|
||||
if (!loginData) {
|
||||
toast.error('Для просмотра фильмов необходимо авторизоваться');
|
||||
navigate('/login');
|
||||
}
|
||||
|
||||
const handleWatchLater = async () => {
|
||||
addToWishlist(movieData);
|
||||
toast.success('Добавлено');
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<section id="player">
|
||||
<Container fluid="md" className="py-4 mb-4">
|
||||
<div className="ratio ratio-16x9 my-4">
|
||||
<iframe width="560" height="315" src="https://www.youtube.com/embed/dfeUzm6KF4g?si=U2D-2WNsJzkcxlBX" title="YouTube video player" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowFullScreen></iframe>
|
||||
</div>
|
||||
<p className="display-4" id="movieTitle">Бойцовский клуб</p>
|
||||
<Container fluid="md" className="py-4 mb-4">
|
||||
<div className="ratio ratio-16x9 my-4">
|
||||
<iframe width="560" height="315" src={ movieData.video } title="YouTube video player" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowFullScreen></iframe>
|
||||
</div>
|
||||
<p className="display-4">{ movieData.title }</p>
|
||||
|
||||
<Row className="jgx-5 gy-5 mb-4">
|
||||
<Col lg={ 7 }>
|
||||
<h3>Описание</h3>
|
||||
<p className="my-4" id="movieDescription">
|
||||
Описание.
|
||||
</p>
|
||||
</Col>
|
||||
<Row className="jgx-5 gy-5 mb-4">
|
||||
<Col lg={ 7 }>
|
||||
<h3>Описание</h3>
|
||||
<p className="my-4">
|
||||
{ movieData.description }
|
||||
</p>
|
||||
</Col>
|
||||
|
||||
<Col lg={ 5 } id="movieInfoContainer">
|
||||
<h3>О фильме</h3>
|
||||
<ul className="list-group list-group-flush my-3">
|
||||
<li className="list-group-item">
|
||||
<span className="fw-bold">Год производства:</span> 1999
|
||||
</li>
|
||||
<li className="list-group-item">
|
||||
<span className="fw-bold">Страна:</span> США, Германия
|
||||
</li>
|
||||
<li className="list-group-item">
|
||||
<span className="fw-bold">Слоган:</span> <span className="text-secondary">«Интриги. Хаос. Мыло»</span>
|
||||
</li>
|
||||
<li className="list-group-item">
|
||||
<span className="fw-bold">Режиссер:</span> Дэвид Финчер
|
||||
</li>
|
||||
<li className="list-group-item">
|
||||
<span className="fw-bold">Возраст:</span> 18+
|
||||
</li>
|
||||
</ul>
|
||||
</Col>
|
||||
</Row>
|
||||
<Col lg={ 5 } id="movieInfoContainer">
|
||||
<h3>О фильме</h3>
|
||||
<ul className="list-group list-group-flush my-3">
|
||||
<li className="list-group-item">
|
||||
<span className="fw-bold">Год производства:</span> { movieData.releaseDate }
|
||||
</li>
|
||||
<li className="list-group-item">
|
||||
<span className="fw-bold">Страна:</span> { movieData.country }
|
||||
</li>
|
||||
<li className="list-group-item">
|
||||
<span className="fw-bold">Слоган:</span> <span className="text-secondary">«{ movieData.tagline }»</span>
|
||||
</li>
|
||||
<li className="list-group-item">
|
||||
<span className="fw-bold">Режиссер:</span> { movieData.director }
|
||||
</li>
|
||||
<li className="list-group-item">
|
||||
<span className="fw-bold">Возраст:</span> { movieData.ageRating.name }
|
||||
</li>
|
||||
</ul>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Button>Посмотреть позже</Button>
|
||||
</Container>
|
||||
</section>
|
||||
</>
|
||||
<Button onClick={ handleWatchLater }>Посмотреть позже</Button>
|
||||
</Container>
|
||||
);
|
||||
};
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user