Compare commits

..

1 Commits

Author SHA1 Message Date
27ec055c62 отчеты 2023-06-15 13:35:28 +04:00
125 changed files with 709 additions and 7969 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,5 +36,3 @@ out/
### VS Code ###
.vscode/
data.mv.db
data.trace.db

View File

@ -14,24 +14,6 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0'
implementation 'org.webjars:font-awesome:6.1.0'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

50
front/.gitignore vendored
View File

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

View File

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

44
front/index.html Normal file
View File

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

3618
front/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

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

View File

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

39
front/script.js Normal file
View File

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

View File

@ -1,45 +0,0 @@
import { useRoutes, Outlet, BrowserRouter } 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'
function Router(props) {
return useRoutes(props.rootRoute);
}
export default function App() {
const routes = [
{ index: true, element: <Films /> },
{ path: '/films', element: <Films />, label: 'Главная' },
{ path: '/registration', element: <Registration />, label: 'Регистрация' },
{ path: '/sessions', element: <Sessions />, label: 'Сеансы' },
{ path: '/orders', element: <Orders />, label: 'Заказы' },
{ path: '/films/:id', element: <FilmPage /> },
{ path: '/search-same/:request', element: <SearchSame /> }
];
const links = routes.filter(route => route.hasOwnProperty('label'));
const rootRoute = [
{ path: '/', element: render(links), children: routes }
];
function render(links) {
return (
<>
<Header links={links} />
<Outlet />
<Footer />
</>
);
}
return (
<BrowserRouter>
<Router rootRoute={ rootRoute } />
</BrowserRouter>
);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 297 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 339 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 194 KiB

View File

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

View File

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

View File

@ -1,177 +0,0 @@
import { React, useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import FilmItem from './components/FilmItem'
import ContentBlock from './components/ContentBlock'
import ModalEdit from './components/ModalEdit'
import Banner from './components/Banner'
import '../styles/banner.css'
import CinemaDto from './models/CinemaDto'
import Service from './services/Service'
export default function Films() {
const navigate = useNavigate();
const fileReader = new FileReader()
const [items, setItems] = useState([]);
const [modalTable, setModalTable] = useState(false);
const [selectedImage, setSelectedImage] = useState();
// для инпутов
const [filmName, setFilmName] = useState('');
const [filmNameEdit, setFilmNameEdit] = useState('');
// хук для запоминания индекса элемента, вызвавшего модальное окно
const [currEditItem, setCurrEditItem] = useState(0);
// фильмы, страны, жанры
useEffect(() => {
Service.readAll('cinema')
.then(data => setItems(data));
}, []);
function handleDeleteFilm(id) {
console.info('Try to remove item');
Service.delete(`cinema/${id}`)
.then(() => {
setItems(items.filter(elem => elem.id !== id))
console.log("Removed")
});
};
function handleEditFilm(id) {
console.info(`Start edit script`);
Service.read(`cinema/${id}`)
.then(function (data) {
setFilmNameEdit(data.name);
setCurrEditItem(data.id);
setModalTable(true)
console.info('End edit script');
})
};
// принимаем событие от кнопки "добавить"
const handleSubmitCreate = (e) => {
e.preventDefault(); // страница перестает перезагружаться
const itemObject = new CinemaDto(selectedImage, filmName);
console.info('Try to add item');
Service.create('cinema', itemObject)
.then((data) => {
setItems([...items, data]);
setFilmName('');
console.info('Added');
})
.catch(function (error) {
console.error('Error:', error);
throw "Can't add item";
});
};
// принимаем событие от кнопки "сохранить изменения"
const handleSubmitEdit = (e, id) => {
console.info('Start synchronize edit');
e.preventDefault(); // страница перестает перезагружаться
const itemObject = new CinemaDto(selectedImage, filmNameEdit, id);
Service.update("cinema/" + id, itemObject)
.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)
}
function handleAddFilmToWillSee(data) {
const elem = CinemaDto.createFrom(data)
Service.create('willSee/', data)
}
// форма для добавления данных
const Form = (
<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>
)
const Content = (
<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={handleDeleteFilm}
editFunc={handleEditFilm}
openFilmPageFunc={(index) => navigate(`/films/${index}`)}
/>
)}
</tbody>
</table>
<ModalEdit visible={modalTable} setVisible={setModalTable}>
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit" onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
<div className="row">
<label className="form-label" htmlFor="filmPictureEdit">Изображение</label>
<input required className="form-control" name="filmPictureEdit" id="filmPictureEdit"
type="file"
onChange={changePicture} />
</div>
<div className="row">
<label className="form-label" htmlFor="filmNameEdit">Название</label>
<input value={filmNameEdit} onChange={e => setFilmNameEdit(e.target.value)} className="form-control" name='filmNameEdit' id="filmNameEdit" type="text" placeholder="Введите название" required />
</div>
<div className="text-center mt-3">
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить изменения</button>
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal" onClick={() => setModalTable(false)}>Отмена</button>
</div>
</form>
</ModalEdit>
</div>
);
return (
<div>
<Banner />
<ContentBlock valueBlock={Content} title='Фильмы' />
</div>
)
}

