Compare commits

...

41 Commits

Author SHA1 Message Date
c5dfae5f3e так правильнее 2023-05-15 15:56:55 +04:00
4e3dfdab49 я надеюсь это все и ничего не сломается 2023-05-13 13:29:35 +04:00
d1011d0537 так правильнее 2023-04-24 16:22:14 +04:00
63dcaa4d7a сделала кое-как как правильно делать не знаю 2023-04-18 18:44:02 +04:00
3aff5cb712 нет json-ignore 2023-04-17 18:24:00 +04:00
1f4f290522 вроде все 2023-04-17 15:52:23 +04:00
1544973e7b сохранение перед исправлениями 2023-04-17 14:12:12 +04:00
7a95e50ac3 удалить 2023-04-15 13:26:20 +04:00
a794ee636f надеюсь это все 2023-04-15 13:25:42 +04:00
0fafffd509 potom dodelaetsya 2023-04-14 14:21:30 +04:00
e2a29f4b65 vite ne nado 2023-04-10 15:40:13 +04:00
aeeeec6e21 Merge remote-tracking branch 'origin/LW04_fail' into LW04_fail 2023-04-10 15:37:32 +04:00
30655dc5a8 order add feature 2023-04-10 15:37:07 +04:00
af4b235a51 commit 2023-04-09 23:05:42 +04:00
5d8837809a bugfix 2023-04-09 19:54:51 +04:00
cf01392e65 exceptions 2023-04-09 18:46:22 +04:00
6f5a9771f0 delete db 2023-04-09 17:45:32 +04:00
91fc7f04ef delete db 2023-04-09 17:44:56 +04:00
74ccd6738b commit front 5 2023-04-09 15:34:56 +04:00
3922ca678d commit front 4 2023-04-09 15:33:44 +04:00
83f8e345fe commit front 3 2023-04-09 15:33:08 +04:00
1331a59414 commit front 2 2023-04-09 15:32:25 +04:00
c7af79da4b commit front 1 2023-04-09 15:32:06 +04:00
6abe4f67cb commit 2023-04-09 15:24:34 +04:00
3211024750 commit 2023-04-09 15:22:02 +04:00
076bd4e61b commit 2023-04-09 15:20:17 +04:00
9d40b79426 контроллеры 2023-04-07 15:28:42 +04:00
465dcc3fae приколы 2023-04-07 14:55:33 +04:00
cfe166c85a hz 2023-03-27 15:01:03 +04:00
77ce0752c1 Не знаю 2023-03-27 14:13:52 +04:00
82dcfd163c Ничего не работает 2023-03-27 03:46:21 +04:00
e6af154d0a Сохранение 2023-03-16 17:32:02 +04:00
a7c19cd750 Некоторые тесты всяких штук 2023-03-16 15:12:45 +04:00
0a40a6e2d1 Merge remote-tracking branch 'origin/LW03' into LW03 2023-03-16 00:57:52 +04:00
28263bf4f9 Убрали комментарий 2023-03-16 00:57:29 +04:00
63919836c4 Убрали комментарий 2023-03-15 23:57:08 +04:00
ba29a321f0 Ну вроде что-то работает 2023-03-15 23:52:50 +04:00
13226e0fa9 ниче не работает 2023-03-13 18:15:50 +04:00
cfcae77ad5 Merge remote-tracking branch 'origin/LW02' into LW02 2023-02-27 18:00:27 +04:00
5ff927f236 ЛР2 2023-02-27 17:59:04 +04:00
2138819860 ЛР2 2023-02-27 17:53:52 +04:00
102 changed files with 7194 additions and 734 deletions

4
.gitignore vendored
View File

@ -5,7 +5,7 @@ build/
!**/src/main/**/build/
!**/src/test/**/build/
node_modules
*.db
### STS ###
.apt_generated
.classpath
@ -36,3 +36,5 @@ out/
### VS Code ###
.vscode/
data.mv.db
data.trace.db

View File

@ -12,9 +12,27 @@ repositories {
mavenCentral()
}
jar {
enabled = false
}
dependencies {
implementation(project(':front'))
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'com.auth0:java-jwt:4.4.0'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
}
tasks.named('test') {

50
front/.gitignore vendored Normal file
View File

@ -0,0 +1,50 @@
# 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

53
front/build.gradle Normal file
View File

@ -0,0 +1,53 @@
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']
}

View File

@ -1,44 +0,0 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet" />
<title>Калькулятор</title>
</head>
<body>
<form class="mx-2 d-flex flex-column align-items-center text-center">
<div>
Первое число
<input id="first" class="form-control" type='number' value='0' />
</div>
<div>
Операция
<select class="form-select" id="operation">
<option value="1">+</option>
<option value="2">-</option>
<option value="3">*</option>
<option value="4">/</option>
</select>
</div>
<div>
Второе число
<input id="second" class="form-control" type='number' value='0' />
</div>
<div>
<button type="button" class="btn btn-primary" id="calculate">Тык</button>
</div>
<div>
Результат:
<p id="result"> </p>
</div>
</form>
</div>
<script src="script.js"></script>
</body>
</html>

3648
front/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,46 @@
{
"name": "int-prog",
"version": "1.0.0",
"main": "index.html",
"scripts": {
"start": "http-server -p 3000 ./",
"test": "echo \"Error: no test specified\" && exit 1"
},
"name": "cinema-react-2",
"version": "0.1.0",
"source": "./public/index.html",
"private": true,
"dependencies": {
"bootstrap": "5.2.1",
"@fortawesome/fontawesome-free": "6.2.0"
"@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": {
"http-server": "14.1.1"
"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"
]
}
}

