This commit is contained in:
dasha 2023-12-12 14:26:41 +04:00
parent 4e3dfdab49
commit 6b22ec18a2
78 changed files with 653 additions and 5655 deletions

View File

@ -17,8 +17,6 @@ jar {
} }
dependencies { dependencies {
implementation(project(':front'))
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor" annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web'

50
front/.gitignore vendored
View File

@ -1,50 +0,0 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
.parcel-cache

View File

@ -1,53 +0,0 @@
import com.github.gradle.node.util.PlatformHelper
import groovy.text.SimpleTemplateEngine
plugins {
id 'java'
id 'com.github.node-gradle.node' version '3.5.1'
id "de.undercouch.download" version '5.3.1'
}
node {
version = '18.15.0'
download = true
}
jar.dependsOn 'npmBuild'
clean.dependsOn 'npmClean'
nodeSetup.dependsOn 'downloadNode'
jar {
from 'dist'
into 'static'
}
task downloadNode(type: Download) {
final helper = new PlatformHelper()
final templateData = [
"url" : node.distBaseUrl.get(),
"version": node.version.get(),
"os" : helper.osName,
"arch" : helper.osArch,
"ext" : helper.windows ? 'zip' : 'tar.gz'
]
final urlTemplate = '${url}/v${version}/node-v${version}-${os}-${arch}.${ext}'
final engine = new SimpleTemplateEngine()
final url = engine.createTemplate(urlTemplate).make(templateData).toString()
final String destDir = '.gradle/'
file(destDir).mkdirs()
src url
dest destDir
overwrite false
}
tasks.register('npmBuild', NpmTask) {
dependsOn npmInstall
args = ['run-script', 'build']
}
tasks.register('npmClean', NpmTask) {
dependsOn npmInstall
args = ['run-script', 'clean']
}

3303
front/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,46 +0,0 @@
{
"name": "cinema-react-2",
"version": "0.1.0",
"source": "./public/index.html",
"private": true,
"dependencies": {
"@fortawesome/fontawesome-free": "^6.2.1",
"@fortawesome/free-solid-svg-icons": "^6.2.1",
"@fortawesome/react-fontawesome": "^0.2.0",
"axios": "^1.2.1",
"bootstrap": "^5.2.3",
"font-awesome": "^4.7.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.4"
},
"scripts": {
"start": "parcel --port 3000",
"build": "npm run clean && parcel build",
"clean": "rimraf dist"
},
"devDependencies": {
"buffer": "^5.7.1",
"parcel": "2.8.3",
"process": "^0.11.10",
"rimraf": "4.4.0"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

View File

@ -1,12 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Киносайт</title>
</head>
<body class="d-flex flex-column h-100">
<div id="root"></div>
<script type="module" src="../src/index.js"></script>
</body>
</html>

View File

@ -1,46 +0,0 @@
import {BrowserRouter, Route, Routes} from 'react-router-dom'
import Films from './pages/Films'
import FilmPage from './pages/FilmPage'
import Header from './pages/components/Header'
import Footer from './pages/components/Footer'
import SearchSame from './pages/SearchSame'
import Registration from './pages/Registration'
import Sessions from './pages/Sessions'
import Orders from './pages/Orders'
import Users from "./pages/Users";
import PrivateRoutes from "./pages/components/PrivateRoutes";
export default function App() {
const links = [
{path: 'films', label: 'Главная', userAccess: 'NONE'},
{path: 'registration', label: 'Регистрация', userAccess: 'NONE'},
{path: 'entry', label: 'Вход', userAccess: 'NONE'},
{path: 'users', label: 'Пользователи', userAccess: 'ADMIN'},
{path: 'sessions', label: 'Сеансы', userAccess: 'NONE'},
{path: 'orders', label: 'Заказы', userAccess: 'USER'}
];
return (
<>
<BrowserRouter>
<Header links={links}/>
<Routes>
<Route element={<Films/>} path='/'/>
<Route element={<Films/>} path='/films'/>
<Route element={<FilmPage/>} path='/films:id'/>
<Route element={<SearchSame/>} path='/search-same/:request'/>
<Route element={<Registration/>} path="/registration"/>
<Route element={<Registration/>} path="/entry"/>
<Route element={<Sessions/>} path="/sessions"/>
<Route element={<PrivateRoutes userAccess='USER'/>}>
<Route element={<Orders/>} path="/orders"/>
</Route>
<Route element={<PrivateRoutes userAccess="ADMIN"/>}>
<Route element={<Users/>} path="/users"/>
</Route>
</Routes>
<Footer/>
</BrowserRouter>
</>
);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 297 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 339 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 194 KiB

View File

@ -1,12 +0,0 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import 'bootstrap/dist/css/bootstrap.css'
import './styles/index.css'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

View File

@ -1,81 +0,0 @@
import { React, useEffect, useState } from 'react'
import ContentBlock from './components/ContentBlock'
import { useParams } from 'react-router-dom'
import axios from 'axios'
export default function FilmPage() {
const params = useParams()
const [items, setItems] = useState({});
useEffect(() => {
fetch("http://localhost:8080/cinema/" + params.id)
.then(function (response) {
return response.json();
})
.then(function (data) {
console.info('Get film success');
setItems(data);
})
.catch(function (error) {
console.error('Error:', error);
throw "Can't get film";
});
}, []);
const content = (
<div>
<div className="container pt-4">
<div className="container d-block text-start">
<img className="row posterFilmPage img-fluid float-start me-3 mt-3" src={items.image} alt={items.name} align="left" />
<a className="col text-white fw-bold fs-2" onClick={() => window.location.reload()} style={{ cursor: "pointer" }}>{items.name}, 2020 г. </a>
<span className="col badge green-mark text-white fw-bold fs-5 mx-2 p-2">9.2</span>
<button className="col badge willSee text-white fw-bold fs-5 mx-2 p-2 border border-0">
Буду смотреть
</button>
</div>
<div className="container table text-start fs-4">
<div className="row text-white fw-bold fs-3">О фильме</div>
<div className="row">
<div className="col-xs-6 col-sm-3">Год производства</div>
<div className="col-xs-6 col-sm-3">1000</div>
</div>
<div className="row">
<div className="col-xs-6 col-sm-3">Страна</div>
<div className="col-xs-6 col-sm-3">Россия</div>
</div>
<div className="row">
<div className="col-xs-6 col-sm-3">Жанр</div>
<div className="col-xs-6 col-sm-3">Драма</div>
</div>
<div className="row">
<div className="col-xs-6 col-sm-3">Длительность</div>
<div className="col-xs-6 col-sm-3">189 мин. / 03:09</div>
</div>
<div className="row">
<div className="col-xs-6 col-sm-3">Возраст</div>
<div className="col-xs-6 col-sm-3">16+</div>
</div>
</div>
<h3 className="text-white fw-bold m-auto p-1 fs-3 text-start">Описание</h3>
<div className="description text-start fs-4">
Пол Эджкомб начальник блока смертников в тюрьме «Холодная гора», каждыйиз узников которого однажды проходит «зеленую милю» по пути к месту казни. Пол повидал много заключённых
и надзирателей за время работы. Однако гигант Джон Коффи, обвинённый в страшном преступлении,
стал одним из самых необычных обитателей блока.
</div>
</div>
<hr className="border border-0 bg-black" />
<div className="container">
<h1 className="fs-1 fw-bold text-white ms-2 text-start">Трейлер</h1>
<nav className="ratio ratio-16x9">
<iframe className="p-2" src="https://www.youtube.com/embed/Ca3mUSDJlgM" title="YouTube video player" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen></iframe>
</nav>
</div>
</div>
);
return (
<div>
<ContentBlock valueBlock={content} title='Страница фильма' />
</div>
)
}

View File

@ -1,224 +0,0 @@
import {React, useState, useEffect} from 'react'
import {useNavigate} from 'react-router-dom'
import FilmItem from './components/FilmItem'
import ContentBlock from './components/ContentBlock'
import ModalEdit from './components/ModalEdit'
import Banner from './components/Banner'
import '../styles/banner.css'
import CinemaDto from './models/CinemaDto'
import Service from './services/Service'
export default function Films() {
const navigate = useNavigate();
const fileReader = new FileReader()
const [items, setItems] = useState([]);
const [modalTable, setModalTable] = useState(false);
const [selectedImage, setSelectedImage] = useState();
// для инпутов
const [filmName, setFilmName] = useState('');
const [filmNameEdit, setFilmNameEdit] = useState('');
// хук для запоминания индекса элемента, вызвавшего модальное окно
const [currEditItem, setCurrEditItem] = useState(0);
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
async function getAll(elem) {
const requestParams = {
method: "GET"
};
const requestUrl = `http://localhost:8080/${elem}`
const response = await fetch(requestUrl, requestParams)
return await response.json()
}
// фильмы
useEffect(() => {
getAll('cinema')
.then(data => setItems(data));
}, []);
async function handleDeleteFilm(id) {
console.info('Try to remove item');
const requestParams = {
method: "DELETE",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
}
};
const response = await fetch(`http://localhost:8080/cinema/${id}`, requestParams)
await response.json()
.then(() => {
setItems(items.filter(elem => elem.id !== id))
console.log("Removed")
});
}
async function handleEditFilm(id) {
console.info(`Start edit script`);
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const requestUrl = `http://localhost:8080/cinema/${id}`
const response = await fetch(requestUrl, requestParams)
return await response.json()
.then(function (data) {
setFilmNameEdit(data.name);
setCurrEditItem(data.id);
setModalTable(true)
console.info('End edit script');
})
};
// принимаем событие от кнопки "добавить"
const handleSubmitCreate = async (e) => {
e.preventDefault(); // страница перестает перезагружаться
const itemObject = new CinemaDto(selectedImage, filmName);
console.info('Try to add item');
const requestParams = {
method: "POST",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
},
body: JSON.stringify(itemObject)
};
await fetch(`http://localhost:8080/cinema`, requestParams)
.then((response) => response.json())
.then((data) => {
setItems([...items, data]);
setFilmName('');
console.info('Added');
})
.catch(function (error) {
console.error('Error:', error);
throw "Can't add item";
});
};
// принимаем событие от кнопки "сохранить изменения"
const handleSubmitEdit = async (e, id) => {
console.info('Start synchronize edit');
e.preventDefault(); // страница перестает перезагружаться
const itemObject = new CinemaDto(selectedImage, filmNameEdit, id);
const requestParams = {
method: "PUT",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
},
body: JSON.stringify(itemObject)
};
const requestUrl = `http://localhost:8080/cinema/${id}`
const response = await fetch(requestUrl, requestParams)
await response.json()
.then((data) => {
setItems(
items.map(item =>
item.id === id ? {
...item,
image: data.image,
name: data.name,
} : item)
)
console.info('End synchronize edit');
setModalTable(false)
})
.catch((error) => {
console.error('Error:', error);
});
};
fileReader.onloadend = () => (
setSelectedImage(fileReader.result)
)
function changePicture(e) {
e.preventDefault();
const file = e.target.files[0]
fileReader.readAsDataURL(file)
}
const Content = (
<div>
{(localStorage.getItem("role") === 'ADMIN') &&
<form className="row g-3 fs-4 description fw-bold needs-validation-content" id="frm-items"
onSubmit={handleSubmitCreate}>
<div className="col-md-3">
<label className="form-label" htmlFor="filmPicture">Изображение</label>
<input required className="form-control" name="filmPicture" id="filmPicture"
type="file"
onChange={changePicture}/>
</div>
<div className="col">
<label className="form-label" htmlFor="filmName">Название</label>
<input required className="form-control" name="filmName" id="filmName" type="text"
value={filmName} onChange={e => setFilmName(e.target.value)}
placeholder="Введите название"/>
</div>
<div className="form-check mx-2">
<input required className="form-check-input" name="film16" id="film16" type="checkbox"/>
<label className="form-check-label" htmlFor="film16">Мне уже 16 лет</label>
<div className="invalid-feedback">Подтвердите, что вам уже есть 16 лет</div>
</div>
<div className="text-start">
<button className="willSee p-1 border border-0 rounded text-white fw-bold fs-4"
id="btn-add-item" type="submit">Добавить
</button>
</div>
</form>}
<hr className="border border-0 bg-black"/>
<table className="table" id="tbl-items">
<tbody>
{items.map((item) =>
<FilmItem
item={item}
key={item.id}
removeFunc={(localStorage.getItem("role") === 'ADMIN') ? handleDeleteFilm : null}
editFunc={(localStorage.getItem("role") === 'ADMIN') ? handleEditFilm : null}
openFilmPageFunc={(index) => navigate(`/films/${index}`)}
/>
)}
</tbody>
</table>
{(localStorage.getItem("role") === 'ADMIN') && <ModalEdit visible={modalTable} setVisible={setModalTable}>
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit"
onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
<div className="row">
<label className="form-label" htmlFor="filmPictureEdit">Изображение</label>
<input required className="form-control" name="filmPictureEdit" id="filmPictureEdit"
type="file"
onChange={changePicture}/>
</div>
<div className="row">
<label className="form-label" htmlFor="filmNameEdit">Название</label>
<input value={filmNameEdit} onChange={e => setFilmNameEdit(e.target.value)}
className="form-control" name='filmNameEdit' id="filmNameEdit" type="text"
placeholder="Введите название" required/>
</div>
<div className="text-center mt-3">
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить
изменения
</button>
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal"
onClick={() => setModalTable(false)}>Отмена
</button>
</div>
</form>
</ModalEdit>}
</div>
);
return (
<div>
<Banner/>
<ContentBlock valueBlock={Content} title='Фильмы'/>
</div>
)
}

View File

@ -1,249 +0,0 @@
import {useEffect, useState} from 'react'
import ContentBlock from './components/ContentBlock'
import Service from './services/Service';
import ModalEdit from './components/ModalEdit';
import OrderItem from './components/OrderItem';
import OrderSessionItem from './components/OrderSessionItem';
export default function Orders() {
const [users, setUsers] = useState([]);
const [modalTable, setModalTable] = useState(false);
// хук для запоминания индекса элемента, вызвавшего модальное окно
const [currEditItem, setCurrEditItem] = useState(0);
// для выпадающих значений
const [customerName, setCustomerName] = useState('');
const [sessionName, setSessionName] = useState('');
const [count, setCount] = useState(1);
const [session, setSession] = useState([]);
const [orderSessions, setOrderSessions] = useState([]);
useEffect(() => {
const user = localStorage.getItem('user')
setCustomerName(user)
getAll('session').then((data) => setSession(data))
getAll(`customer?login=${user}`).then((data) => setUsers(data.orders))
}, [])
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
async function getAll(elem) {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const requestUrl = `http://localhost:8080/${elem}`
const response = await fetch(requestUrl, requestParams)
return await response.json()
}
function handleSubmit(e) {
e.preventDefault();
handleSubmitCreate(e)
console.log('Form submit')
}
// принимаем событие от кнопки "добавить"
const handleSubmitCreate = async (e) => {
e.preventDefault()
console.info('Try to add item');
const requestParams = {
method: "POST",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
}
};
await fetch(`http://localhost:8080/order/${customerName}`, requestParams)
.then(() => {
getAll(`customer?login=${customerName}`).then((data) => setUsers(data.orders))
})
.catch(function (error) {
console.error('Error:', error);
throw "Can't add order";
});
};
function handleEdit(id) {
console.info(`Start edit script`);
getAll(`order/${id}`)
.then(function (data) {
setCurrEditItem(data.id);
setOrderSessions(data.sessions)
setModalTable(true)
console.info('End edit script');
})
}
const handleSubmitAdd = async (e, id) => {
console.info('Start add session');
e.preventDefault(); // страница перестает перезагружаться
const requestParams = {
method: "PUT",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
}
};
const requestUrl = `http://localhost:8080/order/${id}?session=${sessionName}&count=${count}`
const response = await fetch(requestUrl, requestParams)
await response.json()
.then((data) => {
setOrderSessions(data.sessions)
console.info('End add session');
})
.catch((error) => {
console.error('Error:', error);
alert('Не хватает билетов на сеанс')
});
};
const handleSubmitDelete = async (e, id) => {
console.info('Start delete session');
e.preventDefault(); // страница перестает перезагружаться
const requestParams = {
method: "PUT",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
}
};
const requestUrl = `http://localhost:8080/order/${id}?session=${sessionName}&count=-${count}`
const response = await fetch(requestUrl, requestParams)
await response.json()
.then((data) => {
console.info('End delete session')
setOrderSessions(data.sessions)
})
.catch((error) => {
console.error('Error:', error);
});
};
async function handleDelete(id) {
console.info('Try to remove item');
const requestParams = {
method: "DELETE",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
}
};
const response = await fetch(`http://localhost:8080/order/${id}`, requestParams)
await response.json()
.then(() => {
setUsers(users.filter(elem => elem.id !== id))
console.log("Removed")
});
}
async function handleDeleteOrderSession(e, id, sessionId) {
console.info('Start delete session');
const requestParams = {
method: "PUT",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
}
};
const requestUrl = `http://localhost:8080/order/${id}?session=${sessionId}`
const response = await fetch(requestUrl, requestParams)
await response.json()
.then((data) => {
console.info('End delete session')
setOrderSessions(data.sessions)
})
.catch((error) => {
console.error('Error:', error);
});
}
const Content = (
<>
<form className="d-flex flex-column fs-4 fw-bold text-white text-center align-items-center">
<div>
<button className="btn btn-success my-3" type="button" onClick={handleSubmit}>Добавить</button>
</div>
</form>
<table className="table mt-3 text-white">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Customer</th>
<th scope="col">DateOfPurchase</th>
<th scope="col"></th>
</tr>
</thead>
<tbody id="tbody">
{users.map((user) => (
<OrderItem
item={user}
key={user.id}
editFunc={handleEdit}
removeFunc={handleDelete}
/>
))}
</tbody>
</table>
<ModalEdit visible={modalTable} setVisible={setModalTable}>
<form className="fs-4 description fw-bold d-flex flex-column align-items-center" id="frm-items-edit">
<div className="col-6">
<label className="form-label" htmlFor="session">Сеанс</label>
<select required className="form-control" name="session" id="session" value={session.value}
onChange={e => setSessionName(e.target.value)}>
<option value='' defaultValue disabled>Выберите значение</option>
{session && session.map(elem =>
<option key={elem.id}
value={elem.id}>{elem.cinema.name} {new Date(elem.timestamp).toLocaleString('RU-ru')}</option>
)}
</select>
</div>
<div className="col-6">
<label className="form-label" htmlFor="count">Количество</label>
<input required className="form-control" name="count" id="count" type="number" min="1"
value={count} onChange={e => setCount(e.target.value)} placeholder="Введите количество"/>
</div>
<div className="text-center mt-3">
<button className="btn btn-success mx-1" type="button"
onClick={e => handleSubmitAdd(e, currEditItem)}>Добавить
</button>
<button className="btn btn-danger mx-1" type="button"
onClick={e => handleSubmitDelete(e, currEditItem)}>Удалить
</button>
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal"
onClick={() => setModalTable(false)}>Отмена
</button>
</div>
<p>Мои сеансы</p>
<table className="table fs-6 table-bordered" id="tbl-items">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Price</th>
<th scope="col">Cinema</th>
<th scope="col">Timestamp</th>
<th scope="col">Count</th>
</tr>
</thead>
<tbody>
{orderSessions && orderSessions.map((item) =>
<OrderSessionItem
item={item}
key={parseInt(item.sessionId + '' + item.orderId)}
removeFunc={e => handleDeleteOrderSession(e, currEditItem, item.session.id)}
/>
)}
</tbody>
</table>
</form>
</ModalEdit>
</>
)
return (
<ContentBlock className="d-flex justify-content-center flex-wrap" valueBlock={Content} title='Заказы'/>
)
}