View File

@ -1,244 +0,0 @@
import { React, useState, useEffect } 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 [userName, setUserName] = useState('');
const [user, setUser] = useState([]);
const [sessionName, setSessionName] = useState('');
const [count, setCount] = useState(1);
const [session, setSession] = useState([]);
const [orderSessions, setOrderSessions] = useState([]);
useEffect(() => {
getAll('user').then((data) => setUser(data))
getAll('session').then((data) => setSession(data))
getAll('order').then((data) => setUsers(data))
}, [])
async function getAll(elem) {
const requestUrl = `http://localhost:8080/${elem}`
const response = await fetch(requestUrl)
const result = await response.json()
return result
}
function handleSubmit(e) {
e.preventDefault();
if (user.length <= 0) {
throw 'Form not submit'
}
handleSubmitCreate(e)
console.log('Form submit')
setUser('')
}
// принимаем событие от кнопки "добавить"
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/order?user=${userName}`, requestParams)
.then((data) => {
getUserOrders(userName)
getAll('user').then((data) => setUser(data))
})
.catch(function (error) {
console.error('Error:', error);
throw "Can't add order";
});
};
function handleEdit(id) {
console.info(`Start edit script`);
Service.read(`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: {
"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: {
"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);
});
};
function handleDelete(id) {
console.info('Try to remove item');
Service.delete(`order/${id}`)
.then(() => {
setUsers(users.filter(elem => elem.id !== id))
console.log("Removed")
});
};
async function getUserOrders(id) {
Service.read(`user/${id}`)
.then(function (data) {
setUsers(data.orders);
console.info('End');
})
.catch(e => { console.log('Error get orders') })
}
async function handleDeleteOrderSession(e, id, sessionId) {
console.info('Start delete session');
const requestParams = {
method: "PUT",
headers: {
"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 = (
<>
<select required className="form-select" name="user" id="user" value={user.value} onChange={e => {
setUserName(e.target.value)
getUserOrders(e.target.value)
}} >
<option value='' defaultValue disabled>Выберите значение</option>
{user ? user.map(elem =>
<option key={elem.id} value={elem.id}>{elem.login}</option>
) : null}
</select>
<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">User</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.dateTime).toLocaleString('RU-ru')}</option>
) : null}
</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.sessionId)}
/>
) : null}
</tbody>
</table>
</form>
</ModalEdit>
</>
)
return (
<ContentBlock className="d-flex justify-content-center flex-wrap" valueBlock={Content} title='Заказы' />
)
}

View File

