Compare commits

...

41 Commits
master ... LW05

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

4
.gitignore vendored
View File

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

View File

@ -14,6 +14,21 @@ 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.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 Normal file
View File

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

53
front/build.gradle Normal file
View File

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

View File

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

3648
front/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

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

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

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

View File

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

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

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

After

Width:  |  Height:  |  Size: 297 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 339 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

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

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

View File

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

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

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

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

@ -0,0 +1,244 @@
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 [customerName, setCustomerName] = useState('');
const [customer, setCustomer] = useState([]);
const [sessionName, setSessionName] = useState('');
const [count, setCount] = useState(1);
const [session, setSession] = useState([]);
const [orderSessions, setOrderSessions] = useState([]);
useEffect(() => {
getAll('customer').then((data) => setCustomer(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 (customer.length <= 0) {
throw 'Form not submit'
}
handleSubmitCreate(e)
console.log('Form submit')
setCustomer('')
}
// принимаем событие от кнопки "добавить"
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?customer=${customerName}`, requestParams)
.then((data) => {
getCustomerOrders(customerName)
getAll('customer').then((data) => setCustomer(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 getCustomerOrders(id) {
Service.read(`customer/${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="customer" id="customer" value={customer.value} onChange={e => {
setCustomerName(e.target.value)
getCustomerOrders(e.target.value)
}} >
<option value='' defaultValue disabled>Выберите значение</option>
{customer ? customer.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">Customer</th>
<th scope="col">DateOfPurchase</th>
<th scope="col"></th>
</tr>
</thead>
<tbody id="tbody">
{users.map((user) => (
<OrderItem
item={user}
key={user.id}
editFunc={handleEdit}
removeFunc={handleDelete}
/>
))}
</tbody>
</table>
<ModalEdit visible={modalTable} setVisible={setModalTable}>
<form className="fs-4 description fw-bold d-flex flex-column align-items-center" id="frm-items-edit">
<div className="col-6">
<label className="form-label" htmlFor="session">Сеанс</label>
<select required className="form-control" name="session" id="session" value={session.value} onChange={e => setSessionName(e.target.value)} >
<option value='' defaultValue disabled>Выберите значение</option>
{session ? session.map(elem =>
<option key={elem.id} value={elem.id}>{elem.cinema.name} {new Date(elem.timestamp).toLocaleString('RU-ru')}</option>
) : 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

@ -0,0 +1,169 @@
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/customer"
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/customer?login=${login}&password=${password}`, requestParams)
.then(() => {
getAll()
})
};
function handleEdit(id) {
console.info(`Start edit script`);
Service.read(`customer/${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/customer/${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(`customer/${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

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

View File

@ -0,0 +1,191 @@
import { React, useState, useEffect } from 'react'
import ContentBlock from './components/ContentBlock'
import Service from './services/Service';
import ModalEdit from './components/ModalEdit';
import SessionItem from './components/SessionItem';
import CinemaDto from './models/CinemaDto'
export default function Sessions() {
const [price, setPrice] = useState(1);
const [timestamp, setTimestamp] = useState(new Date());
const [maxCount, setMaxCount] = useState(1);
const [priceEdit, setPriceEdit] = useState('');
const [users, setUsers] = useState([]);
const [error, setError] = useState(false);
const [modalTable, setModalTable] = useState(false);
// хук для запоминания индекса элемента, вызвавшего модальное окно
const [currEditItem, setCurrEditItem] = useState(0);
// для выпадающих значений
const [cinemaName, setCinemaName] = useState('');
const [cinema, setCinema] = useState([]);
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}&timestamp=${timestamp}&cinemaid=${cinemaName}&capacity=${maxCount}`, requestParams)
.then(() => {
getAll('session').then((data) => setUsers(data))
getAll('cinema').then((data) => setCinema(data))
})
.catch(function (error) {
console.error('Error:', error);
throw "Can't add session";
});
};
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={timestamp} onChange={e => setTimestamp(e.target.value)} placeholder="Введите дату" />
</div>
{error && timestamp.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод даты</label> : null}
<div>
<button className="btn btn-success my-3" type="button" onClick={handleSubmit}>Сохранить</button>
</div>
</form>
<table className="table mt-3 text-white">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Price</th>
<th scope="col">Cinema</th>
<th scope="col">Timestamp</th>
<th scope="col">Capacity</th>
<th scope="col">MaxCount</th>
<th scope="col"></th>
</tr>
</thead>
<tbody id="tbody">
{users.map((user) => (
<SessionItem
item={user}
key={user.id}
editFunc={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

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

View File

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

View File

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

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,10 +1,17 @@
package com.labwork1.app;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
public static final String REST_API = "/api";
@Override
public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");

View File

@ -0,0 +1,53 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.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

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

@ -0,0 +1,81 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.service.CinemaService;
import jakarta.validation.Valid;
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}"})
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}"})
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}")
public String deleteCinema(@PathVariable Long id) {
cinemaService.deleteCinema(id);
return "redirect:/cinema";
}
}

View File

@ -0,0 +1,47 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.WebConfiguration;
import com.labwork1.app.student.service.CustomerService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/customer")
public class CustomerController {
private final CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping("/{id}")
public CustomerDto getCustomer(@PathVariable Long id) {
return new CustomerDto(customerService.findCustomer(id));
}
@GetMapping
public List<CustomerDto> getCustomers() {
return customerService.findAllCustomers().stream()
.map(CustomerDto::new)
.toList();
}
@PostMapping
public CustomerDto createCustomer(@RequestParam("login") String login,
@RequestParam("password") String password) {
return new CustomerDto(customerService.addCustomer(login, password));
}
@PutMapping("/{id}")
public CustomerDto updateCustomer(@PathVariable Long id,
@RequestParam("login") String login,
@RequestParam("password") String password) {
return new CustomerDto(customerService.updateCustomer(id, login, password));
}
@DeleteMapping("/{id}")
public CustomerDto deleteCustomer(@PathVariable Long id) {
return new CustomerDto(customerService.deleteCustomer(id));
}
}

View File

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

View File

@ -0,0 +1,64 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.service.CustomerService;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/customer")
public class CustomerMvcController {
private final CustomerService customerService;
public CustomerMvcController(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping
public String getCustomers(Model model) {
model.addAttribute("customers",
customerService.findAllCustomers().stream()
.map(CustomerDto::new)
.toList());
return "customer";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editCustomer(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
model.addAttribute("customerDto", new CustomerDto());
} else {
model.addAttribute("customerId", id);
model.addAttribute("customerDto", new CustomerDto(customerService.findCustomer(id)));
}
return "customer-edit";
}
@PostMapping(value = {"/", "/{id}"})
public String saveCustomer(@PathVariable(required = false) Long id,
@ModelAttribute @Valid CustomerDto customerDto,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "customer-edit";
}
if (id == null || id <= 0) {
customerService.addCustomer(customerDto.getLogin(), customerDto.getPassword());
} else {
customerDto.setId(id);
customerService.updateCustomer(id, customerDto.getLogin(), customerDto.getPassword());
}
return "redirect:/customer";
}
@PostMapping("/delete/{id}")
public String deleteCustomer(@PathVariable Long id) {
customerService.deleteCustomer(id);
return "redirect:/customer";
}
}

View File

@ -0,0 +1,51 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.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("customer") Long customer) {
return new OrderDto(orderService.addOrder(customer));
}
@PutMapping("/{id}")
public OrderDto updateOrder(@PathVariable Long id,
@RequestParam("session") Long session,
@RequestParam(value = "count", required = false) Integer count) {
if (count == null)
return new OrderDto(orderService.deleteSessionInOrder(id, session, Integer.MAX_VALUE));
if (count > 0)
return new OrderDto(orderService.addSession(id, session, count));
return new OrderDto(orderService.deleteSessionInOrder(id, session, -count));
}
@DeleteMapping("/{id}")
public OrderDto deleteOrder(@PathVariable Long id) {
return new OrderDto(orderService.deleteOrder(id));
}
}

View File

@ -0,0 +1,71 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.Customer;
import com.labwork1.app.student.model.Order;
import com.labwork1.app.student.model.OrderSession;
import java.sql.Date;
import java.util.List;
public class OrderDto {
private long id;
private Date dateOfPurchase;
private Long customerId;
private String customer;
private List<OrderSessionDto> sessions;
public OrderDto() {
}
public OrderDto(Order order) {
this.id = order.getId();
this.dateOfPurchase = order.getDateOfPurchase();
this.customerId = order.getCustomer().getId();
this.customer = order.getCustomer().getLogin();
if (order.getSessions() != null && order.getSessions().size() > 0)
this.sessions = order.getSessions()
.stream()
.map(x -> new OrderSessionDto(new SessionDto(x.getSession()),
x.getId().getOrderId(), x.getCount())).toList();
}
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public void setId(long id) {
this.id = id;
}
public void setDateOfPurchase(Date dateOfPurchase) {
this.dateOfPurchase = dateOfPurchase;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public void setSessions(List<OrderSessionDto> sessions) {
this.sessions = sessions;
}
public long getId() {
return id;
}
public Date getDateOfPurchase() {
return dateOfPurchase;
}
public String getCustomer() {
return customer;
}
public List<OrderSessionDto> getSessions() {
return sessions;
}
}

View File

@ -0,0 +1,100 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.SessionExtension;
import com.labwork1.app.student.service.CustomerService;
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.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/order")
public class OrderMvcController {
private final OrderService orderService;
private final SessionService sessionService;
private final CustomerService customerService;
public OrderMvcController(OrderService orderService, SessionService sessionService, CustomerService customerService) {
this.orderService = orderService;
this.sessionService = sessionService;
this.customerService = customerService;
}
@GetMapping
public String getOrders(Model model) {
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) {
if (id == null || id <= 0) {
List<CustomerDto> customers = customerService.findAllCustomers().stream()
.map(CustomerDto::new)
.toList();
model.addAttribute("orderDto", new OrderDto());
model.addAttribute("customers", customers);
return "order-edit";
} else {
List<OrderSessionDto> temp = orderService.findOrder(id).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) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "order-edit";
}
orderService.addOrder(orderDto.getCustomerId());
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) {
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) {
orderService.deleteOrder(id);
return "redirect:/order";
}
}

View File

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

@ -0,0 +1,61 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.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.LocalDate;
import java.time.LocalDateTime;
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("timestamp") String timestamp,
@RequestParam("cinemaid") Long cinemaId,
@RequestParam("capacity") Integer capacity) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy-MM-dd-HH:mm");
Date docDate = format.parse(timestamp.replace('T', '-'));
return new SessionDto(sessionService.findSession(
sessionService.addSession(Double.parseDouble(price),
LocalDateTime.now(), 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

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

@ -0,0 +1,80 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.service.CinemaService;
import com.labwork1.app.student.service.SessionService;
import jakarta.validation.Valid;
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}"})
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}")
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 = "/")
public String saveSession(@RequestParam("price") String price,
@RequestParam("timestamp") LocalDateTime timestamp,
@RequestParam("cinemaid") Long cinemaId,
@RequestParam("maxCount") Integer capacity,
Model model) {
sessionService.addSession(Double.parseDouble(price), timestamp,
cinemaId, capacity);
return "redirect:/session";
}
@PostMapping("/delete/{id}")
public String deleteSession(@PathVariable Long id) {
sessionService.deleteSession(id);
return "redirect:/session";
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,62 @@
package com.labwork1.app.student.model;
import jakarta.persistence.*;
@Entity
@Table(name = "order_session")
public class OrderSession {
@EmbeddedId
private OrderSessionKey id;
@ManyToOne
@MapsId("sessionId")
@JoinColumn(name = "session_id")
private Session session;
@ManyToOne
@MapsId("orderId")
@JoinColumn(name = "order_id")
private Order order;
@Column(name = "count")
private Integer count;
public OrderSession() {
}
public OrderSession(Order order, Session session, Integer count) {
this.order = order;
this.session = session;
this.count = count;
this.id = new OrderSessionKey(session.getId(), order.getId());
}
public OrderSessionKey getId() {
return id;
}
public void setId(OrderSessionKey id) {
this.id = id;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}

View File

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

View File

@ -0,0 +1,138 @@
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 = "timestamp can't be null or empty")
@Column
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm")
protected LocalDateTime timestamp;
@OneToMany(mappedBy = "session", fetch = FetchType.EAGER)
private List<OrderSession> orders;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "cinema_fk")
protected Cinema cinema;
@NotNull(message = "maxCount can't be null or empty")
@Column
protected Integer maxCount;
public Session() {
}
public Integer getMaxCount() {
return maxCount;
}
public Session(Double price, LocalDateTime timestamp, Integer maxCount) {
this.price = price;
this.timestamp = timestamp;
this.maxCount = maxCount;
}
public Session(Session session) {
this.id = session.getId();
this.price = session.getPrice();
this.timestamp = session.getTimestamp();
this.orders = session.getOrders();
this.cinema = session.getCinema();
this.maxCount = session.getMaxCount();
}
public Cinema getCinema() {
return cinema;
}
public void setCinema(Cinema cinema) {
this.cinema = cinema;
if (!cinema.getSessions().contains(this)) {
cinema.setSession(this);
}
}
public void addOrder(OrderSession orderSession){
if (orders == null){
orders = new ArrayList<>();
}
if (!orders.contains(orderSession)) {
this.orders.add(orderSession);
}
}
public void removeOrder(OrderSession orderSession){
if (orders.contains(orderSession))
this.orders.remove(orderSession);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Session session = (Session) o;
return Objects.equals(id, session.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Session {" +
"id=" + id +
", price='" + price + '\'' +
", timestamp='" + timestamp.toString() + '\'' +
", maxCount='" + maxCount.toString() + '\'' +
", cinema='" + cinema.toString() + '\'' +
'}';
}
public Long getId() {
return id;
}
public Double getPrice() {
return price;
}
public void setId(Long id) {
this.id = id;
}
public void setOrders(List<OrderSession> orders) {
this.orders = orders;
}
public void setMaxCount(Integer maxCount) {
this.maxCount = maxCount;
}
public void setPrice(Double price) {
this.price = price;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
public List<OrderSession> getOrders() {
return orders;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,60 @@
package com.labwork1.app.student.service;
import com.labwork1.app.student.model.Customer;
import com.labwork1.app.student.repository.CustomerRepository;
import com.labwork1.app.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class CustomerService {
private final CustomerRepository customerRepository;
private final ValidatorUtil validatorUtil;
public CustomerService(CustomerRepository customerRepository, ValidatorUtil validatorUtil) {
this.customerRepository = customerRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Customer addCustomer(String login, String password) {
final Customer customer = new Customer(login, password);
validatorUtil.validate(customer);
return customerRepository.save(customer);
}
@Transactional(readOnly = true)
public Customer findCustomer(Long id) {
final Optional<Customer> customer = customerRepository.findById(id);
return customer.orElseThrow(() -> new CustomerNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Customer> findAllCustomers() {
return customerRepository.findAll();
}
@Transactional
public Customer updateCustomer(Long id, String login, String password) {
final Customer currentCustomer = findCustomer(id);
currentCustomer.setLogin(login);
currentCustomer.setPassword(password);
validatorUtil.validate(currentCustomer);
return customerRepository.save(currentCustomer);
}
@Transactional
public Customer deleteCustomer(Long id) {
final Customer customer = findCustomer(id);
customerRepository.deleteById(id);
return customer;
}
@Transactional
public void deleteAllCustomers() {
customerRepository.deleteAll();
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,75 @@
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 List<SessionExtension> findAllSessions() {
return sessionRepository.getSessionsWithCapacity();
}
@Transactional
public Session updateSession(Long id, Double price) {
final Session currentSession = findSession(id);
currentSession.setPrice(price);
validatorUtil.validate(currentSession);
return sessionRepository.save(currentSession);
}
@Transactional
public Session deleteSession(Long id) {
final Session currentSession = findSession(id);
// все равно сеанс не удалился бы, который участвует в заказах
// для отслеживания операции с ошибкой
if (currentSession.getOrders().size() > 0)
throw new IllegalArgumentException();
sessionRepository.delete(currentSession);
return currentSession;
}
@Transactional
public void deleteAllSessions() {
sessionRepository.deleteAll();
}
@Transactional
public Integer getCapacity(Long sessionId) {
return sessionRepository.getCapacity(sessionId).orElse(0);
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,96 @@
html,
body {
background: #2b2d33;
}
.green-mark {
background-color: #38a65d;
}
.icon {
width: 50px;
height: 50px;
}
hr {
height: 2px !important;
}
.posterFilmPage{
width: 290px;
height: 437px;
}
/* for film-page */
.table {
color: #8f9398;
}
/* main */
@media screen and (max-width: 290px) {
.posterItem {
display: none !important;
}
.fs-1 {
margin-left: 1em !important;
}
}
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;
}
.posterItem {
width: 90px;
height: 90px;
margin-top: -10px;
}
form input {
max-width: 300px;
}
form select {
max-width: 300px;
}
table tbody tr td {
border: 0px !important;
}
footer {
flex: 0 0 auto !important;
background: #1a1c20;
color: #c2c2c2;
}
footer nav {
color: #c2c2c2;
}
header {
background: #1a1c20;
}
header a {
color: #c2c2c2;
text-decoration: none;
}
header a:hover {
color: white;
text-decoration: none;
}
a {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}

View File

@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 448 512"><!--! Font Awesome Pro 6.1.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. -->
<path d="M448 48V384c-63.09 22.54-82.34 32-119.5 32c-62.82 0-86.6-32-149.3-32C158.6 384 142.6 387.6 128 392.2v-64C142.6 323.6 158.6 320 179.2 320c62.73 0 86.51 32 149.3 32C348.9 352 364.1 349 384 342.7v-208C364.1 141 348.9 144 328.5 144c-62.82 0-86.6-32-149.3-32C128.4 112 104.3 132.6 64 140.7v307.3C64 465.7 49.67 480 32 480S0 465.7 0 448V63.1C0 46.33 14.33 32 31.1 32S64 46.33 64 63.1V76.66C104.3 68.63 128.4 48 179.2 48c62.73 0 86.51 32 149.3 32C365.7 80 384.9 70.54 448 48z"/>
</svg>

After

Width:  |  Height:  |  Size: 727 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

View File

@ -0,0 +1,33 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content_header">Фильм</div>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/cinema/{id}(id=${id})}" th:object="${cinemaDto}" enctype="multipart/form-data"
method="post">
<div class="mb-3">
<label for="name" class="form-label">Название</label>
<input type="text" class="form-control" id="name" th:field="${cinemaDto.name}" required="true">
</div>
<div class="mb-3">
<label for="multipartFile" class="form-label">Изображение</label>
<input type="file" class="form-control" id="multipartFile" th:name="multipartFile" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span th:if="${id == null}">Добавить</span>
<span th:if="${id != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/cinema}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,61 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content_header">Фильмы</div>
<div layout:fragment="content">
<div class="d-flex justify-content-between align-items-center">
<form action="#" th:action="@{/cinema/search/}" class="d-flex">
<input class="form-control m-1" type="text" name="request" required="true"/>
<button class="btn btn-secondary m-1" type="submit"><i class="fa-solid fa-magnifying-glass"></i></button>
</form>
<div class="d-flex justify-content-end">
<a type="button" class="btn btn-success m-1"
th:href="@{/cinema/edit}">
<i class="fa-solid fa-plus"></i>
</a>
</div>
</div>
<hr class="border border-0 bg-black"/>
<table class="table" id="tbl-items">
<tbody>
<tr th:each="cinema, iterator: ${cinemas}">
<td>
<img class="posterItem me-3" th:src="${cinema.image}" alt="${cinema.name}" align="left"/>
<div class="d-flex flex-row flex-wrap flex-grow-1 align-items-center">
<div class="pt-3 d-flex flex-column justify-content-start align-items-center mb-3 fs-6 fw-bold">
<p class="text-start">
<a class="text-white fs-5 fw-bold pt-3" th:text="${cinema.name}" href=""></a>
</p>
</div>
<div id="rightPanel"
class="d-flex flex-wrap justify-content-end text-white fw-bold fs-4 flex-grow-1">
<div class="rounded p-1 mx-2 green-mark">9.2</div>
<div>
<a type="button" class="m-1 btn btn-primary"
th:href="@{/cinema/edit/{id}(id=${cinema.id})}">
<i class="fa fa-pencil"></i>
</a>
<a type="button" class="m-1 btn btn-danger"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${cinema.id}').click()|">
<i class="fa fa-trash"></i>
</a>
</div>
</div>
<form th:action="@{/cinema/delete/{id}(id=${cinema.id})}" method="post">
<button th:id="'remove-' + ${cinema.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</div>
<hr class="border border-0 bg-black"/>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

View File

@ -0,0 +1,32 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content_header">Пользователь</div>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/customer/{id}(id=${id})}" th:object="${customerDto}" method="post">
<div class="mb-3">
<label for="login" class="form-label">Логин</label>
<input type="text" class="form-control" id="login" th:field="${customerDto.login}" required="true">
</div>
<div class="mb-3">
<label for="password" class="form-label">Пароль</label>
<input type="text" class="form-control" id="password" th:field="${customerDto.password}" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span th:if="${id == null}">Добавить</span>
<span th:if="${id != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/customer}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,51 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content_header">Пользователи</div>
<div layout:fragment="content">
<div class="d-flex justify-content-end">
<a class="btn btn-success button-fixed"
th:href="@{/customer/edit}">
<i class="fa-solid fa-plus"></i>
</a>
</div>
<table class="table text-white" id="tbl-items">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Логин</th>
<th scope="col">Пароль</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="customer, iterator: ${customers}">
<td th:text="${customer.id}"/>
<td th:text="${customer.login}"/>
<td th:text="${customer.password}"/>
<td>
<div>
<a type="button" class="m-1 btn btn-primary" th:href="@{/customer/edit/{id}(id=${customer.id})}">
<i class="fa fa-pencil"></i>
</a>
<a type="button" class="m-1 btn btn-danger"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${customer.id}').click()|">
<i class="fa fa-trash"></i>
</a>
</div>
<form th:action="@{/customer/delete/{id}(id=${customer.id})}" method="post">
<button th:id="'remove-' + ${customer.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

View File

@ -0,0 +1,57 @@
<!DOCTYPE html>
<html lang="ru"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8"/>
<title>Киносайт</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="icon" href="/favicon.svg">
<script type="text/javascript" src="/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="/webjars/bootstrap/5.1.3/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/webjars/font-awesome/6.1.0/css/all.min.css"/>
<link rel="stylesheet" href="/css/style.css"/>
</head>
<body class="d-flex flex-column h-100 text-white">
<header class="fs-4 fw-bold p-1">
<nav class="navbar navbar-expand-lg navbar-dark text-white">
<div class="container-fluid">
<a class="navbar-brand" href="/">
<i class="fa-solid fa-font-awesome"></i>
</a>
<button class="navbar-toggler" type="button"
data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse menu" id="navbarNav">
<ul class="navbar-nav">
<a class="nav-link" href="/">Главная</a>
<a class="nav-link" href="/cinema">Фильмы</a>
<a class="nav-link" href="/customer">Регистрация</a>
<a class="nav-link" href="/order">Заказы</a>
<a class="nav-link" href="/session">Сеансы</a>
<a class="nav-link" href="/h2-console/" target="_blank">Консоль H2</a>
</ul>
</div>
</div>
</nav>
</header>
<div class="container rounded my-5 p-4 content">
<div class="content_header rounded-top p-2 mb-2">
<h1 class="fs-1 fw-bold text-white ms-5">
<div layout:fragment="content_header">
</div>
</h1>
</div>
<div layout:fragment="content">
</div>
</div>
</body>
<th:block layout:fragment="scripts">
</th:block>
<footer class="d-flex align-items-center fw-bold fs-4 p-2 ps-5">2022 г.
<nav class="d-flex justify-content-center flex-grow-1"><a href="https://vk.com/id0" target="_blank"><img
class="icon" src="/vk.jpg" alt="VK"/></a></nav>
</footer>
</html>

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
<div><span th:text="${error}"></span></div>
<a href="/">На главную</a>
</div>
</body>
</html>

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content_header" th:text="'Главная'"></div>
<div layout:fragment="content">
<div>It's works!</div>
<a href="123">ERROR</a>
</div>
</body>
</html>

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