12
front/public/index.html Normal file
View File

@ -0,0 +1,12 @@
<!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,39 +0,0 @@
const calculateButton = document.getElementById("calculate");
const first = document.getElementById("first");
const second = document.getElementById("second");
const select = document.getElementById("operation");
const result = document.getElementById("result");
calculateButton.onclick = function() {
calculate();
};
function calculate() {
switch (parseInt(select.value)) {
case 1:
doSmth("plus")
break;
case 2:
doSmth("minus")
break;
case 3:
doSmth("mult")
break;
case 4:
doSmth("div")
break;
};
}
function checkNum(res) {
if (res.indexOf(".") != -1)
return parseInt(res)
else
return res
}
function doSmth(address) {
fetch(`http://localhost:8080/${address}?first=${first.value}&second=${second.value}`)
.then(response => response.text())
.then(res => result.innerHTML = checkNum(res));
}

46
front/src/App.js Normal file
View File

@ -0,0 +1,46 @@
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: 'USER'},
{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='USER'/>}>
<Route element={<Users/>} path="/users"/>
</Route>
</Routes>
<Footer/>
</BrowserRouter>
</>
);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 297 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 339 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

BIN
front/src/images/search.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

BIN
front/src/images/search.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

BIN
front/src/images/vk.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

12
front/src/index.js Normal file
View File

@ -0,0 +1,12 @@
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

@ -0,0 +1,81 @@
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>
)
}

224
front/src/pages/Films.jsx Normal file
View File

@ -0,0 +1,224 @@
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>
)
}

249
front/src/pages/Orders.jsx Normal file
View File

@ -0,0 +1,249 @@
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

@ -0,0 +1,118 @@
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

@ -0,0 +1,53 @@
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

@ -0,0 +1,230 @@
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='Сеансы'/>
)
}

181
front/src/pages/Users.jsx Normal file
View File

@ -0,0 +1,181 @@
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

@ -0,0 +1,46 @@
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

@ -0,0 +1,15 @@
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

@ -0,0 +1,27 @@
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

@ -0,0 +1,11 @@
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

@ -0,0 +1,132 @@
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

@ -0,0 +1,18 @@
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

@ -0,0 +1,26 @@
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

@ -0,0 +1,13 @@
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

@ -0,0 +1,17 @@
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

@ -0,0 +1,16 @@
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

@ -0,0 +1,18 @@
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

@ -0,0 +1,13 @@
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

@ -0,0 +1,10 @@
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

@ -0,0 +1,10 @@
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

@ -0,0 +1,42 @@
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

@ -0,0 +1,22 @@
.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

@ -0,0 +1,23 @@
#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

@ -0,0 +1,83 @@
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

@ -0,0 +1,14 @@
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

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

View File

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

View File

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

View File

@ -1 +1,2 @@
rootProject.name = 'app'
include 'front'

View File