@ -1,169 +0,0 @@
import { React, useState, useEffect } from 'react'
import ContentBlock from './components/ContentBlock'
import Service from './services/Service';
import ModalEdit from './components/ModalEdit';
import MyButton from './components/MyButton';
import UserItem from './components/UserItem';
export default function Registration() {
const [login, setLogin] = useState('');
const [password, setPassword] = useState('');
const [loginEdit, setLoginEdit] = useState('');
const [passwordEdit, setPasswordEdit] = useState('');
const [users, setUsers] = useState([]);
const [error, setError] = useState(false);
const [modalTable, setModalTable] = useState(false);
// хук для запоминания индекса элемента, вызвавшего модальное окно
const [currEditItem, setCurrEditItem] = useState(0);
useEffect(() => {
setError(false)
getAll()
}, [])
async function getAll() {
const requestUrl = "http://localhost:8080/user"
const response = await fetch(requestUrl)
const temp = await response.json()
setUsers(temp)
}
function handleSubmit(e) {
e.preventDefault();
if (login.length <= 0 || password.length <= 0) {
setError(true)
throw 'Form not submit'
}
handleSubmitCreate(e)
console.log('Form submit')
setError(false)
setLogin('')
setPassword('')
}
// принимаем событие от кнопки "добавить"
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/user?login=${login}&password=${password}`, requestParams)
.then(() => {
getAll()
})
};
function handleEdit(id) {
console.info(`Start edit script`);
Service.read(`user/${id}`)
.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: {
"Content-Type": "application/json"
}
};
const requestUrl = `http://localhost:8080/user/${id}?login=${loginEdit}&password=${passwordEdit}`
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);
});
};
function handleDelete(id) {
console.info('Try to remove item');
Service.delete(`user/${id}`)
.then(() => {
setUsers(users.filter(elem => elem.id !== id))
console.log("Removed")
});
};
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 <= 0 ? <label className="fs-6 text-danger">Неправильный ввод логина</label> : null}
<div>
<label className="form-label">Пароль</label>
<input className="form-control mainInput" type="text" value={password} onChange={e => setPassword(e.target.value)} placeholder="Введите пароль" />
</div>
{error && password.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод пароля</label> : null}
<div>
<button className="btn btn-success my-3" type="submit">Регистрация</button>
</div>
</form>
<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>
<ModalEdit visible={modalTable} setVisible={setModalTable}>
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit" onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
<div className="row">
<label className="form-label" htmlFor="loginEdit">Логин</label>
<input value={loginEdit} onChange={e => setLoginEdit(e.target.value)} className="form-control" name='loginEdit' id="loginEdit" type="text" placeholder="Введите логин" required />
</div>
<div className="row">
<label className="form-label" htmlFor="passwordEdit">Пароль</label>
<input value={passwordEdit} onChange={e => setPasswordEdit(e.target.value)} className="form-control" name='passwordEdit' id="passwordEdit" type="text" placeholder="Введите пароль" required />
</div>
<div className="text-center mt-3">
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить изменения</button>
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal" onClick={() => setModalTable(false)}>Отмена</button>
</div>
</form>
</ModalEdit>
</>
)
return (
<ContentBlock className="d-flex justify-content-center flex-wrap" valueBlock={Content} title='Регистрация' />
)
}

View File

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

View File

@ -1,191 +0,0 @@
import { React, useState, useEffect } from 'react'
import ContentBlock from './components/ContentBlock'
import Service from './services/Service';
import ModalEdit from './components/ModalEdit';
import SessionItem from './components/SessionItem';
import CinemaDto from './models/CinemaDto'
export default function Sessions() {
const [price, setPrice] = useState(1);
const [dateTime, 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([]);
useEffect(() => {
setError(false)
getAll('cinema').then((data) => setCinema(data))
getAll('session').then((data) => setUsers(data))
}, [])
async function getAll(elem) {
const requestUrl = `http://localhost:8080/${elem}`
const response = await fetch(requestUrl)
const result = await response.json()
return result
}
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}&dateTime=${dateTime}&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";
});
};
function handleEdit(id) {
console.info(`Start edit script`);
Service.read(`session/${id}`)
.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: {
"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);
});
};
function handleDelete(id) {
console.info('Try to remove item');
Service.delete(`session/${id}`)
.then(() => {
setUsers(users.filter(elem => elem.id !== id))
console.log("Removed")
});
};
const Content = (
<>
<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={dateTime} onChange={e => setTimestamp(e.target.value)} placeholder="Введите дату" />
</div>
{error && dateTime.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={handleEdit}
removeFunc={handleDelete}
/>
))}
</tbody>
</table>
<ModalEdit visible={modalTable} setVisible={setModalTable}>
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit" onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
<div className="row">
<label className="form-label" htmlFor="priceEdit">Цена</label>
<input value={priceEdit} onChange={e => setPriceEdit(e.target.value)} className="form-control" name='priceEdit' id="priceEdit" type="number" step="0.01" min="1" placeholder="Введите цену" required />
</div>
<div className="text-center mt-3">
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить изменения</button>
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal" onClick={() => setModalTable(false)}>Отмена</button>
</div>
</form>
</ModalEdit>
</>
)
return (
<ContentBlock className="d-flex justify-content-center flex-wrap" valueBlock={Content} title='Сеансы' />
)
}

View File

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

View File

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

View File

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

View File

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

View File