View File

@ -1,118 +0,0 @@
import {useState, useEffect} from 'react'
import ContentBlock from './components/ContentBlock'
import {useNavigate} from "react-router-dom";
export default function Registration() {
const hostURL = "http://localhost:8080";
const navigate = useNavigate();
const [login, setLogin] = useState('');
const [password, setPassword] = useState('');
const [passwordConfirm, setPasswordConfirm] = useState('');
const [error, setError] = useState(false);
useEffect(() => {
setError(false)
}, [])
function handleSubmit(e) {
e.preventDefault();
if (login.length <= 0 || password.length <= 0 ||
window.location.pathname === '/registration' && passwordConfirm.length <= 0) {
setError(true)
throw 'Form not submit'
}
handleSubmitCreate(e)
console.log('Form submit')
setError(false)
setLogin('')
setPassword('')
setPasswordConfirm('')
}
// принимаем событие от кнопки "добавить"
const handleSubmitCreate = async (e) => {
e.preventDefault()
console.info('Try to signup/login');
let requestURL = "/jwt/login"
let requestData = JSON.stringify({login: login, password: password})
if (window.location.pathname === '/registration') {
requestURL = "/signup"
requestData = JSON.stringify({login: login, password: password, passwordConfirm: passwordConfirm})
}
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: requestData,
};
const response = await fetch(hostURL + requestURL, requestParams);
const result = await response.text();
if (response.status === 200 && window.location.pathname === '/entry') {
localStorage.setItem("token", result);
localStorage.setItem("user", login);
getRole(result);
} else {
localStorage.removeItem("token");
localStorage.removeItem("user");
localStorage.removeItem("role");
}
alert(result);
};
async function getRole(token) {
// вызываем поиск пользователя по токену
const requestParams = {
method: "GET",
headers: {
"Content-Type": "application/json",
},
};
const response = await fetch(hostURL + `/get-role?token=${token}`, requestParams);
const result = await response.text();
localStorage.setItem("role", result);
// вызвали событие
window.dispatchEvent(new Event("storage"));
navigate('/orders')
navigate('/orders')
}
const Content = (
<>
<form onSubmit={handleSubmit}
className="d-flex flex-column fs-4 fw-bold text-white text-center align-items-center">
<div>
<label className="form-label">Логин</label>
<input className="form-control mainInput" type="text" value={login}
onChange={e => setLogin(e.target.value)} placeholder="Введите логин"/>
</div>
{error && login.length <= 2 ?
<label className="fs-6 text-danger">Неправильный ввод логина</label> : null}
<div>
<label className="form-label">Пароль</label>
<input className="form-control mainInput" type="password" value={password}
onChange={e => setPassword(e.target.value)} placeholder="Введите пароль"/>
</div>
{error && password.length <= 5 ?
<label className="fs-6 text-danger">Неправильный ввод пароля</label> : null}
{window.location.pathname === '/registration' ? <div>
<label className="form-label">Подтверждение</label>
<input className="form-control mainInput" type="password" value={passwordConfirm}
onChange={e => setPasswordConfirm(e.target.value)} placeholder="Введите повторно"/>
{error && password.length <= 5 || error && passwordConfirm.length <= 5 || error && passwordConfirm !== password ?
<label className="fs-6 text-danger">Неправильный ввод пароля</label> : null}
</div> : null}
<div>
<button className="btn btn-success my-3" type="submit">
{window.location.pathname === '/registration' ? 'Регистрация' : 'Вход'}
</button>
</div>
</form>
</>
)
return (
<ContentBlock className="d-flex justify-content-center flex-wrap" valueBlock={Content}
title={window.location.pathname === '/registration' ? 'Регистрация' : 'Вход'}/>
)
}

View File

