Compare commits

..

1 Commits
LW04 ... master

Author SHA1 Message Date
27ec055c62 отчеты 2023-06-15 13:35:28 +04:00
95 changed files with 707 additions and 6262 deletions

4
.gitignore vendored
View File

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

View File

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

50
front/.gitignore vendored
View File

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

View File

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

44
front/index.html Normal file
View File

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

3622
front/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

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

View File

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

39
front/script.js Normal file
View File

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

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 297 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 339 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 194 KiB

View File

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

View File

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

View File

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

View File

@ -1,244 +0,0 @@
import { React, useState, useEffect } from 'react'
import ContentBlock from './components/ContentBlock'
import Service from './services/Service';
import ModalEdit from './components/ModalEdit';
import OrderItem from './components/OrderItem';
import OrderSessionItem from './components/OrderSessionItem';
export default function Orders() {
const [users, setUsers] = useState([]);
const [modalTable, setModalTable] = useState(false);
// хук для запоминания индекса элемента, вызвавшего модальное окно
const [currEditItem, setCurrEditItem] = useState(0);
// для выпадающих значений
const [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

@ -1,169 +0,0 @@
import { React, useState, useEffect } from 'react'
import ContentBlock from './components/ContentBlock'
import Service from './services/Service';
import ModalEdit from './components/ModalEdit';
import MyButton from './components/MyButton';
import UserItem from './components/UserItem';
export default function Registration() {
const [login, setLogin] = useState('');
const [password, setPassword] = useState('');
const [loginEdit, setLoginEdit] = useState('');
const [passwordEdit, setPasswordEdit] = useState('');
const [users, setUsers] = useState([]);
const [error, setError] = useState(false);
const [modalTable, setModalTable] = useState(false);
// хук для запоминания индекса элемента, вызвавшего модальное окно
const [currEditItem, setCurrEditItem] = useState(0);
useEffect(() => {
setError(false)
getAll()
}, [])
async function getAll() {
const requestUrl = "http://localhost:8080/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

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

View File

@ -1,191 +0,0 @@
import { React, useState, useEffect } from 'react'
import ContentBlock from './components/ContentBlock'
import Service from './services/Service';
import ModalEdit from './components/ModalEdit';
import SessionItem from './components/SessionItem';
import CinemaDto from './models/CinemaDto'
export default function Sessions() {
const [price, setPrice] = useState(1);
const [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

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

View File

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

View File

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

View File

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

View File

@ -1,43 +0,0 @@
import { React, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import searchImage from '../../images/search.jpg'
import '../../styles/styleHeader.css'
export default function Header() {
const navigate = useNavigate();
const [searchName, setSearchName] = useState('');
function handleSubmit(e) {
console.info('Try to search data');
e.preventDefault();
navigate(`/search-same/${searchName}`)
setSearchName('');
}
return (
<div>
<header className="fs-4 fw-bold p-1">
<nav className="navbar navbar-expand-md navbar-dark">
<div className="container-fluid">
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="navbar-collapse collapse justify-content-end" id="navbarNav">
<div id="main"> <a onClick={() => navigate("/films")} className="text-decoration-none mx-5" style={{ cursor: "pointer" }}>Главная</a></div>
<form onSubmit={handleSubmit} className="col d-flex align-items-center needs-validation">
<input value={searchName} onChange={e => setSearchName(e.target.value)} className="form-control mainInput" type="text" name="text" search="true" rounded="true" required placeholder="Введите название" />
<button className="border border-0 p-0 ms-2" type="submit"><img className="icon" src={searchImage} alt="Поиск" /></button>
</form>
<div className="d-flex justify-content-end flex-grow-1 navbar-nav">
<a onClick={() => navigate("/registration")} className="text-decoration-none mx-3" style={{ cursor: "pointer" }}>Регистрация</a>
<a onClick={() => navigate("/orders")} className="text-decoration-none mx-3" style={{ cursor: "pointer" }}>Заказы</a>
<a onClick={() => navigate("/sessions")} className="text-decoration-none mx-3" style={{ cursor: "pointer" }}>Сеансы</a>
</div>
</div>
</div>
</nav>
</header>
</div>
)
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,14 +1,7 @@
package com.labwork1.app; package com.labwork1.app;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration @Configuration
public class WebConfiguration implements WebMvcConfigurer { public class WebConfiguration implements WebMvcConfigurer {
@ -16,20 +9,4 @@ public class WebConfiguration implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry) { public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*"); registry.addMapping("/**").allowedMethods("*");
} }
@Override
public void addViewControllers(ViewControllerRegistry registry) {
ViewControllerRegistration registration = registry.addViewController("/notFound");
registration.setViewName("forward:/index.html");
registration.setStatusCode(HttpStatus.OK);
// Alternative way (404 error hits the console):
// > registry.addViewController("/notFound").setViewName("forward:/index.html");
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
return container -> {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
};
}
} }

View File

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

View File

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

View File

@ -1,46 +0,0 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.service.CustomerService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/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

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

View File

@ -1,50 +0,0 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.service.OrderService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/order")
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
@GetMapping("/{id}")
public OrderDto getOrder(@PathVariable Long id) {
return new OrderDto(orderService.findOrder(id));
}
@GetMapping
public List<OrderDto> getOrders() {
return orderService.findAllOrders().stream()
.map(OrderDto::new)
.toList();
}
@PostMapping
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

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

View File

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

View File

@ -1,58 +0,0 @@
package com.labwork1.app.student.controller;
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.util.Date;
import java.util.List;
@RestController
@RequestMapping("/session")
public class SessionController {
private final SessionService sessionService;
public SessionController(SessionService sessionService) {
this.sessionService = sessionService;
}
@GetMapping("/{id}")
public SessionDto getSession(@PathVariable Long id) {
return new SessionDto(sessionService.findSession(id));
}
@GetMapping
public List<SessionDto> getSessions() {
return sessionService.findAllSessions().stream()
.map(SessionDto::new)
.toList();
}
@PostMapping
public SessionDto createSession(@RequestParam("price") String price,
@RequestParam("timestamp") String timestamp,
@RequestParam("cinemaid") Long cinemaId,
@RequestParam("capacity") Integer capacity) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy-MM-dd-HH:ss");
Date docDate = format.parse(timestamp.replace('T', '-'));
return new SessionDto(sessionService.findSession(
sessionService.addSession(Double.parseDouble(price),
new Timestamp(docDate.getTime()), cinemaId, capacity).getId()));
}
@PutMapping("/{id}")
public SessionDto updateSession(@PathVariable Long id,
@RequestParam("price") String price) {
return new SessionDto(sessionService.findSession(sessionService
.updateSession(id, Double.parseDouble(price)).getId()));
}
@DeleteMapping("/{id}")
public SessionDto deleteSession(@PathVariable Long id) {
return new SessionDto(sessionService.deleteSession(id));
}
}

View File

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

View File

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

View File

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

@ -1,102 +0,0 @@
package com.labwork1.app.student.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "tab_order")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

View File

@ -1,103 +0,0 @@
package com.labwork1.app.student.service;
import com.labwork1.app.student.model.*;
import com.labwork1.app.student.repository.OrderRepository;
import com.labwork1.app.util.validation.ValidatorUtil;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Date;
import java.util.List;
import java.util.Optional;
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final 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

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

View File

@ -1,74 +0,0 @@
package com.labwork1.app.student.service;
import com.labwork1.app.student.model.Cinema;
import com.labwork1.app.student.model.Session;
import com.labwork1.app.student.model.SessionExtension;
import com.labwork1.app.student.repository.SessionRepository;
import com.labwork1.app.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.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, Timestamp date, Long cinemaId, Integer capacity) {
final Session session = new Session(price, date, capacity);
final Cinema cinema = cinemaService.findCinema(cinemaId);
session.setCinema(cinema);
validatorUtil.validate(session);
return sessionRepository.save(session);
}
@Transactional(readOnly = true)
public SessionExtension findSession(Long id) {
return sessionRepository.getSessionWithCapacity(id)
.orElseThrow(() -> new SessionNotFoundException(id));
}
@Transactional(readOnly = true)
public 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

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

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

@ -1,30 +0,0 @@
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,10 +1 @@
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,13 @@
package com.labwork1.app;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AppApplicationTests {
@Test
void contextLoads() {
}
}

View File

@ -1,129 +0,0 @@
package com.labwork1.app;
import com.labwork1.app.student.model.*;
import com.labwork1.app.student.service.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.sql.Timestamp;
import java.util.List;
@SpringBootTest
public class JpaCustomerTests {
private static final Logger log = LoggerFactory.getLogger(JpaCustomerTests.class);
@Autowired
private CustomerService customerService;
@Autowired
private SessionService sessionService;
@Autowired
private OrderService orderService;
@Autowired
private CinemaService cinemaService;
@Test
void testOrder() {
sessionService.deleteAllSessions();
cinemaService.deleteAllCinemas();
orderService.deleteAllOrders();
customerService.deleteAllCustomers();
// 2 кино
final Cinema cinema1 = cinemaService.addCinema("Меню");
final Cinema cinema2 = cinemaService.addCinema("Аватар");
// 2 сеанса
final Session session1 = sessionService.addSession(300.0,
new Timestamp(System.currentTimeMillis()), cinema1.getId(), 10);
final Session session2 = sessionService.addSession( 200.0,
new Timestamp(System.currentTimeMillis()), cinema1.getId(), 10);
// проверка 2 сеанса у 1 кино
Assertions.assertEquals(cinemaService
.findCinema(cinema1.getId()).getSessions().size(), 2);
// 1 покупатель
final Customer customer1 = customerService.addCustomer("Родион", "Иванов");
customerService.updateCustomer(customer1.getId(), "Пчел", "Пчелов");
Assertions.assertEquals(customerService.findCustomer(customer1.getId()).getLogin(), "Пчел");
// 1 заказ, 1 копия заказа
final Order order0 = orderService.addOrder(customerService.findCustomer(customer1.getId()).getId());
final Order order1 = orderService.findOrder(order0.getId());
Assertions.assertEquals(order0, order1);
// у клиента точно есть заказ?
Assertions.assertEquals(customerService
.findCustomer(customer1.getId()).getOrders().size(), 1);
// 0 заказов
orderService.deleteAllOrders();
Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(-1L));
// 2 покупателя
final Customer customer2 = customerService.addCustomer("Иннокентий", "Иванов");
// 1 заказ
final Order order2 = orderService
.addOrder(customerService.findCustomer(customer2.getId()).getId());
// у заказа 2 сеанса
orderService.addSession(order2.getId(), session1.getId(), 2);
List<SessionExtension> result = sessionService.findAllSessions();
Assertions.assertEquals(sessionService.getCapacity(session1.getId()), 2);
orderService.addSession(order2.getId(), session2.getId(), 5);
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 5);
Assertions.assertThrows(IllegalArgumentException.class, () ->
orderService.addSession(order2.getId(), session2.getId(), 6));
// у заказа 1 сеанс
orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 10);
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
// заполнили всю 2 сессию
orderService.addSession(order2.getId(), session2.getId(), 10);
Assertions.assertEquals(sessionService.findAllSessions().size(), 2);
orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 4);
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 6);
orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 6);
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
Assertions.assertEquals(orderService.findOrder(order2.getId()).getSessions().size(), 1);
Assertions.assertEquals(orderService.findOrder(order2.getId()).getSessions().get(0).getId().getSessionId(), session1.getId());
// у заказа 1 сеанс
// 3 сеанса всего
final Session session3 = sessionService.addSession(300.0,
new Timestamp(System.currentTimeMillis()), cinema2.getId(), 10);
// удалили заказ2, у которого был сеанс1
orderService.deleteOrder(order2.getId());
Assertions.assertEquals(orderService.findAllOrders().size(), 0);
Assertions.assertEquals(sessionService.findAllSessions().size(), 3);
// создали 3 заказ у 2 покупателя
final Order order3 = orderService
.addOrder(customerService.findCustomer(customer2.getId()).getId());
orderService.addSession(order3.getId(), session2.getId(), 2);
orderService.addSession(order3.getId(), session3.getId(), 8);
orderService.addSession(order3.getId(), session1.getId(), 8);
// 2-ой покупатель удален
// 0 заказов после его удаления
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 2);
customerService.deleteCustomer(customer2.getId());
Assertions.assertThrows(CustomerNotFoundException.class, () -> customerService.findCustomer(customer2.getId()));
Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(order3.getId()));
Assertions.assertEquals(orderService.findAllOrders().size(), 0);
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
Assertions.assertEquals(sessionService.getCapacity(session3.getId()), 0);
Assertions.assertEquals(cinemaService.findAllCinemas().size(), 2);
Assertions.assertEquals(sessionService.findAllSessions().size(), 3);
// у синема1 1 и 2 сеанс, у синема2 3 сеанс. он удален
cinemaService.deleteCinema(cinema2.getId());
Assertions.assertEquals(cinemaService.findAllCinemas().size(), 1);
Assertions.assertEquals(sessionService.findAllSessions().size(), 2);
}
}

View File

@ -1,6 +0,0 @@
spring.datasource.url=jdbc:h2:mem:testdb
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=create-drop