@ -1,43 +0,0 @@
import { React, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import searchImage from '../../images/search.jpg'
import '../../styles/styleHeader.css'
export default function Header() {
const navigate = useNavigate();
const [searchName, setSearchName] = useState('');
function handleSubmit(e) {
console.info('Try to search data');
e.preventDefault();
navigate(`/search-same/${searchName}`)
setSearchName('');
}
return (
<div>
<header className="fs-4 fw-bold p-1">
<nav className="navbar navbar-expand-md navbar-dark">
<div className="container-fluid">
<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="navbar-collapse collapse justify-content-end" id="navbarNav">
<div id="main"> <a onClick={() => navigate("/films")} className="text-decoration-none mx-5" style={{ cursor: "pointer" }}>Главная</a></div>
<form onSubmit={handleSubmit} className="col d-flex align-items-center needs-validation">
<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 className="d-flex justify-content-end flex-grow-1 navbar-nav">
<a onClick={() => navigate("/registration")} className="text-decoration-none mx-3" style={{ cursor: "pointer" }}>Регистрация</a>
<a onClick={() => navigate("/orders")} className="text-decoration-none mx-3" style={{ cursor: "pointer" }}>Заказы</a>
<a onClick={() => navigate("/sessions")} className="text-decoration-none mx-3" style={{ cursor: "pointer" }}>Сеансы</a>
</div>
</div>
</div>
</nav>
</header>
</div>
)
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,12 +2,42 @@ 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);
}
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);
}
}

View File

@ -1,23 +1,12 @@
package com.labwork1.app.configuration;
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.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
public static final String REST_API = "/api";
@Override
public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("login");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}
}

View File

@ -1,14 +0,0 @@
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 createPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -1,75 +0,0 @@
package com.labwork1.app.configuration;
import com.labwork1.app.student.controller.UserSignupMvcController;
import com.labwork1.app.student.model.UserRole;
import com.labwork1.app.student.service.UserService;
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.EnableGlobalMethodSecurity;
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.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
private static final String LOGIN_URL = "/login";
private final UserService userService;
public SecurityConfiguration(UserService userService) {
this.userService = 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 {
http.headers().frameOptions().sameOrigin().and()
.cors().and()
.csrf().disable()
.authorizeHttpRequests()
.requestMatchers(UserSignupMvcController.SIGNUP_URL).permitAll()
.requestMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(LOGIN_URL).permitAll()
.and()
.logout().permitAll();
return http.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("/css/**")
.requestMatchers("/js/**")
.requestMatchers("/templates/**")
.requestMatchers("/webjars/**")
.requestMatchers("/vk.jpg");
}
}

View File

@ -1,53 +0,0 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.configuration.WebConfiguration;
import com.labwork1.app.student.service.CinemaService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/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
public CinemaDto createCinema(@RequestBody @Valid CinemaDto cinemaDto) {
return new CinemaDto(cinemaService.addCinema(cinemaDto));
}
@PutMapping("/{id}")
public CinemaDto updateCinema(@RequestBody @Valid CinemaDto cinemaDto) {
return new CinemaDto(cinemaService.updateCinema(cinemaDto));
}
@DeleteMapping("/{id}")
public CinemaDto deleteCinema(@PathVariable Long id) {
return new CinemaDto(cinemaService.deleteCinema(id));
}
}

View File

@ -1,44 +0,0 @@
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 void setId(long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setImage(String image) {
this.image = image;
}
public String getImage() {
return image;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
}

View File

@ -1,86 +0,0 @@
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.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
@Controller
@RequestMapping("/cinema")
public class CinemaMvcController {
private final CinemaService cinemaService;
public CinemaMvcController(CinemaService cinemaService) {
this.cinemaService = cinemaService;
}
@GetMapping
public String getCinemas(Model model) {
model.addAttribute("cinemas",
cinemaService.findAllCinemas().stream()
.map(CinemaDto::new)
.toList());
return "cinema";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
@Secured({UserRole.AsString.ADMIN})
public String editCinema(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
model.addAttribute("cinemaDto", new CinemaDto());
} else {
model.addAttribute("cinemaId", id);
model.addAttribute("cinemaDto", new CinemaDto(cinemaService.findCinema(id)));
}
return "cinema-edit";
}
@GetMapping(value = "/search/")
public String searchCinema(@RequestParam String request,
Model model) {
List<CinemaDto> cinemas = cinemaService.findAllCinemas(request)
.stream().map(CinemaDto::new).toList();
model.addAttribute("cinemas", cinemas);
return "cinema";
}
@PostMapping(value = {"/", "/{id}"})
@Secured({UserRole.AsString.ADMIN})
public String saveCinema(@PathVariable(required = false) Long id,
@RequestParam("multipartFile") MultipartFile multipartFile,
@ModelAttribute @Valid CinemaDto cinemaDto,
BindingResult bindingResult,
Model model) throws IOException {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "cinema-edit";
}
if (id == null || id <= 0) {
cinemaDto.setImage("data:" + multipartFile.getContentType() + ";base64," + Base64.getEncoder().encodeToString(multipartFile.getBytes()));
cinemaService.addCinema(cinemaDto);
} else {
cinemaDto.setId(id);
cinemaDto.setImage("data:" + multipartFile.getContentType() + ";base64," + Base64.getEncoder().encodeToString(multipartFile.getBytes()));
cinemaService.updateCinema(cinemaDto);
}
return "redirect:/cinema";
}
@PostMapping("/delete/{id}")
@Secured({UserRole.AsString.ADMIN})
public String deleteCinema(@PathVariable Long id) {
cinemaService.deleteCinema(id);
return "redirect:/cinema";
}
}