@ -2,42 +2,12 @@ package com.labwork1.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class AppApplication {
public static void main(String[] args) {
SpringApplication.run(AppApplication.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
@GetMapping("/plus")
public String plus(@RequestParam(required = false, defaultValue = "0") double first,
@RequestParam(required = false, defaultValue = "0") double second) {
return Double.toString(first + second);
}
@GetMapping("/minus")
public String minus(@RequestParam(required = false, defaultValue = "0") double first,
@RequestParam(required = false, defaultValue = "0") double second) {
return Double.toString(first - second);
}
@GetMapping("/mult")
public String mult(@RequestParam(required = false, defaultValue = "1") double first,
@RequestParam(required = false, defaultValue = "1") double second) {
return Double.toString(first * second);
}
@GetMapping("/div")
public String div(@RequestParam(required = false, defaultValue = "1") double first,
@RequestParam(required = false, defaultValue = "1") double second) {
if(second == 0)
{
return null;
}
return Double.toString(first/second);
}
public static void main(String[] args) {
SpringApplication.run(AppApplication.class, args);
}
}

View File

@ -1,12 +0,0 @@
package com.labwork1.app;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -0,0 +1,28 @@
package com.labwork1.app.configuration;
import com.labwork1.app.configuration.jwt.JwtFilter;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenAPI30Configuration {
public static final String API_PREFIX = "/api/1.0";
@Bean
public OpenAPI customizeOpenAPI() {
final String securitySchemeName = JwtFilter.TOKEN_BEGIN_STR;
return new OpenAPI()
.addSecurityItem(new SecurityRequirement()
.addList(securitySchemeName))
.components(new Components()
.addSecuritySchemes(securitySchemeName, new SecurityScheme()
.name(securitySchemeName)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")));
}
}

View File

@ -0,0 +1,14 @@
package com.labwork1.app.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordEncoderConfiguration {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,90 @@
package com.labwork1.app.configuration;
import com.labwork1.app.configuration.jwt.JwtFilter;
import com.labwork1.app.student.controller.CustomerController;
import com.labwork1.app.student.model.UserRole;
import com.labwork1.app.student.service.CustomerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
private final CustomerService userService;
private final JwtFilter jwtFilter;
public SecurityConfiguration(CustomerService userService) {
this.userService = userService;
this.jwtFilter = new JwtFilter(userService);
createAdminOnStartup();
}
private void createAdminOnStartup() {
final String admin = "admin";
if (userService.findByLogin(admin) == null) {
log.info("Admin user successfully created");
userService.createUser(admin, admin, admin, UserRole.ADMIN);
}
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
log.info("Creating security configuration");
http.cors()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests()
.requestMatchers("/", SPA_URL_MASK).permitAll()
.requestMatchers(HttpMethod.POST, CustomerController.URL_LOGIN).permitAll()
.requestMatchers(HttpMethod.POST, CustomerController.URL_SIGNUP).permitAll()
.anyRequest()
.authenticated()
.and()
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.anonymous();
return http.userDetailsService(userService).build();
}
@Bean
public AuthenticationManager authenticationManagerBean(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http
.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userService);
return authenticationManagerBuilder.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return web -> web.ignoring()
.requestMatchers(HttpMethod.OPTIONS, "/**")
.requestMatchers("/*.js")
.requestMatchers("/*.html")
.requestMatchers("/*.css")
.requestMatchers("/*.png")
.requestMatchers("/*.jpg")
.requestMatchers("/favicon.ico")
.requestMatchers("/swagger-ui/index.html")
.requestMatchers("/webjars/**")
.requestMatchers("/swagger-resources/**")
.requestMatchers("/v3/api-docs/**")
.requestMatchers("/h2-console");
}
}

View File

@ -0,0 +1,31 @@
package com.labwork1.app.configuration;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
class WebConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController(SecurityConfiguration.SPA_URL_MASK).setViewName("forward:/");
registry.addViewController("/notFound").setViewName("forward:/");
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
return container -> container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -0,0 +1,11 @@
package com.labwork1.app.configuration.jwt;
public class JwtException extends RuntimeException {
public JwtException(Throwable throwable) {
super(throwable);
}
public JwtException(String message) {
super(message);
}
}

View File

@ -0,0 +1,71 @@
package com.labwork1.app.configuration.jwt;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.labwork1.app.student.service.CustomerService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import java.io.IOException;
public class JwtFilter extends GenericFilterBean {
private static final String AUTHORIZATION = "Authorization";
public static final String TOKEN_BEGIN_STR = "Bearer ";
private final CustomerService userService;
public JwtFilter(CustomerService userService) {
this.userService = userService;
}
private String getTokenFromRequest(HttpServletRequest request) {
String bearer = request.getHeader(AUTHORIZATION);
if (StringUtils.hasText(bearer) && bearer.startsWith(TOKEN_BEGIN_STR)) {
return bearer.substring(TOKEN_BEGIN_STR.length());
}
return null;
}
private void raiseException(ServletResponse response, int status, String message) throws IOException {
if (response instanceof final HttpServletResponse httpResponse) {
httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
httpResponse.setStatus(status);
final byte[] body = new ObjectMapper().writeValueAsBytes(message);
response.getOutputStream().write(body);
}
}
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request instanceof final HttpServletRequest httpRequest) {
final String token = getTokenFromRequest(httpRequest);
if (StringUtils.hasText(token)) {
try {
final UserDetails user = userService.loadUserByToken(token);
final UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (JwtException e) {
raiseException(response, HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
return;
} catch (Exception e) {
e.printStackTrace();
raiseException(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
String.format("Internal error: %s", e.getMessage()));
return;
}
}
}
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,27 @@
package com.labwork1.app.configuration.jwt;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "jwt", ignoreInvalidFields = true)
public class JwtProperties {
private String devToken = "";
private Boolean isDev = true;
public String getDevToken() {
return devToken;
}
public void setDevToken(String devToken) {
this.devToken = devToken;
}
public Boolean isDev() {
return isDev;
}
public void setDev(Boolean dev) {
isDev = dev;
}
}

View File

@ -0,0 +1,107 @@
package com.labwork1.app.configuration.jwt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.Optional;
import java.util.UUID;
@Component
public class JwtProvider {
private final static Logger LOG = LoggerFactory.getLogger(JwtProvider.class);
private final static byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
private final static String ISSUER = "auth0";
private final Algorithm algorithm;
private final JWTVerifier verifier;
public JwtProvider(JwtProperties jwtProperties) {
if (!jwtProperties.isDev()) {
LOG.info("Generate new JWT key for prod");
try {
final MessageDigest salt = MessageDigest.getInstance("SHA-256");
salt.update(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
LOG.info("Use generated JWT key for prod \n{}", bytesToHex(salt.digest()));
algorithm = Algorithm.HMAC256(bytesToHex(salt.digest()));
} catch (NoSuchAlgorithmException e) {
throw new JwtException(e);
}
} else {
LOG.info("Use default JWT key for dev \n{}", jwtProperties.getDevToken());
algorithm = Algorithm.HMAC256(jwtProperties.getDevToken());
}
verifier = JWT.require(algorithm)
.withIssuer(ISSUER)
.build();
}
private static String bytesToHex(byte[] bytes) {
byte[] hexChars = new byte[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars, StandardCharsets.UTF_8);
}
public String generateToken(String login) {
final Date issueDate = Date.from(LocalDate.now()
.atStartOfDay(ZoneId.systemDefault())
.toInstant());
final Date expireDate = Date.from(LocalDate.now()
.plusDays(15)
.atStartOfDay(ZoneId.systemDefault())
.toInstant());
return JWT.create()
.withIssuer(ISSUER)
.withIssuedAt(issueDate)
.withExpiresAt(expireDate)
.withSubject(login)
.sign(algorithm);
}
private DecodedJWT validateToken(String token) {
try {
return verifier.verify(token);
} catch (JWTVerificationException e) {
throw new JwtException(String.format("Token verification error: %s", e.getMessage()));
}
}
public boolean isTokenValid(String token) {
if (!StringUtils.hasText(token)) {
return false;
}
try {
validateToken(token);
return true;
} catch (JwtException e) {
LOG.error(e.getMessage());
return false;
}
}
public Optional<String> getLoginFromToken(String token) {
try {
return Optional.ofNullable(validateToken(token).getSubject());
} catch (JwtException e) {
LOG.error(e.getMessage());
return Optional.empty();
}
}
}

View File

@ -0,0 +1,57 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.UserRole;
import com.labwork1.app.student.service.CinemaService;
import jakarta.validation.Valid;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/cinema")
public class CinemaController {
private final CinemaService cinemaService;
public CinemaController(CinemaService cinemaService) {
this.cinemaService = cinemaService;
}
@GetMapping("/{id}")
public CinemaDto getCinema(@PathVariable Long id) {
return new CinemaDto(cinemaService.findCinema(id));
}
@GetMapping
public List<CinemaDto> getCinemas() {
return cinemaService.findAllCinemas().stream()
.map(CinemaDto::new)
.toList();
}
@GetMapping("/search")
public List<CinemaDto> getCinemas(@RequestParam("request") String request) {
return cinemaService.findAllCinemas(request).stream()
.map(CinemaDto::new)
.toList();
}
@PostMapping
@Secured({UserRole.AsString.ADMIN})
public CinemaDto createCinema(@RequestBody @Valid CinemaDto cinemaDto) {
return new CinemaDto(cinemaService.addCinema(cinemaDto));
}
@PutMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public CinemaDto updateCinema(@RequestBody @Valid CinemaDto cinemaDto) {
return new CinemaDto(cinemaService.updateCinema(cinemaDto));
}
@DeleteMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public CinemaDto deleteCinema(@PathVariable Long id) {
return new CinemaDto(cinemaService.deleteCinema(id));
}
}

View File

@ -0,0 +1,32 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.Cinema;
import java.nio.charset.StandardCharsets;
public class CinemaDto {
private long id;
private String name;
private String image;
public CinemaDto() {
}
public CinemaDto(Cinema cinema) {
this.id = cinema.getId();
this.name = cinema.getName();
this.image = new String(cinema.getImage(), StandardCharsets.UTF_8);
}
public String getImage() {
return image;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
}

View File

@ -0,0 +1,86 @@
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.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
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();
}
@Secured({UserRole.AsString.ADMIN})
@GetMapping(OpenAPI30Configuration.API_PREFIX + URL_MAIN)
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);
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

@ -0,0 +1,45 @@
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

@ -0,0 +1,50 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.service.OrderService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/order")
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
@GetMapping("/{id}")
public OrderDto getOrder(@PathVariable Long id) {
return new OrderDto(orderService.findOrder(id));
}
@GetMapping
public List<OrderDto> getOrders() {
return orderService.findAllOrders().stream()
.map(OrderDto::new)
.toList();
}
@PostMapping("/{customer}")
public OrderDto createOrder(@PathVariable String customer) {
return new OrderDto(orderService.addOrder(customer));
}
@PutMapping("/{id}")
public OrderDto updateOrder(@PathVariable Long id,
@RequestParam("session") Long session,
@RequestParam(value = "count", required = false) Integer count) {
if (count == null)
return new OrderDto(orderService.deleteSessionInOrder(id, session, Integer.MAX_VALUE));
if (count > 0)
return new OrderDto(orderService.addSession(id, session, count));
return new OrderDto(orderService.deleteSessionInOrder(id, session, -count));
}
@DeleteMapping("/{id}")
public OrderDto deleteOrder(@PathVariable Long id) {
return new OrderDto(orderService.deleteOrder(id));
}
}

View File

@ -0,0 +1,45 @@
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.sql.Date;
import java.util.List;
public class OrderDto {
private long id;
private Date dateOfPurchase;
private String customer;
private List<OrderSessionDto> sessions;
public OrderDto() {
}
public OrderDto(Order order) {
this.id = order.getId();
this.dateOfPurchase = order.getDateOfPurchase();
this.customer = order.getCustomer().getLogin();
if (order.getSessions() != null && order.getSessions().size() > 0)
this.sessions = order.getSessions()
.stream()
.map(x -> new OrderSessionDto(new SessionDto(x.getSession()),
x.getId().getOrderId(), x.getCount())).toList();
}
public long getId() {
return id;
}
public Date getDateOfPurchase() {
return dateOfPurchase;
}
public String getCustomer() {
return customer;
}
public List<OrderSessionDto> getSessions() {
return sessions;
}
}

View File

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

View File

@ -0,0 +1,64 @@
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.service.SessionService;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/session")
public class SessionController {
private final SessionService sessionService;
public SessionController(SessionService sessionService) {
this.sessionService = sessionService;
}
@GetMapping("/{id}")
public SessionDto getSession(@PathVariable Long id) {
return new SessionDto(sessionService.findSession(id));
}
@GetMapping
public List<SessionDto> getSessions() {
return sessionService.findAllSessions().stream()
.map(SessionDto::new)
.toList();
}
@PostMapping
@Secured({UserRole.AsString.ADMIN})
public SessionDto createSession(@RequestParam("price") String price,
@RequestParam("timestamp") String timestamp,
@RequestParam("cinemaid") Long cinemaId,
@RequestParam("capacity") Integer capacity) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy-MM-dd-HH:ss");
Date docDate = format.parse(timestamp.replace('T', '-'));
return new SessionDto(sessionService.findSession(
sessionService.addSession(Double.parseDouble(price),
new Timestamp(docDate.getTime()), cinemaId, capacity).getId()));
}
@PutMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public SessionDto updateSession(@PathVariable Long id,
@RequestParam("price") String price) {
return new SessionDto(sessionService.findSession(sessionService
.updateSession(id, Double.parseDouble(price)).getId()));
}
@DeleteMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public SessionDto deleteSession(@PathVariable Long id) {
return new SessionDto(sessionService.deleteSession(id));
}
}

View File

@ -0,0 +1,64 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.Session;
import com.labwork1.app.student.model.SessionExtension;
import java.sql.Timestamp;
public class SessionDto {
private long id;
private Double price;
private Timestamp timestamp;
private CinemaDto cinema;
private Long capacity;
private int maxCount;
public SessionDto() {
}
public SessionDto(SessionExtension session) {
this.id = session.getId();
this.price = session.getPrice();
this.timestamp = session.getTimestamp();
this.capacity = session.getCapacity();
this.maxCount = session.getMaxCount();
if (session.getCinema() != null) {
this.cinema = new CinemaDto(session.getCinema());
} else this.cinema = null;
}
public SessionDto(Session session) {
this.id = session.getId();
this.price = session.getPrice();
this.timestamp = session.getTimestamp();
this.maxCount = session.getMaxCount();
if (session.getCinema() != null) {
this.cinema = new CinemaDto(session.getCinema());
} else this.cinema = null;
}
public int getMaxCount() {
return maxCount;
}
public long getId() {
return id;
}
public Double getPrice() {
return price;
}
public Timestamp getTimestamp() {
return timestamp;
}
public Long getCapacity() {
return capacity;
}
public CinemaDto getCinema() {
return cinema;
}
}

View File

@ -0,0 +1,31 @@
package com.labwork1.app.student.controller;
public class UserSignupDto {
private String login;
private String password;
private String passwordConfirm;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}

View File

@ -0,0 +1,70 @@
package com.labwork1.app.student.model;
import com.labwork1.app.student.controller.CinemaDto;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Cinema {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotBlank(message = "name can't be null or empty")
@Column
private String name;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "cinema", cascade = CascadeType.REMOVE)
private List<Session> sessions;
@Lob
private byte[] image;
public Cinema() {
}
public Cinema(String name) {
this.name = name;
this.sessions = new ArrayList<>();
}
public Cinema(CinemaDto cinemaDto) {
this.name = cinemaDto.getName();
this.image = cinemaDto.getImage().getBytes();
this.sessions = new ArrayList<>();
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public List<Session> getSessions() {
return sessions;
}
public void setSession(Session session) {
if (session.getCinema().equals(this)) {
this.sessions.add(session);
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,100 @@
package com.labwork1.app.student.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true, length = 64)
@NotBlank(message = "login can't be null or empty")
@Size(min = 3, max = 64)
private String login;
@Column(nullable = false, length = 64)
@NotBlank(message = "password can't be null or empty")
@Size(min = 6, max = 64)
private String password;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = {CascadeType.MERGE,CascadeType.REMOVE})
private List<Order> orders;
private UserRole role;
public Customer() {
}
public Customer(String login, String password) {
this.login = login;
this.password = password;
this.orders = new ArrayList<>();
this.role = UserRole.USER;
}
public Customer(String login, String password, UserRole role) {
this.login = login;
this.password = password;
this.orders = new ArrayList<>();
this.role = role;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Customer customer = (Customer) o;
return Objects.equals(id, customer.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Customer {" +
"id=" + id +
", login='" + login + '\'' +
", password='" + password + '\'' +
'}';
}
public UserRole getRole() {
return role;
}
public Long getId() {
return id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Order> getOrders() {
return orders;
}
public void setOrder(Order order) {
if (order.getCustomer().equals(this)) {
this.orders.add(order);
}
}
}

View File

@ -0,0 +1,102 @@
package com.labwork1.app.student.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "tab_order")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull(message = "dateOfPurchase can't be null or empty")
@Temporal(TemporalType.DATE)
private Date dateOfPurchase;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "customer_fk")
private Customer customer;
@OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade =
{
CascadeType.REMOVE,
CascadeType.MERGE,
CascadeType.PERSIST
}, orphanRemoval = true)
private List<OrderSession> sessions;
public Order() {
}
public Order(Date dateOfPurchase) {
this.dateOfPurchase = dateOfPurchase;
}
public void addSession(OrderSession orderSession) {
if (sessions == null) {
sessions = new ArrayList<>();
}
if (!sessions.contains(orderSession))
this.sessions.add(orderSession);
}
public void removeSession(OrderSession orderSession){
if (sessions.contains(orderSession))
this.sessions.remove(orderSession);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Order order = (Order) o;
return Objects.equals(id, order.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Order {" +
"id=" + id +
", date='" + dateOfPurchase.toString() + '\'' +
", customer='" + customer.toString() + '\'';
}
public Long getId() {
return id;
}
public Date getDateOfPurchase() {
return dateOfPurchase;
}
public void setDateOfPurchase(Date dateOfPurchase) {
this.dateOfPurchase = dateOfPurchase;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
if (!customer.getOrders().contains(this)) {
customer.setOrder(this);
}
}
public List<OrderSession> getSessions() {
return sessions;
}
public void setSessions(List<OrderSession> sessions) {
this.sessions = sessions;
}
}

View File

@ -0,0 +1,62 @@
package com.labwork1.app.student.model;
import jakarta.persistence.*;
@Entity
@Table(name = "order_session")
public class OrderSession {
@EmbeddedId
private OrderSessionKey id;
@ManyToOne
@MapsId("sessionId")
@JoinColumn(name = "session_id")
private Session session;
@ManyToOne
@MapsId("orderId")
@JoinColumn(name = "order_id")
private Order order;
@Column(name = "count")
private Integer count;
public OrderSession() {
}
public OrderSession(Order order, Session session, Integer count) {
this.order = order;
this.session = session;
this.count = count;
this.id = new OrderSessionKey(session.getId(), order.getId());
}
public OrderSessionKey getId() {
return id;
}
public void setId(OrderSessionKey id) {
this.id = id;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
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,48 @@
package com.labwork1.app.student.model;
import jakarta.persistence.Embeddable;
import java.io.Serializable;
import java.util.Objects;
@Embeddable
public class OrderSessionKey implements Serializable {
private Long sessionId;
private Long orderId;
public OrderSessionKey() {
}
public OrderSessionKey(Long sessionId, Long orderId) {
this.sessionId = sessionId;
this.orderId = orderId;
}
public Long getSessionId() {
return sessionId;
}
public void setSessionId(Long sessionId) {
this.sessionId = sessionId;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof OrderSessionKey that)) return false;
return Objects.equals(getSessionId(), that.getSessionId()) && Objects.equals(getOrderId(), that.getOrderId());
}
@Override
public int hashCode() {
return Objects.hash(getSessionId(), getOrderId());
}
}

View File

@ -0,0 +1,135 @@
package com.labwork1.app.student.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
public class Session {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
@NotNull(message = "price can't be null or empty")
protected Double price;
@NotNull(message = "timestamp can't be null or empty")
@Column
@Temporal(TemporalType.TIMESTAMP)
protected Timestamp timestamp;
@OneToMany(mappedBy = "session", fetch = FetchType.EAGER)
private List<OrderSession> orders;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "cinema_fk")
protected Cinema cinema;
@NotNull(message = "maxCount can't be null or empty")
@Column
protected Integer maxCount;
public Session() {
}
public Integer getMaxCount() {
return maxCount;
}
public Session(Double price, Timestamp timestamp, Integer maxCount) {
this.price = price;
this.timestamp = timestamp;
this.maxCount = maxCount;
}
public Session(Session session) {
this.id = session.getId();
this.price = session.getPrice();
this.timestamp = session.getTimestamp();
this.orders = session.getOrders();
this.cinema = session.getCinema();
this.maxCount = session.getMaxCount();
}
public Cinema getCinema() {
return cinema;
}
public void setCinema(Cinema cinema) {
this.cinema = cinema;
if (!cinema.getSessions().contains(this)) {
cinema.setSession(this);
}
}
public void addOrder(OrderSession orderSession){
if (orders == null){
orders = new ArrayList<>();
}
if (!orders.contains(orderSession)) {
this.orders.add(orderSession);
}
}
public void removeOrder(OrderSession orderSession){
if (orders.contains(orderSession))
this.orders.remove(orderSession);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Session session = (Session) o;
return Objects.equals(id, session.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Session {" +
"id=" + id +
", price='" + price + '\'' +
", timestamp='" + timestamp.toString() + '\'' +
", maxCount='" + maxCount.toString() + '\'' +
", cinema='" + cinema.toString() + '\'' +
'}';
}
public Long getId() {
return id;
}
public Double getPrice() {
return price;
}
public void setId(Long id) {
this.id = id;
}
public void setOrders(List<OrderSession> orders) {
this.orders = orders;
}
public void setMaxCount(Integer maxCount) {
this.maxCount = maxCount;
}
public void setPrice(Double price) {
this.price = price;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public List<OrderSession> getOrders() {
return orders;
}
}

View File

@ -0,0 +1,17 @@
package com.labwork1.app.student.model;
public class SessionExtension extends Session {
private Long capacity;
public SessionExtension(Session session, Long capacity) {
super(session);
this.capacity = capacity;
}
public Long getCapacity() {
return capacity;
}
public void setCapacity(Long capacity) {
this.capacity = capacity;
}
}

View File

@ -0,0 +1,20 @@
package com.labwork1.app.student.model;
import org.springframework.security.core.GrantedAuthority;
public enum UserRole implements GrantedAuthority {
ADMIN,
USER;
private static final String PREFIX = "ROLE_";
@Override
public String getAuthority() {
return PREFIX + this.name();
}
public static final class AsString {
public static final String ADMIN = PREFIX + "ADMIN";
public static final String USER = PREFIX + "USER";
}
}

View File

@ -0,0 +1,13 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Cinema;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface CinemaRepository extends JpaRepository<Cinema, Long> {
@Query("select p from Cinema p where p.name like CONCAT('%',:search,'%')")
List<Cinema> findAll(@Param("search") String search);
}

View File

@ -0,0 +1,12 @@
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,12 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Order;
import com.labwork1.app.student.model.OrderSession;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("Select os from OrderSession os where os.order.id = :orderId and os.session.id = :sessionId")
OrderSession getOrderSession(@Param("orderId") Long orderId, @Param("sessionId") Long sessionId);
}

View File

@ -0,0 +1,24 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Session;
import com.labwork1.app.student.model.SessionExtension;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.Optional;
public interface SessionRepository extends JpaRepository<Session, Long> {
@Query("Select sum(os.count) from OrderSession os where os.session.id = :sessionId")
Optional<Integer> getCapacity(@Param("sessionId") Long sessionId);
@Query("Select new com.labwork1.app.student.model.SessionExtension(s, sum(os.count)) from Session s " +
"left join OrderSession os on s.id = os.session.id " +
"group by s")
List<SessionExtension> getSessionsWithCapacity();
@Query("Select new com.labwork1.app.student.model.SessionExtension(s, sum(os.count)) from Session s " +
"left join OrderSession os on s.id = os.session.id " +
"where s.id = :sessionId " +
"group by s")
Optional<SessionExtension> getSessionWithCapacity(@Param("sessionId") Long sessionId);
}

View File

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

View File

@ -0,0 +1,73 @@
package com.labwork1.app.student.service;
import com.labwork1.app.student.controller.CinemaDto;
import com.labwork1.app.student.model.Cinema;
import com.labwork1.app.student.repository.CinemaRepository;
import com.labwork1.app.util.validation.ValidatorUtil;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class CinemaService {
private final CinemaRepository cinemaRepository;
private final ValidatorUtil validatorUtil;
public CinemaService(CinemaRepository cinemaRepository, ValidatorUtil validatorUtil) {
this.cinemaRepository = cinemaRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Cinema addCinema(CinemaDto dto) {
final Cinema cinema = new Cinema(dto);
validatorUtil.validate(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
public Cinema findCinema(Long id) {
final Optional<Cinema> cinema = cinemaRepository.findById(id);
return cinema.orElseThrow(() -> new CinemaNotFoundException(id));
}
@Transactional
public List<Cinema> findAllCinemas(String search) {
return cinemaRepository.findAll(search);
}
@Transactional
public List<Cinema> findAllCinemas() {
return cinemaRepository.findAll();
}
@Transactional
public Cinema updateCinema(CinemaDto cinema) {
final Cinema currentCinema = findCinema(cinema.getId());
currentCinema.setName(cinema.getName());
currentCinema.setImage(cinema.getImage().getBytes());
validatorUtil.validate(currentCinema);
return cinemaRepository.save(currentCinema);
}
@Transactional
public Cinema deleteCinema(Long id) {
final Cinema currentCinema = findCinema(id);
cinemaRepository.delete(currentCinema);
return currentCinema;
}
@Transactional
public void deleteAllCinemas() {
cinemaRepository.deleteAll();
}
}

View File

@ -0,0 +1,10 @@
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

@ -0,0 +1,125 @@
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

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

View File

@ -0,0 +1,112 @@
package com.labwork1.app.student.service;
import com.labwork1.app.student.model.*;
import com.labwork1.app.student.repository.OrderRepository;
import com.labwork1.app.util.validation.ValidatorUtil;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Date;
import java.util.List;
import java.util.Optional;
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final CustomerService customerService;
private final SessionService sessionService;
private final ValidatorUtil validatorUtil;
public OrderService(OrderRepository orderRepository, CustomerService customerService, SessionService sessionService, ValidatorUtil validatorUtil) {
this.orderRepository = orderRepository;
this.customerService = customerService;
this.sessionService = sessionService;
this.validatorUtil = validatorUtil;
}
@Transactional
public Order addOrder(Long customerId) {
final Order order = new Order(new Date(System.currentTimeMillis()));
final Customer customer = customerService.findCustomer(customerId);
order.setCustomer(customer);
validatorUtil.validate(order);
return orderRepository.save(order);
}
@Transactional
public Order addOrder(String customerName) {
final Order order = new Order(new Date(System.currentTimeMillis()));
final Customer customer = customerService.findByLogin(customerName);
order.setCustomer(customer);
validatorUtil.validate(order);
return orderRepository.save(order);
}
@Transactional
public Order addSession(Long id, Long sessionId, Integer count) {
final Session currentSession = sessionService.findSession(sessionId);
final Order currentOrder = findOrder(id);
final OrderSession currentOrderSession = orderRepository.getOrderSession(id, sessionId);
final Integer currentSessionCapacity = currentSession.getMaxCount() - sessionService.getCapacity(sessionId);
if (currentSessionCapacity < count ||
(currentOrderSession != null && currentOrderSession.getCount() + count > currentSession.getMaxCount())) {
throw new IllegalArgumentException(String.format("No more tickets in session. Capacity: %1$s. Count: %2$s",
currentSessionCapacity, count));
}
if (currentOrderSession == null) {
currentOrder.addSession(new OrderSession(currentOrder, currentSession, count));
}
else if (currentOrderSession.getCount() + count <= currentSession.getMaxCount()) {
currentOrder.removeSession(currentOrderSession);
currentOrder.addSession(new OrderSession(currentOrder, currentSession,
currentOrderSession.getCount() + count));
}
return orderRepository.save(currentOrder);
}
@Transactional(readOnly = true)
public Order findOrder(Long id) {
final Optional<Order> order = orderRepository.findById(id);
return order.orElseThrow(() -> new OrderNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Order> findAllOrders() {
return orderRepository.findAll();
}
@Transactional
public Order deleteOrder(Long id) {
final Order currentOrder = findOrder(id);
orderRepository.delete(currentOrder);
return currentOrder;
}
@Transactional
public Order deleteSessionInOrder(Long id, Long session, Integer count) {
final Order currentOrder = findOrder(id);
final Session currentSession = sessionService.findSession(session);
final OrderSession currentOrderSession = orderRepository.getOrderSession(id, session);
if (currentOrderSession == null)
throw new EntityNotFoundException();
if (count >= currentOrderSession.getCount()) {
currentOrder.removeSession(currentOrderSession);
}
else {
currentOrder.removeSession(currentOrderSession);
currentOrder.addSession(new OrderSession(currentOrder, currentSession,
currentOrderSession.getCount() - count));
}
return orderRepository.save(currentOrder);
}
@Transactional
public void deleteAllOrders() {
orderRepository.deleteAll();
}
}

View File

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

View File

@ -0,0 +1,81 @@
package com.labwork1.app.student.service;
import com.labwork1.app.student.model.Cinema;
import com.labwork1.app.student.model.Session;
import com.labwork1.app.student.model.SessionExtension;
import com.labwork1.app.student.repository.SessionRepository;
import com.labwork1.app.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;
@Service
public class SessionService {
private final SessionRepository sessionRepository;
private final CinemaService cinemaService;
private final ValidatorUtil validatorUtil;
public SessionService(SessionRepository sessionRepository,
CinemaService cinemaService, ValidatorUtil validatorUtil) {
this.sessionRepository = sessionRepository;
this.cinemaService = cinemaService;
this.validatorUtil = validatorUtil;
}
@Transactional
public Session addSession(Double price, Timestamp date, Long cinemaId, Integer capacity) {
final Session session = new Session(price, date, capacity);
final Cinema cinema = cinemaService.findCinema(cinemaId);
session.setCinema(cinema);
validatorUtil.validate(session);
return sessionRepository.save(session);
}
@Transactional(readOnly = true)
public SessionExtension findSession(Long id) {
return sessionRepository.getSessionWithCapacity(id)
.orElseThrow(() -> new SessionNotFoundException(id));
}
@Transactional(readOnly = true)
public Session findBaseSession(Long id) {
final Optional<Session> session = sessionRepository.findById(id);
return session.orElseThrow(() -> new SessionNotFoundException(id));
}
@Transactional(readOnly = true)
public List<SessionExtension> findAllSessions() {
return sessionRepository.getSessionsWithCapacity();
}
@Transactional
public Session updateSession(Long id, Double price) {
final Session currentSession = findBaseSession(id);
currentSession.setPrice(price);
validatorUtil.validate(currentSession);
return sessionRepository.save(currentSession);
}
@Transactional
public Session deleteSession(Long id) {
final Session currentSession = findBaseSession(id);
// все равно сеанс не удалился бы, который участвует в заказах
// для отслеживания операции с ошибкой
if (currentSession.getOrders().size() > 0)
throw new IllegalArgumentException();
sessionRepository.delete(currentSession);
return currentSession;
}
@Transactional
public void deleteAllSessions() {
sessionRepository.deleteAll();
}
@Transactional
public Integer getCapacity(Long sessionId) {
return sessionRepository.getCapacity(sessionId).orElse(0);
}
}

View File

@ -0,0 +1,7 @@
package com.labwork1.app.student.service;
public class UserExistsException extends RuntimeException {
public UserExistsException(String login) {
super(String.format("User '%s' already exists", login));
}
}

View File

@ -0,0 +1,45 @@
package com.labwork1.app.util.error;
import com.labwork1.app.student.service.CinemaNotFoundException;
import com.labwork1.app.student.service.CustomerNotFoundException;
import com.labwork1.app.student.service.OrderNotFoundException;
import com.labwork1.app.student.service.SessionNotFoundException;
import com.labwork1.app.util.validation.ValidationException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.stream.Collectors;
@ControllerAdvice
public class AdviceController {
@ExceptionHandler({
CustomerNotFoundException.class,
OrderNotFoundException.class,
SessionNotFoundException.class,
CinemaNotFoundException.class,
ValidationException.class,
IllegalArgumentException.class
})
public ResponseEntity<Object> handleException(Throwable e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException e) {
final ValidationException validationException = new ValidationException(
e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toSet()));
return handleException(validationException);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleUnknownException(Throwable e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@ -0,0 +1,13 @@
package com.labwork1.app.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException {
public ValidationException(String message) {
super(message);
}
public ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}
}

View File

@ -0,0 +1,30 @@
package com.labwork1.app.util.validation;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.springframework.stereotype.Component;
import java.util.Set;
import java.util.stream.Collectors;
@Component
public class ValidatorUtil {
private final Validator validator;
public ValidatorUtil() {
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
this.validator = factory.getValidator();
}
}
public <T> void validate(T object) {
final Set<ConstraintViolation<T>> errors = validator.validate(object);
if (!errors.isEmpty()) {
throw new ValidationException(errors.stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toSet()));
}
}
}

View File

@ -1 +1,12 @@
spring.main.banner-mode=off
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false
jwt.dev-token=my-secret-jwt
jwt.dev=true

View File

@ -1,13 +0,0 @@
package com.labwork1.app;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AppApplicationTests {
@Test
void contextLoads() {
}
}

Some files were not shown because too many files have changed in this diff Show More