@ -1,53 +0,0 @@
import { React, useState, useEffect } from 'react'
import FilmItem from './components/FilmItem'
import { useParams, useNavigate } from "react-router-dom";
import ContentBlock from './components/ContentBlock';
export default function SearchSame() {
const navigate = useNavigate();
// массив полученных фильмов
const [searchResult, setSearchResult] = useState([]);
const params = useParams()
const [items, setItems] = useState([])
useEffect(() => {
let temp = JSON.stringify(searchResult);
temp = JSON.parse(temp);
setItems(temp);
}, [searchResult, params]);
useEffect(() => {
const fetchData = async () => {
const url = new URL(`http://localhost:8080/cinema/search?request=${params.request}`)
try {
const response = await fetch(url.href);
const json = await response.json();
setSearchResult(json);
console.info('Search success');
} catch (error) {
return;
}
};
fetchData();
}, [])
const Content = (
<table className="table" id="tbl-items">
<tbody>
{items.map((item) =>
<FilmItem
item={item}
key={item.id}
openFilmPageFunc={(index) => navigate(`/films/${index}`)}
/>
)}
</tbody>
</table>
)
return (
<div>
<ContentBlock valueBlock={Content} title='Похожие результаты'/>
</div>
)
}

View File

@ -1,230 +0,0 @@
import {React, useState, useEffect} from 'react'
import ContentBlock from './components/ContentBlock'
import Service from './services/Service';
import ModalEdit from './components/ModalEdit';
import SessionItem from './components/SessionItem';
import CinemaDto from './models/CinemaDto'
export default function Sessions() {
const [price, setPrice] = useState(1);
const [timestamp, setTimestamp] = useState(new Date());
const [maxCount, setMaxCount] = useState(1);
const [priceEdit, setPriceEdit] = useState('');
const [users, setUsers] = useState([]);
const [error, setError] = useState(false);
const [modalTable, setModalTable] = useState(false);
// хук для запоминания индекса элемента, вызвавшего модальное окно
const [currEditItem, setCurrEditItem] = useState(0);
// для выпадающих значений
const [cinemaName, setCinemaName] = useState('');
const [cinema, setCinema] = useState([]);
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
useEffect(() => {
setError(false)
getAll('cinema').then((data) => setCinema(data))
getAll('session').then((data) => setUsers(data))
}, [])
async function getAll(elem) {
const requestParams = {
method: "GET"
};
const requestUrl = `http://localhost:8080/${elem}`
const response = await fetch(requestUrl, requestParams)
return await response.json()
}
function handleSubmit(e) {
e.preventDefault();
if (price.length <= 0 || cinema.length <= 0) {
setError(true)
throw 'Form not submit'
}
handleSubmitCreate(e)
console.log('Form submit')
setError(false)
setPrice('')
setCinema('')
}
// принимаем событие от кнопки "добавить"
const handleSubmitCreate = async (e) => {
e.preventDefault()
console.info('Try to add item');
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json"
}
};
await fetch(`http://localhost:8080/session?price=${price}&timestamp=${timestamp}&cinemaid=${cinemaName}&capacity=${maxCount}`, requestParams)
.then(() => {
getAll('session').then((data) => setUsers(data))
getAll('cinema').then((data) => setCinema(data))
})
.catch(function (error) {
console.error('Error:', error);
throw "Can't add session";
});
};
async function handleEdit(id) {
console.info(`Start edit script`);
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const requestUrl = `http://localhost:8080/session/${id}`
const response = await fetch(requestUrl, requestParams)
return await response.json()
.then(function (data) {
setPriceEdit(data.price);
setCurrEditItem(data.id);
setModalTable(true)
console.info('End edit script');
})
}
const handleSubmitEdit = async (e, id) => {
console.info('Start synchronize edit');
e.preventDefault(); // страница перестает перезагружаться
const requestParams = {
method: "PUT",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
}
};
const requestUrl = `http://localhost:8080/session/${id}?price=${priceEdit}`
const response = await fetch(requestUrl, requestParams)
await response.json()
.then((data) => {
setUsers(
users.map(item =>
item.id === id ? {
...item,
price: data.price
} : item)
)
console.info('End synchronize edit');
setModalTable(false)
})
.catch((error) => {
console.error('Error:', error);
});
};
async function handleDelete(id) {
console.info('Try to remove item');
const requestParams = {
method: "DELETE",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
}
};
const response = await fetch(`session/${id}`, requestParams)
await response.json()
.then(() => {
setUsers(users.filter(elem => elem.id !== id))
console.log("Removed")
})
.catch((error) => {
console.error('Error:', error);
});
}
const Content = (
<>
{(localStorage.getItem("role") === 'ADMIN') &&
<form className="d-flex flex-column fs-4 fw-bold text-white text-center align-items-center">
<div>
<label className="form-label">Цена</label>
<input className="form-control mainInput" min="1" type="number" step="0.01" value={price}
onChange={e => setPrice(e.target.value)} placeholder="Введите цену"/>
</div>
{error && price.length <= 0 ?
<label className="fs-6 text-danger">Неправильный ввод цены</label> : null}
<div>
<label className="form-label">Фильм</label>
<select required className="form-select" name="filmCountry" id="filmCountry"
value={cinema.value} onChange={e => setCinemaName(e.target.value)}>
<option value='' defaultValue disabled>Выберите значение</option>
{cinema ? cinema.map(elem =>
<option key={elem.id} value={elem.id}>{elem.name}</option>
) : null}
</select>
</div>
{error && cinema.length <= 0 ?
<label className="fs-6 text-danger">Неправильный ввод фильма</label> : null}
<div>
<label className="form-label">Кол-во сеансов</label>
<input className="form-control mainInput" min="1" type="number" value={maxCount}
onChange={e => setMaxCount(e.target.value)} placeholder="Введите количество"/>
</div>
{error && price.length <= 0 ?
<label className="fs-6 text-danger">Неправильный ввод цены</label> : null}
<div>
<label className="form-label">Дата</label>
<input className="form-control mainInput" type="datetime-local" value={timestamp}
onChange={e => setTimestamp(e.target.value)} placeholder="Введите дату"/>
</div>
{error && timestamp.length <= 0 ?
<label className="fs-6 text-danger">Неправильный ввод даты</label> : null}
<div>
<button className="btn btn-success my-3" type="button" onClick={handleSubmit}>Сохранить</button>
</div>
</form>}
<table className="table mt-3 text-white">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Price</th>
<th scope="col">Cinema</th>
<th scope="col">Timestamp</th>
<th scope="col">Capacity</th>
<th scope="col">MaxCount</th>
<th scope="col"></th>
</tr>
</thead>
<tbody id="tbody">
{users.map((user) => (
<SessionItem
item={user}
key={user.id}
editFunc={(localStorage.getItem("role") === 'ADMIN') ? handleEdit : null}
removeFunc={(localStorage.getItem("role") === 'ADMIN') ? handleDelete : null}
/>
))}
</tbody>
</table>
{(localStorage.getItem("role") === 'ADMIN') && <ModalEdit visible={modalTable} setVisible={setModalTable}>
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit"
onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
<div className="row">
<label className="form-label" htmlFor="priceEdit">Цена</label>
<input value={priceEdit} onChange={e => setPriceEdit(e.target.value)} className="form-control"
name='priceEdit' id="priceEdit" type="number" step="0.01" min="1"
placeholder="Введите цену" required/>
</div>
<div className="text-center mt-3">
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить
изменения
</button>
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal"
onClick={() => setModalTable(false)}>Отмена
</button>
</div>
</form>
</ModalEdit>}
</>
)
return (
<ContentBlock className="d-flex justify-content-center flex-wrap" valueBlock={Content} title='Сеансы'/>
)
}

View File

@ -1,181 +0,0 @@
import {useState, useEffect} from 'react'
import ContentBlock from './components/ContentBlock'
import ModalEdit from './components/ModalEdit';
import UserItem from './components/UserItem';
import axios from "axios";
export default function Users() {
const [loginEdit, setLoginEdit] = useState('');
const [passwordEdit, setPasswordEdit] = useState('');
const [users, setUsers] = useState([]);
const [modalTable, setModalTable] = useState(false);
// хук для запоминания индекса элемента, вызвавшего модальное окно
const [currEditItem, setCurrEditItem] = useState(0);
const [pageNumbers, setPageNumbers] = useState([]);
const [currPage, setCurrPage] = useState(1);
const url = 'http://localhost:8080/api/1.0/customer'
useEffect(() => {
axios
.get(`${url}?page=${currPage}`, {
headers:{
"Authorization": "Bearer " + localStorage.getItem("token")
}
})
.then((response) => {
setUsers(response.data.content)
setPageNumbers(response.data.totalPages);
})
.catch((error) => {
console.error(error);
});
}, [currPage, pageNumbers]);
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
async function handleEdit(id) {
console.info(`Start edit script`);
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const requestUrl = `customer/${id}`
const response = await fetch(requestUrl, requestParams)
return await response.json()
.then(function (data) {
setLoginEdit(data.login);
setPasswordEdit(data.password);
setCurrEditItem(data.id);
setModalTable(true)
console.info('End edit script');
})
}
const handleSubmitEdit = async (e, id) => {
console.info('Start synchronize edit');
e.preventDefault(); // страница перестает перезагружаться
const requestParams = {
method: "PUT",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
},
body: JSON.stringify({login: loginEdit, password: passwordEdit})
};
const requestUrl = `http://localhost:8080/customer/${id}`
const response = await fetch(requestUrl, requestParams)
const temp = await response.json()
.then((data) => {
setUsers(
users.map(item =>
item.id === id ? {
...item,
login: data.login,
password: data.password
} : item)
)
console.info('End synchronize edit');
setModalTable(false)
})
.catch((error) => {
console.error('Error:', error);
});
};
async function handleDelete(id) {
console.info('Try to remove item');
const requestParams = {
method: "DELETE",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
}
};
const response = await fetch(`customer/${id}`, requestParams)
await response.json()
.then(() => {
setUsers(users.filter(elem => elem.id !== id))
console.log("Removed")
})
.catch((error) => {
console.error('Error:', error);
});
}
const pageOnClick = function (page) {
setCurrPage(page);
}
const renderPageNumbers = () => {
const pageNumbersRender = [];
for (let i = 0; i < pageNumbers; i++) {
pageNumbersRender.push(
<li key={i} className={`${i+1 === currPage ? "active" : ""}`}
onClick={() => pageOnClick(i+1)}>
<a className="text-white" href="#">{i+1}</a>
</li>
);
}
return pageNumbersRender;
};
const Content = (
<>
<table className="table mt-3 text-white">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Login</th>
<th scope="col">Password</th>
<th scope="col"></th>
</tr>
</thead>
<tbody id="tbody">
{users.map((user) => (
<UserItem
item={user}
key={user.id}
editFunc={handleEdit}
removeFunc={handleDelete}/>
))}
</tbody>
</table>
<ul className="pagination text-white">
<span style={{float: "left", padding: "5px 5px"}}>Страницы:</span>
{renderPageNumbers()}
</ul>
<ModalEdit visible={modalTable} setVisible={setModalTable}>
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit"
onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
<div className="row">
<label className="form-label" htmlFor="loginEdit">Логин</label>
<input value={loginEdit} onChange={e => setLoginEdit(e.target.value)} className="form-control"
name='loginEdit' id="loginEdit" type="text" placeholder="Введите логин" required/>
</div>
<div className="row">
<label className="form-label" htmlFor="passwordEdit">Пароль</label>
<input value={passwordEdit} onChange={e => setPasswordEdit(e.target.value)}
className="form-control" name='passwordEdit' id="passwordEdit" type="text"
placeholder="Введите пароль" required/>
</div>
<div className="text-center mt-3">
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить
изменения
</button>
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal"
onClick={() => setModalTable(false)}>Отмена
</button>
</div>
</form>
</ModalEdit>
</>
)
return (
<ContentBlock className="d-flex justify-content-center flex-wrap" valueBlock={Content} title='Вход'/>
)
}

View File