View File

@ -1,51 +0,0 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.configuration.WebConfiguration;
import com.labwork1.app.student.service.OrderService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/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
public OrderDto createOrder(@RequestParam("user") Long user) {
return new OrderDto(orderService.addOrder(user));
}
@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

@ -1,61 +0,0 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.User;
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 Long userId;
private String user;
private List<OrderSessionDto> sessions;
public OrderDto() {
}
public OrderDto(Order order) {
this.id = order.getId();
this.userId = order.getUser().getId();
this.user = order.getUser().getLogin();
if (order.getSessions() != null && !order.getSessions().isEmpty())
this.sessions = order.getSessions()
.stream()
.map(x -> new OrderSessionDto(new SessionDto(x.getSession()),
x.getId().getOrderId(), x.getCount())).toList();
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public void setId(long id) {
this.id = id;
}
public void setUser(String user) {
this.user = user;
}
public void setSessions(List<OrderSessionDto> sessions) {
this.sessions = sessions;
}
public long getId() {
return id;
}
public String getUser() {
return user;
}
public List<OrderSessionDto> getSessions() {
return sessions;
}
}

View File

@ -1,128 +0,0 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.User;
import com.labwork1.app.student.model.Order;
import com.labwork1.app.student.model.SessionExtension;
import com.labwork1.app.student.model.UserRole;
import com.labwork1.app.student.service.UserService;
import com.labwork1.app.student.service.OrderService;
import com.labwork1.app.student.service.SessionService;
import jakarta.validation.Valid;
import org.slf4j.event.KeyValuePair;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Controller
@RequestMapping("/order")
public class OrderMvcController {
private final OrderService orderService;
private final SessionService sessionService;
private final UserService userService;
public OrderMvcController(OrderService orderService, SessionService sessionService, UserService userService) {
this.orderService = orderService;
this.sessionService = sessionService;
this.userService = userService;
}
@GetMapping
public String getOrders(Model model,
Principal principal) {
User user = userService.findByLogin(principal.getName());
if (user.getRole() == UserRole.USER)
model.addAttribute("orders",
orderService.findAllOrders().stream()
.map(OrderDto::new)
.filter(orderDto -> Objects.equals(orderDto.getUserId(),
user.getId()))
.toList());
else
model.addAttribute("orders",
orderService.findAllOrders().stream()
.map(OrderDto::new)
.toList());
return "order";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editOrder(@PathVariable(required = false) Long id,
Model model,
Principal principal) {
if (id == null || id <= 0) {
model.addAttribute("orderDto", new OrderDto());
return "order-edit";
} else {
Order order = orderService.findOrder(id);
User user = userService.findByLogin(principal.getName());
if (!Objects.equals(order.getUser().getId(), user.getId()) && user.getRole() == UserRole.USER)
return "redirect:/order";
List<OrderSessionDto> temp = order.getSessions()
.stream().map(x -> new OrderSessionDto(new SessionDto(x.getSession()),
x.getOrder().getId(), x.getCount())).toList();
List<SessionDto> sessions = sessionService.findAllSessions().stream()
.map(SessionDto::new)
.toList();
HashMap<SessionDto, Integer> orderSessions = new HashMap<>();
for (var os : temp) {
orderSessions.put(os.getSession(), os.getCount());
}
model.addAttribute("orderSessions", orderSessions);
model.addAttribute("sessions", sessions);
model.addAttribute("orderSessionDto", new OrderSessionDto());
return "ordersession";
}
}
@PostMapping(value = "/")
public String saveOrder(@ModelAttribute @Valid OrderDto orderDto,
BindingResult bindingResult,
Model model,
Principal principal) {
Long userId = userService.findByLogin(principal.getName()).getId();
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "order-edit";
}
orderService.addOrder(userId);
return "redirect:/order";
}
@PostMapping(value = {"/{id}"})
public String editOrder(@PathVariable Long id,
@RequestParam("session") Long session,
@RequestParam(value = "count", required = false) Integer count,
Model model,
Principal principal) {
Order order = orderService.findOrder(id);
User user = userService.findByLogin(principal.getName());
if (!Objects.equals(order.getUser().getId(), user.getId()) && user.getRole() == UserRole.USER)
return "/order";
if (count == null)
orderService.deleteSessionInOrder(id, session, Integer.MAX_VALUE);
else if (count > 0)
orderService.addSession(id, session, count);
return "redirect:/order/edit/" + id;
}
@PostMapping("/delete/{id}")
public String deleteOrder(@PathVariable Long id,
Principal principal) {
Order order = orderService.findOrder(id);
User user = userService.findByLogin(principal.getName());
if (!Objects.equals(order.getUser().getId(), user.getId()) && user.getRole() == UserRole.USER)
return "redirect:/order";
orderService.deleteOrder(id);
return "redirect:/order";
}
}

View File

@ -1,40 +0,0 @@
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 void setSession(SessionDto session) {
this.session = session;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public void setCount(Integer count) {
this.count = count;
}
public SessionDto getSession() {
return session;
}
public Long getOrderId() {
return orderId;
}
public Integer getCount() {
return count;
}
}

View File

@ -1,61 +0,0 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.configuration.WebConfiguration;
import com.labwork1.app.student.service.SessionService;
import org.springframework.web.bind.annotation.*;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/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
public SessionDto createSession(@RequestParam("price") String price,
@RequestParam("dateTime") String dateTime,
@RequestParam("cinemaId") Long cinemaId,
@RequestParam("capacity") Integer capacity) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:ss");
Date docDate = format.parse(dateTime.replace('T', '-'));
LocalDateTime localDateTime = LocalDateTime.ofInstant(docDate.toInstant(), ZoneId.systemDefault());
return new SessionDto(sessionService.findSession(
sessionService.addSession(Double.parseDouble(price),
localDateTime, cinemaId, capacity).getId()));
}
@PutMapping("/{id}")
public SessionDto updateSession(@PathVariable Long id,
@RequestParam("price") String price) {
return new SessionDto(sessionService.findSession(sessionService
.updateSession(id, Double.parseDouble(price)).getId()));
}
@DeleteMapping("/{id}")
public SessionDto deleteSession(@PathVariable Long id) {
return new SessionDto(sessionService.deleteSession(id));
}
}

View File

@ -1,89 +0,0 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.Session;
import com.labwork1.app.student.model.SessionExtension;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
public class SessionDto {
private long id;
private Double price;
@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm")
private LocalDateTime 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 CinemaDto getCinema() {
return cinema;
}
public void setCinema(CinemaDto cinema) {
this.cinema = cinema;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
public Long getCapacity() {
return capacity;
}
public void setCapacity(Long capacity) {
this.capacity = capacity;
}
public int getMaxCount() {
return maxCount;
}
public void setMaxCount(int maxCount) {
this.maxCount = maxCount;
}
}

View File

@ -1,86 +0,0 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.UserRole;
import com.labwork1.app.student.service.CinemaService;
import com.labwork1.app.student.service.SessionService;
import jakarta.validation.Valid;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
@Controller
@RequestMapping("/session")
public class SessionMvcController {
private final SessionService sessionService;
private final CinemaService cinemaService;
public SessionMvcController(SessionService sessionService, CinemaService cinemaService) {
this.sessionService = sessionService;
this.cinemaService = cinemaService;
}
@GetMapping
public String getSessions(Model model) {
model.addAttribute("sessions", sessionService.findAllSessions().stream()
.map(SessionDto::new)
.toList());
return "session";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
@Secured({UserRole.AsString.ADMIN})
public String editSession(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
List<CinemaDto> cinemas = cinemaService.findAllCinemas().stream()
.map(CinemaDto::new)
.toList();
model.addAttribute("sessionDto", new SessionDto());
model.addAttribute("cinemas", cinemas);
} else {
model.addAttribute("sessionId", id);
model.addAttribute("sessionDto", new SessionDto(sessionService.findSession(id)));
}
return "session-edit";
}
@PostMapping(value = "/{id}")
@Secured({UserRole.AsString.ADMIN})
public String editSession(@PathVariable Long id,
@ModelAttribute @Valid SessionDto sessionDto,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "session-edit";
}
sessionService.updateSession(id, sessionDto.getPrice());
return "redirect:/session";
}
@PostMapping(value = "/")
@Secured({UserRole.AsString.ADMIN})
public String saveSession(@RequestParam("price") String price,
@RequestParam("dateTime") LocalDateTime dateTime,
@RequestParam("cinemaId") Long cinemaId,
@RequestParam("maxCount") Integer capacity,
Model model) {
sessionService.addSession(Double.parseDouble(price), dateTime,
cinemaId, capacity);
return "redirect:/session";
}
@PostMapping("/delete/{id}")
@Secured({UserRole.AsString.ADMIN})
public String deleteSession(@PathVariable Long id) {
sessionService.deleteSession(id);
return "redirect:/session";
}
}