@ -1,46 +0,0 @@
import { React, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import banner1 from '../../images/banner1.jpg'
import banner2 from '../../images/banner2.jpg'
import banner3 from '../../images/banner3.jpg'
export default function Banner() {
const length = 3;
var old = 0;
var current = 1;
const navigate = useNavigate();
const [bannerState, setBannerState] = useState(['show', 'hide', 'hide']);
useEffect(() => {
const timer = window.setInterval(() => {
setBannerState([...bannerState, bannerState[current] = 'show', bannerState[old] = 'hide']);
console.info('Banner changed');
old = current;
current++;
if (current === length) {
current = 0;
}
}, 5000)
return () => {
window.clearInterval(timer);
}
}, [])
return (
<div className="d-flex align-items-center flex-column" id="banner">
<a className={bannerState[0]} onClick={() => navigate("/films/0")} style={{ cursor: "pointer" }}>
<img src={banner1} />
</a>
<a className={bannerState[1]} onClick={() => navigate("/films/0")} style={{ cursor: "pointer" }}>
<img src={banner2} />
</a>
<a className={bannerState[2]} onClick={() => navigate("/films/0")} style={{ cursor: "pointer" }}>
<img src={banner3} />
</a>
</div>
)
}

View File

@ -1,15 +0,0 @@
import React from 'react'
import '../../styles/styleBlock.css'
export default function ContentBlock(props) {
return (
<div className="container rounded my-5 p-4 content">
<div className="content_header rounded-top p-2 mb-2">
<h1 className="fs-1 fw-bold text-white ms-5">{props.title}</h1>
</div>
{props.valueBlock}
</div>
)
}

View File

@ -1,27 +0,0 @@
import React from "react"
import '../../styles/styleFilmItem.css'
import MyButton from './MyButton'
export default function FilmItem(props) {
return (
<tr>
<td>
<img className="posterItem me-3" src={props.item.image} alt={props.item.name} align="left" />
<div className="d-flex flex-row flex-wrap flex-grow-1 align-items-center">
<div className="pt-3 description d-flex flex-column justify-content-start align-items-center mb-3 fs-6 fw-bold">
<p className="text-start description">
<a className="text-white fs-5 fw-bold pt-3" onClick={() => props.openFilmPageFunc(props.item.id)} style={{ cursor: "pointer" }}>
{props.item.name}
</a>
</p>
</div>
<div id="rightPanel" className="d-flex flex-wrap justify-content-end text-white fw-bold fs-4 flex-grow-1">
<div className="rounded p-1 mx-2 green-mark">9.2</div>
<MyButton value={props}/>
</div>
</div>
<hr className="border border-0 bg-black" />
</td>
</tr>
)
}

View File

@ -1,11 +0,0 @@
import React from 'react'
import vk from '../../images/vk.jpg'
import '../../styles/styleFooter.css'
export default function Footer() {
return (
<footer className="d-flex align-items-center fw-bold fs-4 p-2 ps-5">2022 г.
<nav className="d-flex justify-content-center flex-grow-1"><a href="https://vk.com/id0" target="_blank"><img className="icon" src={vk} alt="VK" /></a></nav>
</footer>
)
}

View File

@ -1,132 +0,0 @@
import {useEffect, useState} from 'react'
import {useNavigate, Link} from 'react-router-dom'
import '../../styles/styleHeader.css'
import searchImage from '../../images/search.jpg'
export default function Header(props) {
const navigate = useNavigate();
const [searchName, setSearchName] = useState('');
const [userRole, setUserRole] = useState('');
useEffect(() => {
console.log('im here')
window.addEventListener("storage", () => {
const token = localStorage.getItem("token");
const user = localStorage.getItem("user");
if (token) {
getRole(token)
.then((role) => {
if (localStorage.getItem("role") !== role) {
localStorage.removeItem("token");
localStorage.removeItem("user");
localStorage.removeItem("role");
// вызвали событие
window.dispatchEvent(new Event("storage"));
navigate("/entry");
}
});
}
if (!token || !user) {
localStorage.removeItem("token");
localStorage.removeItem("user");
localStorage.removeItem("role");
navigate("/entry");
}
getUserRole();
});
getUserRole();
}, [])
async function getRole(token) {
// вызываем поиск пользователя по токену
const requestParams = {
method: "GET",
headers: {
"Content-Type": "application/json"
}
};
const response = await fetch(`http://localhost:8080/get-role?token=${token}`, requestParams);
return await response.text();
}
const getUserRole = function () {
const role = localStorage.getItem("role") || "";
setUserRole(role);
}
const validate = function (userAccess) {
if (userAccess === 'NONE')
return true;
return userAccess === 'USER' && userRole !== '' || userAccess === userRole;
}
function handleSubmit(e) {
console.info('Try to search data');
e.preventDefault();
navigate(`/search-same/${searchName}`)
setSearchName('');
}
const handleSubmitLogout = function () {
localStorage.removeItem("token");
localStorage.removeItem("user");
localStorage.removeItem("role");
// вызвали событие
window.dispatchEvent(new Event("storage"));
}
return (
<div>
<header className="fs-4 fw-bold p-1">
<nav className="navbar navbar-expand-lg navbar-dark text-white">
<div className="container-fluid">
<a className="navbar-brand" href="/">
<i className="fa-solid fa-font-awesome"></i>
</a>
<button className="navbar-toggler" type="button"
data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse menu" id="navbarNav">
<ul className="navbar-nav">
{
props.links.map((route) => (
<li key={route.path} className="nav-link">
{
validate(route.userAccess) &&
<Link className="nav-link" to={route.path}>
{route.label}
</Link>
}
</li>
))
}
{
(userRole !== '') &&
<li className="nav-link">
<Link className="nav-link" to='entry' onClick={handleSubmitLogout}>
Выход
</Link>
</li>
}
</ul>
<form onSubmit={handleSubmit}
className="col d-flex align-items-center needs-validation justify-content-end">
<input value={searchName} onChange={e => setSearchName(e.target.value)}
className="form-control mainInput" type="text" name="text" search="true"
rounded="true" required placeholder="Введите название"/>
<button className="border border-0 p-0 ms-2" type="submit">
<img className="icon"
src={searchImage}
alt="Поиск"/>
</button>
</form>
</div>
</div>
</nav>
</header>
</div>
)
}

View File

@ -1,18 +0,0 @@
import React from 'react'
import * as classes from "../../styles/ModalEdit.module.css"
export default function ModalEdit({children, visible, setVisible}) {
const rootClasses = [classes.myModal]
if (visible) {
rootClasses.push(classes.active);
}
//onClick={()=>setVisible(false)}
return (
<div className={rootClasses.join(' ')} >
<div className={classes.myModalContent}>
{children}
</div>
</div>
)
}

View File

@ -1,26 +0,0 @@
import React from "react"
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faEdit } from "@fortawesome/free-solid-svg-icons"
import { faRemove } from "@fortawesome/free-solid-svg-icons"
export default function MyButton({ value }) {
const delButton = (
<button onClick={() => value.removeFunc(value.item.id)} type="button" className="m-1 btn btn-danger">
<FontAwesomeIcon icon={faRemove} />
</button>
)
const editButton = (
<button onClick={() => value.editFunc(value.item.id)} type="button" className="m-1 btn btn-primary">
<FontAwesomeIcon icon={faEdit} />
</button>
)
return (
<div>
{value.editFunc ? editButton : null}
{value.removeFunc ? delButton : null}
</div>
)
}

View File

@ -1,13 +0,0 @@
import React from "react"
import MyButton from './MyButton'
export default function OrderItem(props) {
return (
<tr>
<td>{props.item.id}</td>
<td>{props.item.customer}</td>
<td>{props.item.dateOfPurchase}</td>
<td><MyButton value={props} /></td>
</tr>
)
}

View File

@ -1,17 +0,0 @@
import React from "react"
import MyButton from "./MyButton";
export default function OrderSessionItem(props) {
return (
<>
<tr>
<td>{props.item.session.id}</td>
<td>{props.item.session.price}</td>
<td>{props.item.session.cinema.name}</td>
<td>{new Date(props.item.session.timestamp).toLocaleString('RU-ru')}</td>
<td>{props.item.count}</td>
<td><MyButton value={props} /></td>
</tr>
</>
)
}

View File

@ -1,16 +0,0 @@
import {Navigate, Outlet} from 'react-router-dom';
const PrivateRoutes = (props) => {
const userRole = localStorage.getItem("role");
function validate() {
if ((props.userAccess === "USER" && userRole) || (props.userAccess === userRole)) {
return true;
}
return false;
}
return validate() ? <Outlet/> : <Navigate to="/entry"/>;
}
export default PrivateRoutes;

View File

@ -1,18 +0,0 @@
import React, { useEffect, useState } from "react"
import MyButton from './MyButton'
export default function SessionItem(props) {
const date = new Date(props.item.timestamp).toLocaleString('RU-ru')
return (
<tr>
<td>{props.item.id}</td>
<td>{props.item.price}</td>
<td>{props.item.cinema.name}</td>
<td>{date}</td>
<td>{props.item.maxCount - props.item.capacity}</td>
<td>{props.item.maxCount}</td>
<td><MyButton value={props} /></td>
</tr>
)
}

View File

@ -1,13 +0,0 @@
import React from "react"
import MyButton from './MyButton'
export default function UserItem(props) {
return (
<tr>
<td>{props.item.id}</td>
<td>{props.item.login}</td>
<td>{props.item.password}</td>
<td><MyButton value={props} /></td>
</tr>
)
}

View File

@ -1,10 +0,0 @@
export default class CinemaDto {
constructor(image, name, id) {
this.image = image;
this.name = name;
this.id = parseInt(id);
}
static createFrom(item) {
return new CinemaDto(item.image, item.name, item.id);
}
}

View File

@ -1,10 +0,0 @@
export default class CustomerDto {
constructor(login, password, id) {
this.login = login;
this.password = password;
this.id = parseInt(id);
}
static createFrom(item) {
return new CustomerDto(item.login, item.password, item.id);
}
}

View File

@ -1,42 +0,0 @@
import axios from 'axios'
function toJSON(data) {
const jsonObj = {};
const fields = Object.getOwnPropertyNames(data);
for (const field of fields) {
if (data[field] === undefined) {
continue;
}
jsonObj[field] = data[field];
}
return jsonObj;
}
export default class Service {
static dataUrlPrefix = 'http://localhost:8080/';
static async readAll(url) {
const response = await axios.get(this.dataUrlPrefix + url);
return response.data;
}
static async read(url) {
const response = await axios.get(this.dataUrlPrefix + url);
return response.data;
}
static async create(url, data) {
const response = await axios.post(this.dataUrlPrefix + url, toJSON(data));
return response.data;
}
static async update(url, data) {
const response = await axios.put(this.dataUrlPrefix + url, toJSON(data));
return response.data;
}
static async delete(url) {
const response = await axios.delete(this.dataUrlPrefix + url);
return response.data.id ? response.data.id : response.error;
}
}

View File

@ -1,22 +0,0 @@
.myModal {
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
display: none;
background: rgba(0,0,0, 0.5);
}
.myModalContent {
padding: 25px;
background: white;
border-radius: 16px;
max-width: 600px;
}
.myModal.active {
display: flex;
justify-content: center;
align-items: center;
}

View File

@ -1,23 +0,0 @@
#banner {
margin: 15px;
}
@keyframes newAnim {
from { opacity: 0; }
to { opacity: 1; }
}
#banner img {
max-width: 90%;
border-radius: 5px;
animation: newAnim 1s forwards;
}
#banner a.show {
text-align: center;
display: block;
}
#banner a.hide {
display: none;
}

View File