View File

@ -1,59 +0,0 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.configuration.WebConfiguration;
import com.labwork1.app.student.model.UserSignupDto;
import com.labwork1.app.student.service.UserService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/user")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
public UserDto getUser(@PathVariable Long id) {
return new UserDto(userService.findUser(id));
}
@GetMapping
public List<UserDto> getUsers() {
return userService.findAllUsers().stream()
.map(UserDto::new)
.toList();
}
@PostMapping
public UserDto createUser(@RequestBody @Valid UserSignupDto userSignupDto) {
return new UserDto(userService.addUser(userSignupDto));
}
@PutMapping("/{id}")
public UserDto updateUser(@PathVariable Long id,
@RequestParam("login") String login,
@RequestParam("password") String password) {
return new UserDto(userService.updateUser(id, login, password));
}
@PutMapping("/{id}/cart")
public UserDto updateUserCart(@PathVariable Long id,
@RequestParam("session") Long session,
@RequestParam(value = "count", required = false) Integer count) {
if (count == null)
return new UserDto(userService.deleteSessionInCart(id, session, Integer.MAX_VALUE));
if (count > 0)
return new UserDto(userService.addSession(id, session, count));
return new UserDto(userService.deleteSessionInCart(id, session, -count));
}
@DeleteMapping("/{id}")
public UserDto deleteUser(@PathVariable Long id) {
return new UserDto(userService.deleteUser(id));
}
}

View File

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

View File

@ -1,57 +0,0 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.UserRole;
import com.labwork1.app.student.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.IntStream;
@Controller
@RequestMapping("/user")
@Secured({UserRole.AsString.ADMIN})
public class UserMvcController {
private final UserService userService;
public UserMvcController(UserService userService) {
this.userService = userService;
}
@GetMapping
public String getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int size,
Model model) {
final Page<UserDto> users = userService.findAllPages(page, size)
.map(UserDto::new);
model.addAttribute("users", users);
final int totalPages = users.getTotalPages();
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
.boxed()
.toList();
model.addAttribute("pages", pageNumbers);
model.addAttribute("totalPages", totalPages);
return "user";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editUser(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
model.addAttribute("userDto", new UserDto());
} else {
model.addAttribute("userId", id);
model.addAttribute("userDto", new UserDto(userService.findUser(id)));
}
return "user-edit";
}
@PostMapping("/delete/{id}")
public String deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return "redirect:/user";
}
}

View File

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

View File

@ -1,41 +0,0 @@
package com.labwork1.app.student.controller;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class UserSignupDto {
@NotBlank
@Size(min = 3, max = 64)
private String login;
@NotBlank
@Size(min = 6, max = 64)
private String password;
@NotBlank
@Size(min = 6, max = 64)
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

@ -1,50 +0,0 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.User;
import com.labwork1.app.student.model.UserSignupDto;
import com.labwork1.app.student.service.UserService;
import jakarta.validation.Valid;
import jakarta.validation.ValidationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(UserSignupMvcController.SIGNUP_URL)
public class UserSignupMvcController {
public static final String SIGNUP_URL = "/signup";
private final UserService userService;
public UserSignupMvcController(UserService userService) {
this.userService = userService;
}
@GetMapping
public String showSignupForm(Model model) {
model.addAttribute("userDto", new UserSignupDto());
return "signup";
}
@PostMapping
public String signup(@ModelAttribute("userDto") @Valid UserSignupDto userSignupDto,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "signup";
}
try {
final User user = userService.addUser(
userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
return "redirect:/login?created=" + user.getLogin();
} catch (ValidationException e) {
model.addAttribute("errors", e.getMessage());
return "signup";
}
}
}

View File

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

@ -1,86 +0,0 @@
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;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_fk")
private User user;
@OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade =
{
CascadeType.REMOVE,
CascadeType.MERGE,
CascadeType.PERSIST
}, orphanRemoval = true)
private List<OrderSession> sessions;
public Order() {
}
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 +
", user='" + user.toString() + '\'';
}
public Long getId() {
return id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
if (!user.getOrders().contains(this)) {
user.setOrder(this);
}
}
public List<OrderSession> getSessions() {
return sessions;
}
public void setSessions(List<OrderSession> sessions) {
this.sessions = sessions;
}
}