@ -1,83 +0,0 @@
html,
body {
background: #2b2d33;
}
.green-mark {
background-color: #38a65d;
}
.willSee {
background-color: #38a65d;
}
.delete {
background-color: #e94049;
}
.icon {
width: 50px;
height: 50px;
}
hr {
height: 2px; /* Толщина линии */
}
.description {
color: #8f9398;
}
.editIcon {
height: 2.5vh;
}
.posterChoiceToTaste {
width: 290px;
height: 437px;
}
.posterFilmPage{
width: 290px;
height: 437px;
}
a {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/* for film-page */
.table {
color: #8f9398;
}
/* main */
@media screen and (max-width: 290px) {
.posterItem {
display: none !important;
}
.fs-1 {
margin-left: 1em !important;
}
}
/* willsee */
@media screen and (max-width: 290px) {
.posterItem {
display: none !important;
}
.fs-1 {
font-size: medium !important;
margin-left: 1em !important;
}
}
/* choicetotaste */
@media screen and (max-width: 250px) {
.fs-2 {
font-size: medium !important;
}
.fs-1 {
font-size: large !important;
}
}
.pagination li {
color: white;
float: left;
padding: 5px 5px;
text-decoration: none;
}
.pagination li.active {
background-color: gray;
color: white;
border-radius: 2px;
}

View File

@ -1,14 +0,0 @@
html,
body {
background: #2b2d33;
}
.content {
min-height: calc(100vh - 25.1vh);
background: #40444d;
}
.content_header {
margin: -1.5em -1.5em 0em -1.5em;
background-color: #8f9297;
}

View File

@ -1,13 +0,0 @@
.posterItem {
width: 90px;
height: 90px;
margin-top: -10px;
}
form input {
max-width: 300px;
}
table tbody tr td {
border: 0px !important;
}

View File

@ -1,9 +0,0 @@
footer {
flex: 0 0 auto !important;
background: #1a1c20;
color: #c2c2c2;
}
footer nav {
color: #c2c2c2;
}

View File

@ -1,15 +0,0 @@
header {
background: #1a1c20;
}
header a {
color: #c2c2c2;
}
header a:hover {
color: #ffffff;
}
.mainInput {
max-width: 200px;
}

View File

@ -1,9 +1,9 @@
package com.labwork1.app.configuration; package com.labwork1.app.configuration;
import com.labwork1.app.configuration.jwt.JwtFilter; import com.labwork1.app.configuration.jwt.JwtFilter;
import com.labwork1.app.student.controller.CustomerController; import com.labwork1.app.student.controller.UserController;
import com.labwork1.app.student.model.UserRole; import com.labwork1.app.student.model.UserRole;
import com.labwork1.app.student.service.CustomerService; import com.labwork1.app.student.service.UserService;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
@ -22,10 +22,10 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
public class SecurityConfiguration { public class SecurityConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class); private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
public static final String SPA_URL_MASK = "/{path:[^\\.]*}"; public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
private final CustomerService userService; private final UserService userService;
private final JwtFilter jwtFilter; private final JwtFilter jwtFilter;
public SecurityConfiguration(CustomerService userService) { public SecurityConfiguration(UserService userService) {
this.userService = userService; this.userService = userService;
this.jwtFilter = new JwtFilter(userService); this.jwtFilter = new JwtFilter(userService);
createAdminOnStartup(); createAdminOnStartup();
@ -49,9 +49,9 @@ public class SecurityConfiguration {
.and() .and()
.authorizeHttpRequests() .authorizeHttpRequests()
.requestMatchers("/", SPA_URL_MASK).permitAll() .requestMatchers("/", SPA_URL_MASK).permitAll()
.requestMatchers(HttpMethod.POST, CustomerController.URL_LOGIN).permitAll() .requestMatchers(HttpMethod.POST, UserController.URL_LOGIN).permitAll()
.requestMatchers(HttpMethod.POST, CustomerController.URL_SIGNUP).permitAll() .requestMatchers(HttpMethod.POST, UserController.URL_SIGNUP).permitAll()
.requestMatchers(HttpMethod.POST, CustomerController.URL_GET_ROLE).permitAll() .requestMatchers(HttpMethod.POST, UserController.URL_GET_ROLE).permitAll()
.anyRequest() .anyRequest()
.authenticated() .authenticated()
.and() .and()
@ -82,6 +82,6 @@ public class SecurityConfiguration {
.requestMatchers("/webjars/**") .requestMatchers("/webjars/**")
.requestMatchers("/swagger-resources/**") .requestMatchers("/swagger-resources/**")
.requestMatchers("/v3/api-docs/**") .requestMatchers("/v3/api-docs/**")
.requestMatchers("/h2-console"); .requestMatchers("/h2-console/**");
} }
} }

View File

@ -1,7 +1,7 @@
package com.labwork1.app.configuration.jwt; package com.labwork1.app.configuration.jwt;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.labwork1.app.student.service.CustomerService; import com.labwork1.app.student.service.UserService;
import jakarta.servlet.FilterChain; import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException; import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletRequest;
@ -20,9 +20,9 @@ public class JwtFilter extends GenericFilterBean {
private static final String AUTHORIZATION = "Authorization"; private static final String AUTHORIZATION = "Authorization";
public static final String TOKEN_BEGIN_STR = "Bearer "; public static final String TOKEN_BEGIN_STR = "Bearer ";
private final CustomerService userService; private final UserService userService;
public JwtFilter(CustomerService userService) { public JwtFilter(UserService userService) {
this.userService = userService; this.userService = userService;
} }

View File

@ -1,13 +1,21 @@
package com.labwork1.app.student.controller; package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.Cinema; import com.labwork1.app.student.model.Cinema;
import jakarta.persistence.Column;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
public class CinemaDto { public class CinemaDto {
private long id; private long id;
@NotBlank
private String name; private String name;
private String image; private String image;
@NotBlank
private String description;
@NotNull
private Long year;
public CinemaDto() { public CinemaDto() {
} }
@ -15,9 +23,19 @@ public class CinemaDto {
public CinemaDto(Cinema cinema) { public CinemaDto(Cinema cinema) {
this.id = cinema.getId(); this.id = cinema.getId();
this.name = cinema.getName(); this.name = cinema.getName();
this.description = cinema.getDescription();
this.year = cinema.getYear();
this.image = new String(cinema.getImage(), StandardCharsets.UTF_8); this.image = new String(cinema.getImage(), StandardCharsets.UTF_8);
} }
public String getDescription() {
return description;
}
public Long getYear() {
return year;
}
public String getImage() { public String getImage() {
return image; return image;
} }

View File

@ -1,91 +0,0 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.configuration.OpenAPI30Configuration;
import com.labwork1.app.student.model.Customer;
import com.labwork1.app.student.model.UserRole;
import com.labwork1.app.student.service.CustomerService;
import com.labwork1.app.util.validation.ValidationException;
import jakarta.validation.Valid;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.IntStream;
@RestController
public class CustomerController {
private final CustomerService customerService;
public static final String URL_LOGIN = "/jwt/login";
public static final String URL_SIGNUP = "/signup";
public static final String URL_MAIN = "/customer";
public static final String URL_GET_ROLE = "/get-role";
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@PostMapping(URL_LOGIN)
public String login(@RequestBody @Valid CustomerDto userDto) {
return customerService.loginAndGetToken(userDto);
}
@PostMapping(URL_SIGNUP)
public String signup(@RequestBody @Valid UserSignupDto userSignupDto){
try {
Customer user = customerService.addCustomer(userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
return user.getLogin() + " was created";
}
catch(ValidationException e){
return e.getMessage();
}
}
@GetMapping(URL_MAIN + "/{id}")
public CustomerDto getCustomer(@PathVariable Long id) {
return new CustomerDto(customerService.findCustomer(id));
}
@GetMapping(URL_MAIN)
public CustomerDto getCustomerByLogin(@RequestParam("login") String login) {
return new CustomerDto(customerService.findByLogin(login));
}
@GetMapping(URL_GET_ROLE)
public String getRole(@RequestParam("token") String token) {
UserDetails userDetails = customerService.loadUserByToken(token);
Customer user = customerService.findByLogin(userDetails.getUsername());
return user.getRole().toString();
}
@GetMapping(OpenAPI30Configuration.API_PREFIX + URL_MAIN)
@Secured({UserRole.AsString.ADMIN})
public Page<CustomerDto> getCustomers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int size) {
/*final Page<CustomerDto> users = customerService.findAllPages(page, size)
.map(CustomerDto::new);
final int totalPages = users.getTotalPages();
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
.boxed()
.toList();
return Pair.of(users, pageNumbers);*/
final Page<CustomerDto> users = customerService.findAllPages(page, size)
.map(CustomerDto::new);
return users;
}
@PutMapping(URL_MAIN + "/{id}")
@Secured({UserRole.AsString.ADMIN})
public CustomerDto updateCustomer(@PathVariable Long id,
@RequestBody @Valid CustomerDto userDto) {
return new CustomerDto(customerService.updateCustomer(id, userDto.getLogin(), userDto.getPassword()));
}
@DeleteMapping(URL_MAIN + "/{id}")
public CustomerDto deleteCustomer(@PathVariable Long id) {
return new CustomerDto(customerService.deleteCustomer(id));
}
}

View File

@ -1,45 +0,0 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.Customer;
import com.labwork1.app.student.model.Order;
import com.labwork1.app.student.model.OrderSession;
import java.util.ArrayList;
import java.util.List;
public class CustomerDto {
private long id;
private String login;
private String password;
private List<OrderDto> orders;
public CustomerDto() {
}
public CustomerDto(Customer customer) {
this.id = customer.getId();
this.login = customer.getLogin();
this.password = customer.getPassword();
this.orders = new ArrayList<>();
if (customer.getOrders() != null) {
orders = customer.getOrders().stream()
.map(OrderDto::new).toList();
}
}
public long getId() {
return id;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public List<OrderDto> getOrders() {
return orders;
}
}

View File

@ -26,9 +26,9 @@ public class OrderController {
.toList(); .toList();
} }
@PostMapping("/{customer}") @PostMapping("/{user}")
public OrderDto createOrder(@PathVariable String customer) { public OrderDto createOrder(@PathVariable String user) {
return new OrderDto(orderService.addOrder(customer)); return new OrderDto(orderService.addOrder(user));
} }
@PutMapping("/{id}") @PutMapping("/{id}")

View File

@ -1,6 +1,6 @@
package com.labwork1.app.student.controller; package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.Customer; import com.labwork1.app.student.model.User;
import com.labwork1.app.student.model.Order; import com.labwork1.app.student.model.Order;
import com.labwork1.app.student.model.OrderSession; import com.labwork1.app.student.model.OrderSession;
@ -9,8 +9,7 @@ import java.util.List;
public class OrderDto { public class OrderDto {
private long id; private long id;
private Date dateOfPurchase; private String user;
private String customer;
private List<OrderSessionDto> sessions; private List<OrderSessionDto> sessions;
public OrderDto() { public OrderDto() {
@ -18,8 +17,7 @@ public class OrderDto {
public OrderDto(Order order) { public OrderDto(Order order) {
this.id = order.getId(); this.id = order.getId();
this.dateOfPurchase = order.getDateOfPurchase(); this.user = order.getUser().getLogin();
this.customer = order.getCustomer().getLogin();
if (order.getSessions() != null && order.getSessions().size() > 0) if (order.getSessions() != null && order.getSessions().size() > 0)
this.sessions = order.getSessions() this.sessions = order.getSessions()
.stream() .stream()
@ -31,12 +29,8 @@ public class OrderDto {
return id; return id;
} }
public Date getDateOfPurchase() { public String getUser() {
return dateOfPurchase; return user;
}
public String getCustomer() {
return customer;
} }
public List<OrderSessionDto> getSessions() { public List<OrderSessionDto> getSessions() {

View File

@ -1,7 +1,5 @@
package com.labwork1.app.student.controller; package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.Session;
import com.labwork1.app.student.model.SessionExtension;
import com.labwork1.app.student.model.UserRole; import com.labwork1.app.student.model.UserRole;
import com.labwork1.app.student.service.SessionService; import com.labwork1.app.student.service.SessionService;
import org.springframework.security.access.annotation.Secured; import org.springframework.security.access.annotation.Secured;
@ -37,15 +35,15 @@ public class SessionController {
@PostMapping @PostMapping
@Secured({UserRole.AsString.ADMIN}) @Secured({UserRole.AsString.ADMIN})
public SessionDto createSession(@RequestParam("price") String price, public SessionDto createSession(@RequestParam("price") String price,
@RequestParam("timestamp") String timestamp, @RequestParam("dateTime") String dateTime,
@RequestParam("cinemaid") Long cinemaId, @RequestParam("cinemaid") Long cinemaId,
@RequestParam("capacity") Integer capacity) throws ParseException { @RequestParam("capacity") Integer capacity) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(); SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy-MM-dd-HH:ss"); format.applyPattern("yyyy-MM-dd-HH:ss");
Date docDate = format.parse(timestamp.replace('T', '-')); Date docDate = format.parse(dateTime.replace('T', '-'));
return new SessionDto(sessionService.findSession( return new SessionDto(sessionService.findSession(
sessionService.addSession(Double.parseDouble(price), sessionService.addSession(Double.parseDouble(price),
new Timestamp(docDate.getTime()), cinemaId, capacity).getId())); new Timestamp(docDate.getTime()), cinemaId, capacity).getId()));
} }
@PutMapping("/{id}") @PutMapping("/{id}")

View File

@ -8,7 +8,7 @@ import java.sql.Timestamp;
public class SessionDto { public class SessionDto {
private long id; private long id;
private Double price; private Double price;
private Timestamp timestamp; private Timestamp dateTime;
private CinemaDto cinema; private CinemaDto cinema;
private Long capacity; private Long capacity;
@ -20,7 +20,7 @@ public class SessionDto {
public SessionDto(SessionExtension session) { public SessionDto(SessionExtension session) {
this.id = session.getId(); this.id = session.getId();
this.price = session.getPrice(); this.price = session.getPrice();
this.timestamp = session.getTimestamp(); this.dateTime = session.getTimestamp();
this.capacity = session.getCapacity(); this.capacity = session.getCapacity();
this.maxCount = session.getMaxCount(); this.maxCount = session.getMaxCount();
if (session.getCinema() != null) { if (session.getCinema() != null) {
@ -31,7 +31,7 @@ public class SessionDto {
public SessionDto(Session session) { public SessionDto(Session session) {
this.id = session.getId(); this.id = session.getId();
this.price = session.getPrice(); this.price = session.getPrice();
this.timestamp = session.getTimestamp(); this.dateTime = session.getTimestamp();
this.maxCount = session.getMaxCount(); this.maxCount = session.getMaxCount();
if (session.getCinema() != null) { if (session.getCinema() != null) {
this.cinema = new CinemaDto(session.getCinema()); this.cinema = new CinemaDto(session.getCinema());
@ -51,7 +51,7 @@ public class SessionDto {
} }
public Timestamp getTimestamp() { public Timestamp getTimestamp() {
return timestamp; return dateTime;
} }
public Long getCapacity() { public Long getCapacity() {

View File

@ -0,0 +1,88 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.configuration.OpenAPI30Configuration;
import com.labwork1.app.student.model.User;
import com.labwork1.app.student.model.UserRole;
import com.labwork1.app.student.service.UserService;
import com.labwork1.app.util.validation.ValidationException;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
@RestController
public class UserController {
private final UserService userService;
public static final String URL_LOGIN = "/jwt/login";
public static final String URL_SIGNUP = "/signup";
public static final String URL_MAIN = "/user";
public static final String URL_GET_ROLE = "/get-role";
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping(URL_LOGIN)
public String login(@RequestBody @Valid UserDto userDto) {
return userService.loginAndGetToken(userDto);
}
@PostMapping(URL_SIGNUP)
public String signup(@RequestBody @Valid UserSignupDto userSignupDto){
try {
User user = userService.addUser(userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
return user.getLogin() + " was created";
}
catch(ValidationException e){
return e.getMessage();
}
}
@GetMapping(URL_MAIN + "/{id}")
public UserDto getUser(@PathVariable Long id) {
return new UserDto(userService.findUser(id));
}
@GetMapping(URL_MAIN)
public UserDto getUserByLogin(@RequestParam("login") String login) {
return new UserDto(userService.findByLogin(login));
}
@GetMapping(URL_GET_ROLE)
public String getRole(@RequestParam("token") String token) {
UserDetails userDetails = userService.loadUserByToken(token);
User user = userService.findByLogin(userDetails.getUsername());
return user.getRole().toString();
}
@GetMapping(OpenAPI30Configuration.API_PREFIX + URL_MAIN)
@Secured({UserRole.AsString.ADMIN})
public Page<UserDto> getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int size) {
return userService.findAllPages(page, size)
.map(UserDto::new);
}
@PutMapping(URL_MAIN + "/{id}")
@Secured({UserRole.AsString.ADMIN})
public UserDto updateUser(@PathVariable Long id,
@RequestBody @Valid UserDto userDto) {
return new UserDto(userService.updateUser(id, userDto.getLogin(), userDto.getPassword()));
}
@PutMapping("/{id}")
public UserDto updateUserCart(@PathVariable Long id,
@RequestParam("session") Long session,
@RequestParam(value = "count", required = false) Integer count) {
if (count == null)
return new UserDto(userService.deleteSessionInCart(id, session, Integer.MAX_VALUE));
if (count > 0)
return new UserDto(userService.addSession(id, session, count));
return new UserDto(userService.deleteSessionInCart(id, session, -count));
}
@DeleteMapping(URL_MAIN + "/{id}")
public UserDto deleteUser(@PathVariable Long id) {
return new UserDto(userService.deleteUser(id));
}
}

View File

@ -0,0 +1,53 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.User;
import java.util.ArrayList;
import java.util.List;
public class UserDto {
private long id;
private String login;
private String password;
private List<OrderDto> orders;
private List<UserSessionDto> sessions;
public UserDto() {
}
public UserDto(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.password = user.getPassword();
this.orders = new ArrayList<>();
if (user.getOrders() != null) {
orders = user.getOrders().stream()
.map(OrderDto::new).toList();
}
if (user.getSessions() != null && user.getSessions().size() > 0)
this.sessions = user.getSessions()
.stream()
.map(x -> new UserSessionDto(new SessionDto(x.getSession()),
x.getId().getUserId(), x.getCount())).toList();
}
public long getId() {
return id;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public List<OrderDto> getOrders() {
return orders;
}
public List<UserSessionDto> getSessions() {
return sessions;
}
}

View File

@ -0,0 +1,28 @@
package com.labwork1.app.student.controller;
public class UserSessionDto {
private SessionDto session;
private Long userId;
private Integer count;
public UserSessionDto() {
}
public UserSessionDto(SessionDto session, Long userId, Integer count) {
this.session = session;
this.userId = userId;
this.count = count;
}
public SessionDto getSession() {
return session;
}
public Long getUserId() {
return userId;
}
public Integer getCount() {
return count;
}
}

View File

@ -3,6 +3,7 @@ package com.labwork1.app.student.model;
import com.labwork1.app.student.controller.CinemaDto; import com.labwork1.app.student.controller.CinemaDto;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -15,6 +16,12 @@ public class Cinema {
@NotBlank(message = "name can't be null or empty") @NotBlank(message = "name can't be null or empty")
@Column @Column
private String name; private String name;
@NotBlank(message = "description can't be null or empty")
@Column
private String description;
@NotNull(message = "year can't be null or empty")
@Column(name = "col_year")
private Long year;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "cinema", cascade = CascadeType.REMOVE) @OneToMany(fetch = FetchType.EAGER, mappedBy = "cinema", cascade = CascadeType.REMOVE)
private List<Session> sessions; private List<Session> sessions;
@Lob @Lob
@ -23,13 +30,10 @@ public class Cinema {
public Cinema() { public Cinema() {
} }
public Cinema(String name) {
this.name = name;
this.sessions = new ArrayList<>();
}
public Cinema(CinemaDto cinemaDto) { public Cinema(CinemaDto cinemaDto) {
this.name = cinemaDto.getName(); this.name = cinemaDto.getName();
this.description = cinemaDto.getDescription();
this.year = cinemaDto.getYear();
this.image = cinemaDto.getImage().getBytes(); this.image = cinemaDto.getImage().getBytes();
this.sessions = new ArrayList<>(); this.sessions = new ArrayList<>();
} }
@ -52,6 +56,22 @@ public class Cinema {
} }
} }
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getYear() {
return year;
}
public void setYear(Long year) {
this.year = year;
}
public Long getId() { public Long getId() {
return id; return id;
} }

View File

@ -14,12 +14,9 @@ public class Order {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@NotNull(message = "dateOfPurchase can't be null or empty")
@Temporal(TemporalType.DATE)
private Date dateOfPurchase;
@ManyToOne(fetch = FetchType.EAGER) @ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "customer_fk") @JoinColumn(name = "user_fk")
private Customer customer; private User user;
@OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade = @OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade =
{ {
CascadeType.REMOVE, CascadeType.REMOVE,
@ -31,10 +28,6 @@ public class Order {
public Order() { public Order() {
} }
public Order(Date dateOfPurchase) {
this.dateOfPurchase = dateOfPurchase;
}
public void addSession(OrderSession orderSession) { public void addSession(OrderSession orderSession) {
if (sessions == null) { if (sessions == null) {
sessions = new ArrayList<>(); sessions = new ArrayList<>();
@ -65,30 +58,21 @@ public class Order {
public String toString() { public String toString() {
return "Order {" + return "Order {" +
"id=" + id + "id=" + id +
", date='" + dateOfPurchase.toString() + '\'' + ", user='" + user.toString() + '\'';
", customer='" + customer.toString() + '\'';
} }
public Long getId() { public Long getId() {
return id; return id;
} }
public Date getDateOfPurchase() { public User getUser() {
return dateOfPurchase; return user;
} }
public void setDateOfPurchase(Date dateOfPurchase) { public void setUser(User user) {
this.dateOfPurchase = dateOfPurchase; this.user = user;
} if (!user.getOrders().contains(this)) {
user.setOrder(this);
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
if (!customer.getOrders().contains(this)) {
customer.setOrder(this);
} }
} }

View File

@ -15,17 +15,19 @@ public class Session {
protected Long id; protected Long id;
@NotNull(message = "price can't be null or empty") @NotNull(message = "price can't be null or empty")
protected Double price; protected Double price;
@NotNull(message = "timestamp can't be null or empty") @NotNull(message = "dateTime can't be null or empty")
@Column @Column(name = "date_time")
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
protected Timestamp timestamp; protected Timestamp dateTime;
@OneToMany(mappedBy = "session", fetch = FetchType.EAGER) @OneToMany(mappedBy = "session", fetch = FetchType.EAGER)
private List<OrderSession> orders; private List<OrderSession> orders;
@OneToMany(mappedBy = "session", fetch = FetchType.EAGER)
private List<UserSession> users;
@ManyToOne(fetch = FetchType.EAGER) @ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "cinema_fk") @JoinColumn(name = "cinema_fk")
protected Cinema cinema; protected Cinema cinema;
@NotNull(message = "maxCount can't be null or empty") @NotNull(message = "maxCount can't be null or empty")
@Column @Column(name = "max_count")
protected Integer maxCount; protected Integer maxCount;
public Session() { public Session() {
@ -35,17 +37,18 @@ public class Session {
return maxCount; return maxCount;
} }
public Session(Double price, Timestamp timestamp, Integer maxCount) { public Session(Double price, Timestamp dateTime, Integer maxCount) {
this.price = price; this.price = price;
this.timestamp = timestamp; this.dateTime = dateTime;
this.maxCount = maxCount; this.maxCount = maxCount;
} }
public Session(Session session) { public Session(Session session) {
this.id = session.getId(); this.id = session.getId();
this.price = session.getPrice(); this.price = session.getPrice();
this.timestamp = session.getTimestamp(); this.dateTime = session.getTimestamp();
this.orders = session.getOrders(); this.orders = session.getOrders();
this.users = session.getUsers();
this.cinema = session.getCinema(); this.cinema = session.getCinema();
this.maxCount = session.getMaxCount(); this.maxCount = session.getMaxCount();
} }
@ -73,6 +76,20 @@ public class Session {
this.orders.remove(orderSession); this.orders.remove(orderSession);
} }
public void addUser(UserSession userSession){
if (users == null){
users = new ArrayList<>();
}
if (!users.contains(userSession)) {
this.users.add(userSession);
}
}
public void removeUser(UserSession userSession){
if (users.contains(userSession))
this.users.remove(userSession);
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
@ -91,7 +108,7 @@ public class Session {
return "Session {" + return "Session {" +
"id=" + id + "id=" + id +
", price='" + price + '\'' + ", price='" + price + '\'' +
", timestamp='" + timestamp.toString() + '\'' + ", dateTime='" + dateTime.toString() + '\'' +
", maxCount='" + maxCount.toString() + '\'' + ", maxCount='" + maxCount.toString() + '\'' +
", cinema='" + cinema.toString() + '\'' + ", cinema='" + cinema.toString() + '\'' +
'}'; '}';
@ -122,14 +139,22 @@ public class Session {
} }
public Timestamp getTimestamp() { public Timestamp getTimestamp() {
return timestamp; return dateTime;
} }
public void setTimestamp(Timestamp timestamp) { public void setTimestamp(Timestamp dateTime) {
this.timestamp = timestamp; this.dateTime = dateTime;
} }
public List<OrderSession> getOrders() { public List<OrderSession> getOrders() {
return orders; return orders;
} }
public void setUsers(List<UserSession> users) {
this.users = users;
}
public List<UserSession> getUsers() {
return users;
}
} }

View File

@ -9,7 +9,8 @@ import java.util.List;
import java.util.Objects; import java.util.Objects;
@Entity @Entity
public class Customer { @Table(name = "tab_user")
public class User {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@ -21,33 +22,55 @@ public class Customer {
@NotBlank(message = "password can't be null or empty") @NotBlank(message = "password can't be null or empty")
@Size(min = 6, max = 64) @Size(min = 6, max = 64)
private String password; private String password;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = {CascadeType.MERGE,CascadeType.REMOVE}) @OneToMany(fetch = FetchType.EAGER, mappedBy = "user", cascade = {CascadeType.MERGE,CascadeType.REMOVE})
private List<Order> orders; private List<Order> orders;
@OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade =
{
CascadeType.REMOVE,
CascadeType.MERGE,
CascadeType.PERSIST
}, orphanRemoval = true)
private List<UserSession> sessions;
private UserRole role; private UserRole role;
public Customer() { public User() {
} }
public Customer(String login, String password) { public User(String login, String password) {
this.login = login; this.login = login;
this.password = password; this.password = password;
this.orders = new ArrayList<>(); this.orders = new ArrayList<>();
this.sessions = new ArrayList<>();
this.role = UserRole.USER; this.role = UserRole.USER;
} }
public Customer(String login, String password, UserRole role) { public User(String login, String password, UserRole role) {
this.login = login; this.login = login;
this.password = password; this.password = password;
this.orders = new ArrayList<>(); this.orders = new ArrayList<>();
this.sessions = new ArrayList<>();
this.role = role; this.role = role;
} }
public void addSession(UserSession userSession) {
if (sessions == null) {
sessions = new ArrayList<>();
}
if (!sessions.contains(userSession))
this.sessions.add(userSession);
}
public void removeSession(UserSession userSession){
if (sessions.contains(userSession))
this.sessions.remove(userSession);
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
Customer customer = (Customer) o; User user = (User) o;
return Objects.equals(id, customer.id); return Objects.equals(id, user.id);
} }
@Override @Override
@ -57,7 +80,7 @@ public class Customer {
@Override @Override
public String toString() { public String toString() {
return "Customer {" + return "User {" +
"id=" + id + "id=" + id +
", login='" + login + '\'' + ", login='" + login + '\'' +
", password='" + password + '\'' + ", password='" + password + '\'' +
@ -93,8 +116,12 @@ public class Customer {
} }
public void setOrder(Order order) { public void setOrder(Order order) {
if (order.getCustomer().equals(this)) { if (order.getUser().equals(this)) {
this.orders.add(order); this.orders.add(order);
} }
} }
public List<UserSession> getSessions() {
return sessions;
}
} }

View File

@ -0,0 +1,62 @@
package com.labwork1.app.student.model;
import jakarta.persistence.*;
@Entity
@Table(name = "user_session")
public class UserSession {
@EmbeddedId
private UserSessionKey id;
@ManyToOne
@MapsId("sessionId")
@JoinColumn(name = "session_id")
private Session session;
@ManyToOne
@MapsId("userId")
@JoinColumn(name = "user_id")
private User user;
@Column(name = "count")
private Integer count;
public UserSession() {
}
public UserSession(User user, Session session, Integer count) {
this.user = user;
this.session = session;
this.count = count;
this.id = new UserSessionKey(session.getId(), user.getId());
}
public UserSessionKey getId() {
return id;
}
public void setId(UserSessionKey id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}

View File

@ -0,0 +1,49 @@
package com.labwork1.app.student.model;
import jakarta.persistence.Embeddable;
import java.io.Serializable;
import java.util.Objects;
@Embeddable
public class UserSessionKey implements Serializable {
private Long sessionId;
private Long userId;
public UserSessionKey() {
}
public UserSessionKey(Long sessionId, Long userId) {
this.sessionId = sessionId;
this.userId = userId;
}
public Long getSessionId() {
return sessionId;
}
public void setSessionId(Long sessionId) {
this.sessionId = sessionId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UserSessionKey that)) return false;
return Objects.equals(getSessionId(), that.getSessionId()) && Objects.equals(getUserId(), that.getUserId());
}
@Override
public int hashCode() {
return Objects.hash(getSessionId(), getUserId());
}
}

View File

@ -1,12 +0,0 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
Customer findOneByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,14 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.OrderSession;
import com.labwork1.app.student.model.User;
import com.labwork1.app.student.model.UserSession;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface UserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
@Query("Select us from UserSession us where us.user.id = :userId and us.session.id = :sessionId")
UserSession getUserSession(@Param("userId") Long userId, @Param("sessionId") Long sessionId);
}

View File

@ -27,13 +27,6 @@ public class CinemaService {
return cinemaRepository.save(cinema); return cinemaRepository.save(cinema);
} }
@Transactional
public Cinema addCinema(String name) {
final Cinema cinema = new Cinema(name);
validatorUtil.validate(cinema);
return cinemaRepository.save(cinema);
}
@Transactional @Transactional
public Cinema findCinema(Long id) { public Cinema findCinema(Long id) {
final Optional<Cinema> cinema = cinemaRepository.findById(id); final Optional<Cinema> cinema = cinemaRepository.findById(id);

View File

@ -1,10 +0,0 @@
package com.labwork1.app.student.service;
public class CustomerNotFoundException extends RuntimeException {
public CustomerNotFoundException(Long id) {
super(String.format("Customer with id [%s] is not found", id));
}
public CustomerNotFoundException(String login) {
super(String.format("Customer with login [%s] is not found", login));
}
}

View File

@ -1,125 +0,0 @@
package com.labwork1.app.student.service;
import com.labwork1.app.configuration.jwt.JwtProvider;
import com.labwork1.app.student.controller.CustomerDto;
import com.labwork1.app.student.model.Customer;
import com.labwork1.app.student.model.UserRole;
import com.labwork1.app.student.repository.CustomerRepository;
import com.labwork1.app.util.validation.ValidationException;
import com.labwork1.app.util.validation.ValidatorUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.labwork1.app.configuration.jwt.JwtException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Service
public class CustomerService implements UserDetailsService {
private final CustomerRepository customerRepository;
private final PasswordEncoder passwordEncoder;
private final ValidatorUtil validatorUtil;
private final JwtProvider jwtProvider;
public CustomerService(CustomerRepository customerRepository, PasswordEncoder passwordEncoder, ValidatorUtil validatorUtil, JwtProvider jwtProvider) {
this.customerRepository = customerRepository;
this.passwordEncoder = passwordEncoder;
this.validatorUtil = validatorUtil;
this.jwtProvider = jwtProvider;
}
public Page<Customer> findAllPages(int page, int size) {
return customerRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
}
public Customer findByLogin(String login) {
return customerRepository.findOneByLoginIgnoreCase(login);
}
@Transactional
public Customer addCustomer(String login, String password, String passwordConfirm) {
return createUser(login, password, passwordConfirm, UserRole.USER);
}
public Customer createUser(String login, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) {
throw new UserExistsException(login);
}
final Customer user = new Customer(login, passwordEncoder.encode(password), role);
validatorUtil.validate(user);
if (!Objects.equals(password, passwordConfirm)) {
throw new ValidationException("Passwords not equals");
}
return customerRepository.save(user);
}
public String loginAndGetToken(CustomerDto userDto) {
final Customer user = findByLogin(userDto.getLogin());
if (user == null) {
throw new CustomerNotFoundException(userDto.getLogin());
}
if (!passwordEncoder.matches(userDto.getPassword(), user.getPassword())) {
throw new CustomerNotFoundException(user.getLogin());
}
return jwtProvider.generateToken(user.getLogin());
}
public UserDetails loadUserByToken(String token) throws UsernameNotFoundException {
if (!jwtProvider.isTokenValid(token)) {
throw new JwtException("Bad token");
}
final String userLogin = jwtProvider.getLoginFromToken(token)
.orElseThrow(() -> new JwtException("Token is not contain Login"));
return loadUserByUsername(userLogin);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final Customer userEntity = findByLogin(username);
if (userEntity == null) {
throw new UsernameNotFoundException(username);
}
return new org.springframework.security.core.userdetails.User(
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
}
@Transactional(readOnly = true)
public Customer findCustomer(Long id) {
final Optional<Customer> customer = customerRepository.findById(id);
return customer.orElseThrow(() -> new CustomerNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Customer> findAllCustomers() {
return customerRepository.findAll();
}
@Transactional
public Customer updateCustomer(Long id, String login, String password) {
final Customer currentCustomer = findCustomer(id);
currentCustomer.setLogin(login);
currentCustomer.setPassword(passwordEncoder.encode(password));
validatorUtil.validate(currentCustomer);
return customerRepository.save(currentCustomer);
}
@Transactional
public Customer deleteCustomer(Long id) {
final Customer customer = findCustomer(id);
customerRepository.deleteById(id);
return customer;
}
@Transactional
public void deleteAllCustomers() {
customerRepository.deleteAll();
}
}

View File

@ -14,31 +14,31 @@ import java.util.Optional;
@Service @Service
public class OrderService { public class OrderService {
private final OrderRepository orderRepository; private final OrderRepository orderRepository;
private final CustomerService customerService; private final UserService userService;
private final SessionService sessionService; private final SessionService sessionService;
private final ValidatorUtil validatorUtil; private final ValidatorUtil validatorUtil;
public OrderService(OrderRepository orderRepository, CustomerService customerService, SessionService sessionService, ValidatorUtil validatorUtil) { public OrderService(OrderRepository orderRepository, UserService userService, SessionService sessionService, ValidatorUtil validatorUtil) {
this.orderRepository = orderRepository; this.orderRepository = orderRepository;
this.customerService = customerService; this.userService = userService;
this.sessionService = sessionService; this.sessionService = sessionService;
this.validatorUtil = validatorUtil; this.validatorUtil = validatorUtil;
} }
@Transactional @Transactional
public Order addOrder(Long customerId) { public Order addOrder(Long userId) {
final Order order = new Order(new Date(System.currentTimeMillis())); final Order order = new Order();
final Customer customer = customerService.findCustomer(customerId); final User user = userService.findUser(userId);
order.setCustomer(customer); order.setUser(user);
validatorUtil.validate(order); validatorUtil.validate(order);
return orderRepository.save(order); return orderRepository.save(order);
} }
@Transactional @Transactional
public Order addOrder(String customerName) { public Order addOrder(String userName) {
final Order order = new Order(new Date(System.currentTimeMillis())); final Order order = new Order();
final Customer customer = customerService.findByLogin(customerName); final User user = userService.findByLogin(userName);
order.setCustomer(customer); order.setUser(user);
validatorUtil.validate(order); validatorUtil.validate(order);
return orderRepository.save(order); return orderRepository.save(order);
} }

View File

@ -0,0 +1,10 @@
package com.labwork1.app.student.service;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(Long id) {
super(String.format("User with id [%s] is not found", id));
}
public UserNotFoundException(String login) {
super(String.format("User with login [%s] is not found", login));
}
}

View File

@ -0,0 +1,171 @@
package com.labwork1.app.student.service;
import com.labwork1.app.configuration.jwt.JwtProvider;
import com.labwork1.app.student.controller.UserDto;
import com.labwork1.app.student.model.*;
import com.labwork1.app.student.repository.UserRepository;
import com.labwork1.app.util.validation.ValidationException;
import com.labwork1.app.util.validation.ValidatorUtil;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.labwork1.app.configuration.jwt.JwtException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Service
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final SessionService sessionService;
private final PasswordEncoder passwordEncoder;
private final ValidatorUtil validatorUtil;
private final JwtProvider jwtProvider;
public UserService(UserRepository userRepository, SessionService sessionService, PasswordEncoder passwordEncoder, ValidatorUtil validatorUtil, JwtProvider jwtProvider) {
this.userRepository = userRepository;
this.sessionService = sessionService;
this.passwordEncoder = passwordEncoder;
this.validatorUtil = validatorUtil;
this.jwtProvider = jwtProvider;
}
public Page<User> findAllPages(int page, int size) {
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
}
public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
@Transactional
public User addUser(String login, String password, String passwordConfirm) {
return createUser(login, password, passwordConfirm, UserRole.USER);
}
public User createUser(String login, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) {
throw new UserExistsException(login);
}
final User user = new User(login, passwordEncoder.encode(password), role);
validatorUtil.validate(user);
if (!Objects.equals(password, passwordConfirm)) {
throw new ValidationException("Passwords not equals");
}
return userRepository.save(user);
}
public String loginAndGetToken(UserDto userDto) {
final User user = findByLogin(userDto.getLogin());
if (user == null) {
throw new UserNotFoundException(userDto.getLogin());
}
if (!passwordEncoder.matches(userDto.getPassword(), user.getPassword())) {
throw new UserNotFoundException(user.getLogin());
}
return jwtProvider.generateToken(user.getLogin());
}
public UserDetails loadUserByToken(String token) throws UsernameNotFoundException {
if (!jwtProvider.isTokenValid(token)) {
throw new JwtException("Bad token");
}
final String userLogin = jwtProvider.getLoginFromToken(token)
.orElseThrow(() -> new JwtException("Token is not contain Login"));
return loadUserByUsername(userLogin);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final User userEntity = findByLogin(username);
if (userEntity == null) {
throw new UsernameNotFoundException(username);
}
return new org.springframework.security.core.userdetails.User(
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
}
@Transactional(readOnly = true)
public User findUser(Long id) {
final Optional<User> user = userRepository.findById(id);
return user.orElseThrow(() -> new UserNotFoundException(id));
}
@Transactional(readOnly = true)
public List<User> findAllUsers() {
return userRepository.findAll();
}
@Transactional
public User updateUser(Long id, String login, String password) {
final User currentUser = findUser(id);
currentUser.setLogin(login);
currentUser.setPassword(passwordEncoder.encode(password));
validatorUtil.validate(currentUser);
return userRepository.save(currentUser);
}
@Transactional
public User addSession(Long id, Long sessionId, Integer count) {
final Session currentSession = sessionService.findSession(sessionId);
final User currentUser = findUser(id);
final UserSession currentUserSession = userRepository.getUserSession(id, sessionId);
final Integer currentSessionCapacity = currentSession.getMaxCount() - sessionService.getCapacity(sessionId);
if (currentSessionCapacity < count ||
(currentUserSession != null && currentUserSession.getCount() + count > currentSession.getMaxCount())) {
throw new IllegalArgumentException(String.format("No more tickets in session. Capacity: %1$s. Count: %2$s",
currentSessionCapacity, count));
}
if (currentUserSession == null) {
currentUser.addSession(new UserSession(currentUser, currentSession, count));
}
else if (currentUserSession.getCount() + count <= currentSession.getMaxCount()) {
currentUser.removeSession(currentUserSession);
currentUser.addSession(new UserSession(currentUser, currentSession,
currentUserSession.getCount() + count));
}
return userRepository.save(currentUser);
}
@Transactional
public User deleteSessionInCart(Long id, Long session, Integer count) {
final User currentUser = findUser(id);
final Session currentSession = sessionService.findSession(session);
final UserSession currentUserSession = userRepository.getUserSession(id, session);
if (currentUserSession == null)
throw new EntityNotFoundException();
if (count >= currentUserSession.getCount()) {
currentUser.removeSession(currentUserSession);
}
else {
currentUser.removeSession(currentUserSession);
currentUser.addSession(new UserSession(currentUser, currentSession,
currentUserSession.getCount() - count));
}
return userRepository.save(currentUser);
}
@Transactional
public User deleteUser(Long id) {
final User user = findUser(id);
userRepository.deleteById(id);
return user;
}
@Transactional
public void deleteAllUsers() {
userRepository.deleteAll();
}
}

View File

@ -1,7 +1,7 @@
package com.labwork1.app.util.error; package com.labwork1.app.util.error;
import com.labwork1.app.student.service.CinemaNotFoundException; import com.labwork1.app.student.service.CinemaNotFoundException;
import com.labwork1.app.student.service.CustomerNotFoundException; import com.labwork1.app.student.service.UserNotFoundException;
import com.labwork1.app.student.service.OrderNotFoundException; import com.labwork1.app.student.service.OrderNotFoundException;
import com.labwork1.app.student.service.SessionNotFoundException; import com.labwork1.app.student.service.SessionNotFoundException;
import com.labwork1.app.util.validation.ValidationException; import com.labwork1.app.util.validation.ValidationException;
@ -17,7 +17,7 @@ import java.util.stream.Collectors;
@ControllerAdvice @ControllerAdvice
public class AdviceController { public class AdviceController {
@ExceptionHandler({ @ExceptionHandler({
CustomerNotFoundException.class, UserNotFoundException.class,
OrderNotFoundException.class, OrderNotFoundException.class,
SessionNotFoundException.class, SessionNotFoundException.class,
CinemaNotFoundException.class, CinemaNotFoundException.class,

View File

@ -13,10 +13,10 @@
//import java.util.List; //import java.util.List;
// //
//@SpringBootTest //@SpringBootTest
//public class JpaCustomerTests { //public class JpaUserTests {
// private static final Logger log = LoggerFactory.getLogger(JpaCustomerTests.class); // private static final Logger log = LoggerFactory.getLogger(JpaUserTests.class);
// @Autowired // @Autowired
// private CustomerService customerService; // private UserService userService;
// @Autowired // @Autowired
// private SessionService sessionService; // private SessionService sessionService;
// @Autowired // @Autowired
@ -29,7 +29,7 @@
// sessionService.deleteAllSessions(); // sessionService.deleteAllSessions();
// cinemaService.deleteAllCinemas(); // cinemaService.deleteAllCinemas();
// orderService.deleteAllOrders(); // orderService.deleteAllOrders();
// customerService.deleteAllCustomers(); // userService.deleteAllUsers();
// // 2 кино // // 2 кино
// final Cinema cinema1 = cinemaService.addCinema("Меню"); // final Cinema cinema1 = cinemaService.addCinema("Меню");
// final Cinema cinema2 = cinemaService.addCinema("Аватар"); // final Cinema cinema2 = cinemaService.addCinema("Аватар");
@ -44,26 +44,26 @@
// Assertions.assertEquals(cinemaService // Assertions.assertEquals(cinemaService
// .findCinema(cinema1.getId()).getSessions().size(), 2); // .findCinema(cinema1.getId()).getSessions().size(), 2);
// // 1 покупатель // // 1 покупатель
// final Customer customer1 = customerService.addCustomer("Родион", "Иванов"); // final User user1 = userService.addUser("Родион", "Иванов");
// customerService.updateCustomer(customer1.getId(), "Пчел", "Пчелов"); // userService.updateUser(user1.getId(), "Пчел", "Пчелов");
// Assertions.assertEquals(customerService.findCustomer(customer1.getId()).getLogin(), "Пчел"); // Assertions.assertEquals(userService.findUser(user1.getId()).getLogin(), "Пчел");
// // 1 заказ, 1 копия заказа // // 1 заказ, 1 копия заказа
// final Order order0 = orderService.addOrder(customerService.findCustomer(customer1.getId()).getId()); // final Order order0 = orderService.addOrder(userService.findUser(user1.getId()).getId());
// final Order order1 = orderService.findOrder(order0.getId()); // final Order order1 = orderService.findOrder(order0.getId());
// Assertions.assertEquals(order0, order1); // Assertions.assertEquals(order0, order1);
// //
// // у клиента точно есть заказ? // // у клиента точно есть заказ?
// Assertions.assertEquals(customerService // Assertions.assertEquals(userService
// .findCustomer(customer1.getId()).getOrders().size(), 1); // .findUser(user1.getId()).getOrders().size(), 1);
// // 0 заказов // // 0 заказов
// orderService.deleteAllOrders(); // orderService.deleteAllOrders();
// Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(-1L)); // Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(-1L));
// // 2 покупателя // // 2 покупателя
// final Customer customer2 = customerService.addCustomer("Иннокентий", "Иванов"); // final User user2 = userService.addUser("Иннокентий", "Иванов");
// //
// // 1 заказ // // 1 заказ
// final Order order2 = orderService // final Order order2 = orderService
// .addOrder(customerService.findCustomer(customer2.getId()).getId()); // .addOrder(userService.findUser(user2.getId()).getId());
// // у заказа 2 сеанса // // у заказа 2 сеанса
// orderService.addSession(order2.getId(), session1.getId(), 2); // orderService.addSession(order2.getId(), session1.getId(), 2);
// //
@ -104,16 +104,16 @@
// //
// // создали 3 заказ у 2 покупателя // // создали 3 заказ у 2 покупателя
// final Order order3 = orderService // final Order order3 = orderService
// .addOrder(customerService.findCustomer(customer2.getId()).getId()); // .addOrder(userService.findUser(user2.getId()).getId());
// orderService.addSession(order3.getId(), session2.getId(), 2); // orderService.addSession(order3.getId(), session2.getId(), 2);
// orderService.addSession(order3.getId(), session3.getId(), 8); // orderService.addSession(order3.getId(), session3.getId(), 8);
// orderService.addSession(order3.getId(), session1.getId(), 8); // orderService.addSession(order3.getId(), session1.getId(), 8);
// // 2-ой покупатель удален // // 2-ой покупатель удален
// // 0 заказов после его удаления // // 0 заказов после его удаления
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 2); // Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 2);
// customerService.deleteCustomer(customer2.getId()); // userService.deleteUser(user2.getId());
// //
// Assertions.assertThrows(CustomerNotFoundException.class, () -> customerService.findCustomer(customer2.getId())); // Assertions.assertThrows(UserNotFoundException.class, () -> userService.findUser(user2.getId()));
// Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(order3.getId())); // Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(order3.getId()));
// Assertions.assertEquals(orderService.findAllOrders().size(), 0); // Assertions.assertEquals(orderService.findAllOrders().size(), 0);
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0); // Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);