View File

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

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

@ -1,171 +0,0 @@
package com.labwork1.app.student.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import org.springframework.format.annotation.DateTimeFormat;
import java.sql.Timestamp;
import java.time.LocalDateTime;
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 = "dateTime can't be null or empty")
@Column
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm")
protected LocalDateTime dateTime;
@OneToMany(mappedBy = "session", fetch = FetchType.EAGER)
private List<OrderSession> orders;
@OneToMany(mappedBy = "session", fetch = FetchType.EAGER)
private List<UserSession> users;
@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, LocalDateTime dateTime, Integer maxCount) {
this.price = price;
this.dateTime = dateTime;
this.maxCount = maxCount;
}
public Session(Session session) {
this.id = session.getId();
this.price = session.getPrice();
this.dateTime = session.getTimestamp();
this.orders = session.getOrders();
this.users = session.getUsers();
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);
}
public LocalDateTime getDateTime() {
return dateTime;
}
public void setUsers(List<UserSession> users) {
this.users = users;
}
public void setDateTime(LocalDateTime dateTime) {
this.dateTime = dateTime;
}
public List<UserSession> getUsers() {
return users;
}
public void addUser(UserSession userSession){
if (users == null){
users = new ArrayList<>();
}
if (!users.contains(userSession)) {
this.users.add(userSession);
}
}
public void removeUser(UserSession userSession){
if (users.contains(userSession))
this.users.remove(userSession);
}
@Override
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 + '\'' +
", dateTime='" + dateTime.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 LocalDateTime getTimestamp() {
return dateTime;
}
public void setTimestamp(LocalDateTime dateTime) {
this.dateTime = dateTime;
}
public List<OrderSession> getOrders() {
return orders;
}
}

View File

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

@ -1,132 +0,0 @@
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
@Table(name = "tab_user")
public class User {
@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 = "user", cascade = {CascadeType.MERGE,CascadeType.REMOVE})
private List<Order> orders;
@OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade =
{
CascadeType.REMOVE,
CascadeType.MERGE,
CascadeType.PERSIST
}, orphanRemoval = true)
private List<UserSession> sessions;
private UserRole role;
public User() {
}
public User(String login, String password) {
this.login = login;
this.password = password;
this.orders = new ArrayList<>();
this.sessions = new ArrayList<>();
this.role = UserRole.USER;
}
public User(String login, String password, UserRole role) {
this.login = login;
this.password = password;
this.orders = new ArrayList<>();
this.sessions = new ArrayList<>();
this.role = role;
}
public User(UserSignupDto userSignupDto) {
this.login = userSignupDto.getLogin();
this.password = userSignupDto.getPassword();
this.role = UserRole.USER;
}
public void addSession(UserSession userSession) {
if (sessions == null) {
sessions = new ArrayList<>();
}
if (!sessions.contains(userSession))
this.sessions.add(userSession);
}
public void removeSession(UserSession userSession){
if (sessions.contains(userSession))
this.sessions.remove(userSession);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "User {" +
"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<UserSession> getSessions() {
return sessions;
}
public List<Order> getOrders() {
return orders;
}
public void setOrder(Order order) {
if (order.getUser().equals(this)) {
this.orders.add(order);
}
}
}

View File

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

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

View File

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

View File

@ -1,40 +0,0 @@
package com.labwork1.app.student.model;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserSignupDto {
@NotBlank
@Size(min = 3, max = 64)
private String login;
@NotBlank
@Size(min = 6, max = 64)
private String password;
@NotBlank
@Size(min = 6, max = 64)
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

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

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

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

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

View File

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

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

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

@ -1,103 +0,0 @@
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 UserService userService;
private final SessionService sessionService;
private final ValidatorUtil validatorUtil;
public OrderService(OrderRepository orderRepository, UserService userService, SessionService sessionService, ValidatorUtil validatorUtil) {
this.orderRepository = orderRepository;
this.userService = userService;
this.sessionService = sessionService;
this.validatorUtil = validatorUtil;
}
@Transactional
public Order addOrder(Long userId) {
final Order order = new Order();
final User user = userService.findUser(userId);
order.setUser(user);
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

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

@ -1,81 +0,0 @@
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.time.LocalDateTime;
import java.util.List;
@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, LocalDateTime 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) {
return sessionRepository.findById(id)
.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

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

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