Compare commits

...

No commits in common. "main" and "Lab_6Vue" have entirely different histories.

81 changed files with 13192 additions and 24 deletions

56
.gitignore vendored
View File

@ -1,26 +1,38 @@
# ---> Java
# Compiled class file
*.class
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
# Log file
*.log
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
# BlueJ files
*.ctxt
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
/front/node_modules/

View File

@ -1,2 +0,0 @@
# Pibd-22_Presnyakova.V.V_IP

48
build.gradle Normal file
View File

@ -0,0 +1,48 @@
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.8'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}
group = 'ru.ulstu.is'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
jar {
enabled = false
}
dependencies {
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0'
implementation 'org.webjars:font-awesome:6.1.0'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'com.auth0:java-jwt:4.4.0'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}

1116
data.trace.db Normal file

File diff suppressed because it is too large Load Diff

28
front/vue-project/.gitignore vendored Normal file
View File

@ -0,0 +1,28 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
/cypress/videos/
/cypress/screenshots/
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@ -0,0 +1,29 @@
# vue-project
This template should help get you started developing with Vue 3 in Vite.
## Recommended IDE Setup
[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin).
## Customize configuration
See [Vite Configuration Reference](https://vitejs.dev/config/).
## Project Setup
```sh
npm install
```
### Compile and Hot-Reload for Development
```sh
npm run dev
```
### Compile and Minify for Production
```sh
npm run build
```

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script type="module" src="/src/main.js"></script>
</body>
</html>

8463
front/vue-project/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,25 @@
{
"name": "vue-project",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.3.6",
"bootstrap": "^5.2.3",
"bootstrap-vue": "^2.23.1",
"sass-loader": "^13.2.2",
"vue": "^3.2.47",
"vue-router": "^4.1.6",
"vuex": "^4.1.0"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.0.0",
"@vitejs/plugin-vue-jsx": "^3.0.0",
"node-sass": "^8.0.0",
"vite": "^4.1.4"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -0,0 +1,19 @@
<script>
import Header from './components/Header.vue';
export default {
components: {
Header
}
}
</script>
<template>
<Header></Header>
<div class="container-fluid">
<router-view></router-view>
</div>
</template>
<style scoped>
</style>

View File

@ -0,0 +1,74 @@
/* color palette from <https://github.com/vuejs/theme> */
:root {
--vt-c-white: #ffffff;
--vt-c-white-soft: #f8f8f8;
--vt-c-white-mute: #f2f2f2;
--vt-c-black: #181818;
--vt-c-black-soft: #222222;
--vt-c-black-mute: #282828;
--vt-c-indigo: #2c3e50;
--vt-c-divider-light-1: rgba(60, 60, 60, 0.29);
--vt-c-divider-light-2: rgba(60, 60, 60, 0.12);
--vt-c-divider-dark-1: rgba(84, 84, 84, 0.65);
--vt-c-divider-dark-2: rgba(84, 84, 84, 0.48);
--vt-c-text-light-1: var(--vt-c-indigo);
--vt-c-text-light-2: rgba(60, 60, 60, 0.66);
--vt-c-text-dark-1: var(--vt-c-white);
--vt-c-text-dark-2: rgba(235, 235, 235, 0.64);
}
/* semantic color variables for this project */
:root {
--color-background: var(--vt-c-white);
--color-background-soft: var(--vt-c-white-soft);
--color-background-mute: var(--vt-c-white-mute);
--color-border: var(--vt-c-divider-light-2);
--color-border-hover: var(--vt-c-divider-light-1);
--color-heading: var(--vt-c-text-light-1);
--color-text: var(--vt-c-text-light-1);
--section-gap: 160px;
}
@media (prefers-color-scheme: dark) {
:root {
--color-background: var(--vt-c-black);
--color-background-soft: var(--vt-c-black-soft);
--color-background-mute: var(--vt-c-black-mute);
--color-border: var(--vt-c-divider-dark-2);
--color-border-hover: var(--vt-c-divider-dark-1);
--color-heading: var(--vt-c-text-dark-1);
--color-text: var(--vt-c-text-dark-2);
}
}
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
position: relative;
font-weight: normal;
}
body {
min-height: 100vh;
color: var(--color-text);
background: var(--color-background);
transition: color 0.5s, background-color 0.5s;
line-height: 1.6;
font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
font-size: 15px;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 261.76 226.69"><path d="M161.096.001l-30.225 52.351L100.647.001H-.005l130.877 226.688L261.749.001z" fill="#41b883"/><path d="M161.096.001l-30.225 52.351L100.647.001H52.346l78.526 136.01L209.398.001z" fill="#34495e"/></svg>

After

Width:  |  Height:  |  Size: 276 B

View File

@ -0,0 +1,35 @@
@import './base.css';
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
font-weight: normal;
}
a,
.green {
text-decoration: none;
color: hsla(160, 100%, 37%, 1);
transition: 0.4s;
}
@media (hover: hover) {
a:hover {
background-color: hsla(160, 100%, 37%, 0.2);
}
}
@media (min-width: 1024px) {
body {
display: flex;
place-items: center;
}
#app {
display: grid;
grid-template-columns: 1fr 1fr;
padding: 0 2rem;
}
}

View File

@ -0,0 +1,94 @@
<script>
import axios from 'axios';
import CatalogMixins from '../mixins/CatalogMixins.js';
import Component from '../models/Component.js';
import DataService from '../services/DataService';
export default {
mixins: [
CatalogMixins
],
data() {
return {
getAllUrl: 'component/',
dataUrl: 'component',
transformer: (data) => new Component(data),
headers: [
{ name: 'componentName', label: 'Название компонента' },
{ name: 'amount', label: 'Кол-во' }
],
dataFilterUrl: 'component/filter?'
}
},
methods: {
filter() {
let urlParams = ""
if (document.getElementById('componentNameFilterInput').value !== "") {
if (urlParams !== "") {
urlParams += "&";
}
urlParams += "componentName=" + this.componentName;
}
if (document.getElementById('componentAmountFilterInput').value !== "") {
if (urlParams !== "") {
urlParams += "&";
}
urlParams += "amount=" + this.amount;
}
DataService.readAll(this.dataFilterUrl + urlParams, (data) => new Component(data))
.then(data => {
this.items = data;
});
},
clearFilters() {
this.loadItems();
this.id = null;
this.componentName = null;
this.amount = null;
}
},
beforeCreate() {
if (localStorage.getItem("token") == null) {
this.$router.push("/login");
}
}
}
</script>
<template>
<div class="input-group mb-3">
<input type="text" class="form-control" id="componentNameFilterInput" placeholder="Name" required v-model="componentName">
<input type="number" class="form-control" id="componentAmountFilterInput" placeholder="Amount" required v-model="amount">
<button class="btn btn-primary" type="button" id="report-button"
@click.prevent="filter">Сформировать</button>
<button class="btn btn-outline-secondary" type="button" id="report-button"
@click.prevent="clearFilters">Очистить</button>
</div>
<ToolBar
@add="showAddModal"
@edit="showEditModal"
@remove="removeSelectedItems">
</ToolBar>
<DataTable
:headers="this.headers"
:items="this.items"
:selectedItems="this.selectedItems"
@dblclick="showEditModalDblClick">
</DataTable>
<Modal
:header="this.modal.header"
:confirm="this.modal.confirm"
v-model:visible="this.modalShow"
@done="saveItem">
<div class="mb-3">
<label for="name" class="form-label">Название компонента</label>
<input type="text" class="form-control" id="name" required v-model="data.componentName">
</div>
<div class="mb-3">
<label for="amount" class="form-label">Количество</label>
<input type="number" class="form-control" id="amount" required v-model="data.amount">
</div>
</Modal>
</template>

View File

@ -0,0 +1,70 @@
<script>
export default {
props: {
headers: Array,
items: Array,
selectedItems: Array
},
emits: {
dblclick: null
},
methods: {
rowClick(id) {
if (this.isSelected(id)) {
var index = this.selectedItems.indexOf(id);
if (index !== -1) {
this.selectedItems.splice(index, 1);
}
} else {
this.selectedItems.push(id);
}
},
rowDblClick(id) {
this.$emit('dblclick', id);
},
isSelected(id) {
return this.selectedItems.includes(id);
},
dataConvert(data) {
return data;
}
}
}
</script>
<template>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th v-for="header in this.headers"
:id="header.name"
scope="col">{{ header.label }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in this.items"
@click="rowClick(item.id)"
@dblclick="rowDblClick(item.id)"
:class="{selected: isSelected(item.id)}">
<th scope="row">{{ index + 1 }}</th>
<td v-for="header in this.headers">
{{ dataConvert(item[header.name]) }}
</td>
</tr>
</tbody>
</table>
</template>
<style scoped>
tbody tr:hover {
cursor: pointer;
}
tr.selected {
background-color: #0d6efd;
opacity: 80%;
}
tbody tr {
user-select: none;
}
</style>

View File

@ -0,0 +1,176 @@
<script>
import axios from 'axios';
import CatalogMixins from '../mixins/CatalogMixins.js';
import Favor from "../models/Favor";
import Component from '../models/Component';
import Order from '../models/Order';
import DataService from '../services/DataService';
//import Multiselect from 'vue-multiselect'
export default {
mixins: [
CatalogMixins
],
data() {
return {
getAllUrl: 'favor/',
dataUrl: 'favor',
transformer: (data) => new Favor(data),
headers: [
{ name: 'favorName', label: 'Название услуги' },
{ name: 'price', label: 'Цена' },
],
headersComps: [
{ name: 'componentName', label: 'Компонент' }
],
selectedItemsComps: [],
dataFilterUrl: 'favor/filter?',
orderUrl: 'order/',
orders: [],
componentUrl: 'component/',
components: [],
}
},
beforeCreate() {
if (localStorage.getItem("token") == null) {
this.$router.push("/login");
}
},
created() {
DataService.readAll(this.orderUrl, (data) => new Order(data))
.then(data => {
this.orders = data;
});
DataService.readAll(this.componentUrl, (data) => new Component(data))
.then(data => {
this.components = data;
});
},
methods: {
filter() {
let urlParams = ""
if (document.getElementById('favorNameFilterInput').value !== "") {
if (urlParams !== "") {
urlParams += "&";
}
urlParams += "favorName=" + this.favorName;
}
if (document.getElementById('priceFilterInput').value !== "") {
if (urlParams !== "") {
urlParams += "&";
}
urlParams += "price=" + this.price;
}
DataService.readAll(this.dataFilterUrl + urlParams, (data) => new Favor(data))
.then(data => {
this.items = data;
});
},
clearFilters() {
this.loadItems();
this.id = null;
this.favorName = null;
this.price = null;
},
addComponentToFavor(favorId) {
let componentId = document.getElementById('components').value;
let response = axios.post(`http://localhost:8080/api/favor/${favorId}/component?compId=${componentId}`);
console.log(response);
},
delComponentFromFavor(favorId, selectedItemsComps){
if (this.selectedItemsComps.length === 0) {
return;
}
if (confirm('Удалить выбранные элементы?')) {
const promises = [];
const self = this;
this.selectedItemsComps.forEach(item => {
promises.push(DataService.delete(this.dataUrl + "/" + favorId + "/component?compId=" + item));
});
Promise.all(promises).then((results) => {
results.forEach(function (id) {
const index = self.selectedItems.indexOf(id);
if (index === - 1) {
return;
}
self.selectedItems.splice(index, 1);
});
this.getItems();
});
}
},
itemsComps(componentIds) {
let result = [];
if (typeof componentIds === 'undefined') {
return;
}
this.components.forEach(component => {
for (let i = 0; i < componentIds.length; i++) {
if (component.id === componentIds[i]) {
result.push(component);
}
}
});
return result;
}
}
}
</script>
<template>
<div class="input-group mb-3">
<input type="text" class="form-control" id="favorNameFilterInput" placeholder="Услуга" required v-model="favorName">
<input type="number" class="form-control" id="priceFilterInput" placeholder="Цена" required v-model="price">
<button class="btn btn-primary" type="button" id="report-button"
@click.prevent="filter">Сформировать</button>
<button class="btn btn-outline-secondary" type="button" id="report-button"
@click.prevent="clearFilters">Очистить</button>
</div>
<ToolBar
@add="showAddModal"
@edit="showEditModal"
@remove="removeSelectedItems">
</ToolBar>
<DataTable
:headers="this.headers"
:items="this.items"
:selectedItems="this.selectedItems"
@dblclick="showEditModalDblClick">
</DataTable>
<Modal
:header="this.modal.header"
:confirm="this.modal.confirm"
v-model:visible="this.modalShow"
@done="saveItem">
<div class="mb-3">
<label for="name" class="form-label">Название услуги</label>
<input type="text" class="form-control" id="name" required v-model="data.favorName">
</div>
<div class="mb-3">
<label for="price" class="form-label">Цена</label>
<input type="number" class="form-control" id="price" required v-model="data.price">
</div>
<DataTable
:headers="this.headersComps"
:items="itemsComps(data.componentIds)"
:selectedItems="this.selectedItemsComps">
</DataTable>
<div class="mb-3">
<label for="components" class="form-label">Добавить компонент</label>
<select class="form-select" id="components" required>
<option disabled value="">Выберите компонент</option>
<option v-for="component in this.components"
:value="component.id">
{{ component.componentName }}
</option>
</select>
</div>
<button class="btn btn-outline-secondary" type="button" id="addComputerButton"
@click.prevent="addComponentToFavor(data.id)">Добавить</button>
<button class="btn btn-danger" type="button" id="delComputerButton"
@click.prevent="delComponentFromFavor(data.id, selectedItemsComps)">Удалить</button>
</Modal>
</template>

View File

@ -0,0 +1,41 @@
<script>
export default {
methods: {
getRoutes() {
return this.$router.options.routes.filter(route => route.meta?.hasOwnProperty('label'));
},
logout() {
localStorage.clear();
this.$router.push('/login');
}
}
}
</script>
<template>
<nav class="navbar navbar-expand-lg bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="/">
<i class="fa-solid fa-book"></i>
Service
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item"
v-for="route in this.getRoutes()">
<router-link class="nav-link" :to="route.path">{{ route.meta.label }}</router-link>
</li>
</ul>
</div>
<button class="btn btn-danger" @click.prevent="logout">Выход</button>
</div>
</nav>
</template>
<style scoped>
</style>

View File

@ -0,0 +1,96 @@
<script>
export default {
methods: {
getUserInfo () {
if (localStorage.getItem("token")) {
this.loginButton.classList.add("visually-hidden");
this.logoutButton.classList.remove("visually-hidden");
this.userSpan.innerText = localStorage.getItem("user");
} else {
this.loginButton.classList.remove("visually-hidden");
this.logoutButton.classList.add("visually-hidden");
this.userSpan.innerText = "";
localStorage.removeItem("user");
}
},
async login (login, password) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({login: login, password: password}),
};
const response = await fetch(this.hostURL + "/jwt/login", requestParams);
const result = await response.text();
if (response.status === 200) {
localStorage.setItem("token", result);
localStorage.setItem("user", login);
this.$router.push("/cabinets");
} else {
localStorage.removeItem("token");
localStorage.removeItem("user");
alert(result);
}
},
loginForm () {
this.login(this.loginInput.value, this.passwordInput.value).then(() => {
this.loginInput.value = "";
this.passwordInput.value = "";
this.getUserInfo();
});
},
logoutForm () {
localStorage.removeItem("token");
localStorage.removeItem("user");
this.getUserInfo();
},
toSignup() {
this.$router.push("/signup");
}
},
data() {
return {
hostURL: "http://localhost:8080",
loginInput: undefined,
passwordInput: undefined,
loginButton: undefined,
logoutButton: undefined,
userSpan: undefined
}
},
mounted() {
this.loginInput = document.getElementById("login");
this.passwordInput = document.getElementById("password");
this.loginButton = document.getElementById("loginBtn");
this.logoutButton = document.getElementById("logoutBtn");
this.userSpan = document.getElementById("user");
this.getUserInfo();
}
}
</script>
<template>
<form id="loginForm" onsubmit="return false">
<div class="row mt-3">
<div class="col-sm-4">
<label for="login" class="form-label visually-hidden">Login</label>
<input type="text" class="form-control" id="login" required placeholder="Логин">
</div>
<div class="col-sm-4 mt-3 mt-sm-0">
<label for="password" class="form-label visually-hidden">Password</label>
<input type="password" class="form-control" id="password" required placeholder="Пароль">
</div>
<div class="d-grid col-sm-2 mx-auto mt-3 mt-sm-0">
<button id="loginBtn" type="submit" class="btn btn-success" @click.prevent="loginForm">Войти</button>
<button id="logoutBtn" type="button" class="btn btn-danger visually-hidden" @click.prevent="logoutForm">Выйти</button>
</div>
<div class="d-grid col-sm-2 mx-auto mt-3 mt-sm-0">
<span id="user" class="align-middle"></span>
</div>
</div>
</form>
<div class="mt-3">
<button class="btn btn-outline-secondary" @click.prevent="toSignup">Регистрация</button>
</div>
</template>

View File

@ -0,0 +1,67 @@
<script>
export default {
props: {
header: String,
confirm: String,
visible: Boolean
},
emits: {
done: null,
'update:visible': (value) => {
if (typeof value !== 'boolean') {
throw 'Value is not a boolean';
}
return true;
}
},
methods: {
hide() {
this.$emit('update:visible', false);
},
done() {
if (this.$refs.form.checkValidity()) {
this.$emit('done');
this.hide();
} else {
this.$refs.form.reportValidity();
}
}
}
}
</script>
<template>
<div class="modal fade" tabindex="-1" aria-hidden="true"
:class="{ 'modal-show': this.visible, 'show': this.visible }">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">{{ header }}</h1>
<button type="button" class="btn-close" aria-label="Close"
@click.prevent="hide"></button>
</div>
<div class="modal-body">
<form @submit.prevent="done" ref="form">
<slot></slot>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
@click.prevent="hide">Закрыть</button>
<button type="button" class="btn btn-primary"
@click.prevent="done">{{ confirm }}</button>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.modal-show {
display: block;
}
.modal-content {
width: max-content;
}
</style>

View File

@ -0,0 +1,121 @@
<script>
import axios from 'axios';
import CatalogMixins from '../mixins/CatalogMixins.js';
import Order from "../models/Order";
import Favor from '../models/Favor';
import Component from '../models/Component';
import DataService from '../services/DataService';
export default {
mixins: [
CatalogMixins
],
data() {
return {
getAllUrl: 'order/',
dataUrl: 'order',
transformer: (data) => new Order(data),
headers: [
{ name: 'date', label: 'Дата' }
],
headersFavs: [
{ name: 'favorName', label: 'Название услуги' },
{ name: 'price', label: 'Цена' },
],
selectedItemsFavs: [],
dataFilterUrl: 'order/filter?',
favorUrl: 'favor/',
favors: [],
componentUrl: 'component/',
components: []
}
},
beforeCreate() {
if (localStorage.getItem("token") == null) {
this.$router.push("/login");
}
},
created() {
DataService.readAll(this.favorUrl, (data) => new Favor(data))
.then(data => {
this.favors = data;
});
DataService.readAll(this.componentUrl, (data) => new Component(data))
.then(data => {
this.components = data;
});
},
methods: {
filter() {
let urlParams = ""
if (document.getElementById('numberFilterInput').value !== "") {
urlParams += "number=" + this.number;
}
DataService.readAll(this.dataFilterUrl + urlParams, (data) => new Order(data))
.then(data => {
this.items = data;
});
},
clearFilters() {
this.loadItems();
this.id = null;
this.number = null;
},
addFavorInOrder(orderId) {
let favorId = document.getElementById('favors').value;
let response = axios.post(`http://localhost:8080/order/${orderId}/favor?favId=${favorId}`);
console.log(response);
},
itemsComps(favorIds) {
let result = [];
if (typeof favorIds === 'undefined') {
return;
}
this.favors.forEach(favor => {
for (let i = 0; i < favorIds.length; i++) {
if (favor.id === favorIds[i]) {
result.push(favor);
}
}
});
return result;
}
}
}
</script>
<template>
<ToolBar
@add="showAddModal"
@edit="showEditModal">
</ToolBar>
<DataTable
:headers="this.headers"
:items="this.items"
:selectedItems="this.selectedItems"
@dblclick="showEditModalDblClick">
</DataTable>
<Modal
:header="this.modal.header"
:confirm="this.modal.confirm"
v-model:visible="this.modalShow"
@done="saveItem">
<DataTable
:headers="this.headersFavs"
:items="itemsComps(data.favorIds)"
:selectedItems="this.selectedItemsFavs">
</DataTable>
<div class="mb-3">
<label for="favors" class="form-label">Добавить услуги</label>
<select class="form-select" id="favors" required>
<option disabled value="">Выберите услуги</option>
<option v-for="favor in this.favors"
:value="favor.id">
{{ favor.favorName }}
</option>
</select>
</div>
<button class="btn btn-outline-secondary" type="button" id="addFavorButton"
@click.prevent="addFavorInOrder(data.id)">Добавить</button>
</Modal>
</template>

View File

@ -0,0 +1,51 @@
<script>
import axios from "axios";
export default {
data() {
return {
data: []
}
},
methods: {
async createUser() {
const response = await axios.post("http://localhost:8080/signup", this.toJSON(this.data));
if (response.data !== "error") {
this.$router.push("/login");
} else {
document.getElementById('error').value = "Error!";
}
},
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;
}
}
}
</script>
<template>
<div class="mb-3">
<input type="text" name="login" class="form-control"
placeholder="Логин" required autofocus maxlength="64" v-model="data.login"/>
</div>
<div class="mb-3">
<input type="password" name="password" class="form-control"
placeholder="Пароль" required minlength="6" maxlength="64" v-model="data.password"/>
</div>
<div class="mb-3">
<input type="password" name="passwordConfirm" class="form-control"
placeholder="Пароль (подтверждение)" required minlength="6" maxlength="64" v-model="data.passwordConfirm"/>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success button-fixed" @click.prevent="createUser">Создать</button>
<a class="btn btn-primary button-fixed" href="/login">Назад</a>
</div>
<p id="error"></p>
</template>

View File

@ -0,0 +1,46 @@
<script>
export default {
props: {
},
emits: {
add: null,
edit: null,
remove: null
},
methods: {
add() {
this.$emit('add');
},
edit() {
this.$emit('edit');
},
remove() {
this.$emit('remove');
}
}
}
</script>
<template>
<div class="btn-group mt-2" role="group">
<button type="button" class="btn btn-success"
@click.prevent="add">
Добавить
</button>
<button type="button" class="btn btn-warning"
@click.prevent="edit">
Изменить
</button>
<button type="button" class="btn btn-danger"
@click.prevent="remove">
Удалить
</button>
</div>
</template>
<style scoped>
.btn {
min-width: 140px;
}
</style>

View File

@ -0,0 +1,45 @@
<script>
import CatalogMixins from '../mixins/CatalogMixins.js';
import User from '../models/User.js';
export default {
mixins: [
CatalogMixins
],
data() {
return {
getAllUrl: 'user',
dataUrl: 'user',
transformer: (data) => new User(data),
headers: [
{ name: 'id', label: 'ID' },
{ name: 'login', label: 'Логин' },
{ name: 'role', label: 'Роль' }
],
ifAdmin: Boolean
}
},
beforeCreate() {
if (localStorage.getItem("token") == null) {
this.$router.push("/login");
}
},
created() {
this.ifAdmin = localStorage.getItem("user") === "admin";
}
}
</script>
<template>
<div v-if="ifAdmin">
<DataTable
:headers="this.headers"
:items="this.items"
:selectedItems="this.selectedItems"
@dblclick="showEditModalDblClick">
</DataTable>
</div>
<div v-else>
<h2>Эта страница доступна только администраторам!</h2>
</div>
</template>

View File

@ -0,0 +1,26 @@
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import Components from './components/Components.vue'
import Favors from './components/Favors.vue'
import Orders from './components/Orders.vue'
import Login from "./components/Login.vue";
import Signup from "@/components/Signup.vue";
import Users from "@/components/Users.vue";
const routes = [
{ path: '/', redirect: '/components' },
{ path: '/components', component: Components, meta: { label: 'Компоненты' } },
{ path: '/favors', component: Favors, meta: { label: 'Услуги' } },
{ path: '/orders', component: Orders, meta: { label: 'Заказы' } },
{ path: '/users', component: Users, meta: { label: 'Пользователи' } },
{ path: '/login', component: Login},
{ path: '/signup', component: Signup}
]
const router = createRouter({
history: createWebHistory(),
linkActiveClass: 'active',
routes
})
createApp(App).use(router).mount('#app')

View File

@ -0,0 +1,102 @@
import ToolBar from '../components/ToolBar.vue';
import DataTable from '../components/DataTable.vue';
import Modal from '../components/Modal.vue';
import DataService from '../services/DataService';
const CatalogMixin = {
components: {
ToolBar, DataTable, Modal
},
data() {
return {
getAllUrl: undefined,
dataUrl: undefined,
transformer: undefined,
headers: [],
items: [],
selectedItems: [],
modal: {
header: undefined,
confirm: undefined,
},
modalShow: false,
data: undefined,
isEdit: false
}
},
created() {
this.loadItems();
},
methods: {
loadItems() {
this.getItems();
this.data = this.transformer();
},
getItems() {
DataService.readAll(this.getAllUrl, this.transformer)
.then(data => {
this.items = data;
});
},
showAddModal() {
this.isEdit = false;
this.data = this.transformer();
this.modal.header = 'Добавление элемента';
this.modal.confirm = 'Добавить';
this.modalShow = true;
},
showEditModal() {
if (this.selectedItems.length === 0) {
return;
}
this.showEditModalDblClick(this.selectedItems[0]);
},
showEditModalDblClick(editId) {
DataService.read(this.dataUrl + "/" + editId, this.transformer)
.then(data => {
this.data = data;
this.isEdit = true;
this.modal.header = 'Редактирование элемента';
this.modal.confirm = 'Сохранить';
this.modalShow = true;
});
},
saveItem() {
if (!this.isEdit) {
DataService.create(this.dataUrl + "/", this.data)
.then(() => {
this.getItems();
});
} else {
DataService.update(this.dataUrl + "/" + this.data.id, this.data)
.then(() => {
this.getItems();
});
}
},
removeSelectedItems() {
if (this.selectedItems.length === 0) {
return;
}
if (confirm('Удалить выбранные элементы?')) {
const promises = [];
const self = this;
this.selectedItems.forEach(item => {
promises.push(DataService.delete(this.dataUrl + "/" + item));
});
Promise.all(promises).then((results) => {
results.forEach(function (id) {
const index = self.selectedItems.indexOf(id);
if (index === - 1) {
return;
}
self.selectedItems.splice(index, 1);
});
this.getItems();
});
}
}
}
}
export default CatalogMixin;

View File

@ -0,0 +1,38 @@
export default class Component {
constructor(data) {
this._id = data?.id;
this._componentName = data?.componentName;
this._amount = data?.amount;
this._favorIds = data?.favorIds;
}
get id() {
return this._id;
}
get amount() {
return this._amount;
}
set amount(value) {
if (typeof value !== 'number' || value === null) {
throw 'New amount value ' + value + ' is not a string or empty';
}
this._amount = value;
}
get componentName() {
return this._componentName;
}
set componentName(value) {
if (typeof value !== 'string' || value === null || value.length == 0) {
throw 'New name value ' + value + ' is not a string or empty';
}
this._componentName = value;
}
get favorIds() {
return this._favorIds;
}
}

View File

@ -0,0 +1,43 @@
export default class Favor {
constructor(data) {
this._id = data?.id;
this._favorName = data?.favorName;
this._price = data?.price;
this._componentIds = data?.componentIds;
this._orderIds = data?.orderIds;
}
get id() {
return this._id;
}
get favorName() {
return this._favorName;
}
set favorName(value) {
if (typeof value !== 'string' || value === null || value.length == 0) {
throw 'New name value ' + value + ' is not a string or empty';
}
this._favorName = value;
}
get price() {
return this._price;
}
set price(value) {
if (typeof value !== 'number' || value === null) {
throw 'New price value ' + value + ' is not a number or empty';
}
this._price = value;
}
get componentIds() {
return this._componentIds;
}
get orderIds() {
return this._orderIds;
}
}

View File

@ -0,0 +1,26 @@
export default class Cabinet {
constructor(data) {
this._id = data?.id;
this._date = data?.date;
this._favorIds = data?.favorIds;
}
get id() {
return this._id;
}
get date() {
return this._date;
}
set date(value) {
if (typeof value !== 'string' || value === null || value.length == 0) {
throw 'New date value ' + value + ' is not a string or empty';
}
this._date = value;
}
get favorIds() {
return this._favorIds;
}
}

View File

@ -0,0 +1,33 @@
export default class Monitor {
constructor(data) {
this._id = data?.id;
this._login = data?.login;
this._role = data?.role;
}
get id() {
return this._id;
}
get login() {
return this._login;
}
set login(value) {
if (typeof value !== 'string' || value === null || value.length == 0) {
throw 'New model name value ' + value + ' is not a string or empty';
}
this._login = value;
}
get role() {
return this._role;
}
set role(value) {
if (typeof value !== 'string' || value === null || value.length == 0) {
throw 'New model name value ' + value + ' is not a string or empty';
}
this._role = value;
}
}

View File

@ -0,0 +1,10 @@
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
]
})
export default router

View File

@ -0,0 +1,62 @@
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.substring(1)] = data[field];
}
return jsonObj;
}
export default class DataService {
static dataUrlPrefix = 'http://localhost:8080/api/1.0/';
static async readAll(url, transformer) {
const response = (await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).get(this.dataUrlPrefix + url));
return response.data.map(item => transformer(item));
}
static async read(url, transformer) {
const response = await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).get(this.dataUrlPrefix + url);
return transformer(response.data);
}
static async create(url, data) {
const response = await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).post(this.dataUrlPrefix + url, toJSON(data));
return true;
}
static async update(url, data) {
const response = await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).put(this.dataUrlPrefix + url, toJSON(data));
return true;
}
static async delete(url) {
const response = await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).delete(this.dataUrlPrefix + url);
return response.data.id;
}
}

View File

@ -0,0 +1,15 @@
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), vueJsx()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

240
gradlew vendored Normal file
View File

@ -0,0 +1,240 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

91
gradlew.bat vendored Normal file
View File

@ -0,0 +1,91 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

1
settings.gradle Normal file
View File

@ -0,0 +1 @@
rootProject.name = 'sbapp'

View File

@ -0,0 +1,16 @@
package ru.ulstu.is.sbapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class SbappApplication {
public static void main(String[] args) {
SpringApplication.run(SbappApplication.class, args);
}
}

View File

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

View File

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

View File

@ -0,0 +1,73 @@
package ru.ulstu.is.sbapp.repair.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import ru.ulstu.is.sbapp.repair.configuration.jwt.JwtFilter;
import ru.ulstu.is.sbapp.repair.controller.UserController;
import ru.ulstu.is.sbapp.repair.controller.UserSignupController;
import ru.ulstu.is.sbapp.repair.model.UserRole;
import ru.ulstu.is.sbapp.repair.service.UserService;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
private final UserService userService;
private final JwtFilter jwtFilter;
public SecurityConfiguration(UserService userService) {
this.userService = userService;
this.jwtFilter = new JwtFilter(userService);
createAdminOnStartup();
}
private void createAdminOnStartup() {
final String admin = "admin";
if (userService.findByLogin(admin) == null) {
log.info("Admin user successfully created");
userService.createUser(admin, admin, admin, UserRole.ADMIN);
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
log.info("Creating security configuration");
http.cors()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/", SPA_URL_MASK).permitAll()
.antMatchers(HttpMethod.POST, UserController.URL_LOGIN).permitAll()
.antMatchers(HttpMethod.POST, UserSignupController.URL_LOGIN).permitAll()
.anyRequest()
.authenticated()
.and()
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.anonymous();
}
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userService);
}
@Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/**/*.{js,html,css,png}")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/webjars/**")
.antMatchers("/swagger-resources/**")
.antMatchers("/v3/api-docs/**");
}
}

View File

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

View File

@ -0,0 +1,10 @@
package ru.ulstu.is.sbapp.repair.configuration.jwt;
public class JwtException extends RuntimeException {
public JwtException(Throwable throwable) {
super(throwable);
}
public JwtException(String message) {
super(message);
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,61 @@
package ru.ulstu.is.sbapp.repair.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.repair.configuration.OpenAPI30Configuration;
import ru.ulstu.is.sbapp.repair.dtos.ComponentDTO;
import ru.ulstu.is.sbapp.repair.service.ComponentService;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/component")
public class ComponentController {
private final ComponentService componentService;
public ComponentController(ComponentService productService){
this.componentService = productService;
}
@PostMapping("/")
public ComponentDTO addComponent(@RequestBody @Valid ComponentDTO componentDTO) throws IOException {
return new ComponentDTO(componentService.addComponent(componentDTO.getComponentName(), componentDTO.getAmount()));
}
@PutMapping("/{id}")
public ComponentDTO updateComponent(@PathVariable Long id,@RequestBody @Valid ComponentDTO componentDTO) {
return new ComponentDTO(componentService.updateComponent(id,componentDTO.getComponentName(), componentDTO.getAmount()));
}
@DeleteMapping("/{id}")
public ComponentDTO removeComponent(@PathVariable Long id) {
return new ComponentDTO(componentService.deleteComponent(id));
}
@DeleteMapping
public void removeAllComponents() {
componentService.deleteAllComponent();
}
@GetMapping("/{id}")
public ComponentDTO findComponent(@PathVariable Long id) {
return new ComponentDTO(componentService.findComponent(id));
}
@GetMapping
public List<ComponentDTO> findAllComponents() {
return componentService.findAllComponent()
.stream()
.map(ComponentDTO::new)
.toList();
}
@GetMapping("/filter")
public List<ComponentDTO> getFilteredComponents(@RequestParam(value = "id", required = false) Long id,
@RequestParam(value = "componentName", required = false) String componentName,
@RequestParam(value = "amount", required = false) Integer amount ) {
return componentService.findFilteredComponents(id, componentName, amount).stream()
.map(ComponentDTO::new)
.toList();
}
}

View File

@ -0,0 +1,73 @@
package ru.ulstu.is.sbapp.repair.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.repair.configuration.OpenAPI30Configuration;
import ru.ulstu.is.sbapp.repair.dtos.ComponentDTO;
import ru.ulstu.is.sbapp.repair.dtos.FavorDTO;
import ru.ulstu.is.sbapp.repair.service.FavorService;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/favor")
public class FavorController {
private final FavorService favorService;
public FavorController(FavorService favorService){
this.favorService = favorService;
}
@PostMapping
public FavorDTO addFavor(@RequestBody @Valid FavorDTO favorDTO) {
return new FavorDTO(favorService.addFavor(favorDTO.getFavorName(), favorDTO.getPrice()));
}
@PutMapping("/{id}")
public FavorDTO updateFavor(@PathVariable Long id,@RequestBody @Valid FavorDTO favorDTO) {
return new FavorDTO(favorService.updateFavor(id,favorDTO.getFavorName(), favorDTO.getPrice()));
}
@PostMapping("/{id}/component")
public FavorDTO putIntoFavor(@PathVariable Long id, @RequestParam("compId") Long compId){
return new FavorDTO(favorService.addComponentToFavor(id, compId));
}
@DeleteMapping("/{id}")
public FavorDTO removeFavor(@PathVariable Long id) {
return new FavorDTO(favorService.deleteFavor(id));
}
//promises.push(DataService.delete(this.dataUrl + "/" + favorId + "?compId=" + item));
@DeleteMapping("/{id}/component")
public FavorDTO removeComponentFromFavor(@PathVariable Long id, @RequestParam("compId") Long compId) {
return new FavorDTO(favorService.deleteComponentfromFavor(id, compId));
}
@DeleteMapping
public void removeAllFavors() {
favorService.deleteAllFavor();
}
@GetMapping("/{id}")
public FavorDTO findFavor(@PathVariable Long id) {
return new FavorDTO(favorService.findFavor(id));
}
@GetMapping
public List<FavorDTO> findAllFavors() {
return favorService.findAllFavor()
.stream()
.map(FavorDTO::new)
.toList();
}
@GetMapping("/filter")
public List<FavorDTO> getFilteredFavors(@RequestParam(value = "id", required = false) Long id,
@RequestParam(value = "favorName", required = false) String favorName,
@RequestParam(value = "price", required = false) Integer price) {
return favorService.findFilteredFavors(id, favorName, price).stream()
.map(FavorDTO::new)
.toList();
}
}

View File

@ -0,0 +1,55 @@
package ru.ulstu.is.sbapp.repair.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.repair.configuration.OpenAPI30Configuration;
import ru.ulstu.is.sbapp.repair.dtos.FavorDTO;
import ru.ulstu.is.sbapp.repair.dtos.OrderDTO;
import ru.ulstu.is.sbapp.repair.service.OrderService;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/order")
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService productService){
this.orderService = productService;
}
@PostMapping
public OrderDTO addOrder(@RequestBody @Valid OrderDTO orderDTO) {
return new OrderDTO(orderService.addOrder());
}
@PutMapping("/{id}")
public OrderDTO updateOrder(@PathVariable Long id) {
return new OrderDTO(orderService.updateOrder(id));
}
@PostMapping("/{id}/favor")
public OrderDTO putIntoOrder(@PathVariable Long id, @RequestParam("favId") Long favId){
return new OrderDTO(orderService.addFavorToOrder(id, favId));
}
@DeleteMapping("/{id}")
public OrderDTO removeOrder(@PathVariable Long id) {
return new OrderDTO(orderService.deleteOrder(id));
}
@DeleteMapping
public void removeAllOrders() {
orderService.deleteAllOrder();
}
@GetMapping("/{id}")
public OrderDTO findOrder(@PathVariable Long id) {
return new OrderDTO(orderService.findOrder(id));
}
@GetMapping
public List<OrderDTO> findAllOrders() {
return orderService.findAllOrders()
.stream()
.map(OrderDTO::new)
.toList();
}
}

View File

@ -0,0 +1,29 @@
package ru.ulstu.is.sbapp.repair.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
@RestController
public class ReportController {
// private final Order_FavorService orderFavorService;
// @Autowired
// public ReportController(Order_FavorService orderFavorService) {
// this.orderFavorService = orderFavorService;
// }
// @GetMapping("/report")
// public Map<String, Integer> GetReport (@RequestParam(value = "from") Object value1,
// @RequestParam(value = "to") Object value2) throws ParseException {
// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//
// Date d1 = formatter.parse(value1.toString());
// Date d2 = formatter.parse(value2.toString());
// return orderFavorService.makereport(d1, d2);
// }
}

View File

@ -0,0 +1,30 @@
package ru.ulstu.is.sbapp.repair.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.is.sbapp.repair.configuration.OpenAPI30Configuration;
import ru.ulstu.is.sbapp.repair.dtos.UserDto;
import ru.ulstu.is.sbapp.repair.model.User;
import ru.ulstu.is.sbapp.repair.service.UserService;
import javax.validation.Valid;
import java.util.List;
@RestController
public class UserController {
public static final String URL_LOGIN = "/jwt/login";
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping(OpenAPI30Configuration.API_PREFIX + "/user")
public List<User> getUsers() {
return userService.findAllUsers();
}
@PostMapping(URL_LOGIN)
public String login(@RequestBody @Valid UserDto userDto) {
return userService.loginAndGetToken(userDto);
}
}

View File

@ -0,0 +1,32 @@
package ru.ulstu.is.sbapp.repair.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.is.sbapp.repair.dtos.UserSignupDto;
import ru.ulstu.is.sbapp.repair.model.User;
import ru.ulstu.is.sbapp.repair.service.UserService;
import ru.ulstu.is.sbapp.repair.util.validation.ValidationException;
import javax.validation.Valid;
@Controller
@RestController
public class UserSignupController {
public static final String URL_LOGIN = "/signup";
private final UserService userService;
public UserSignupController(UserService userService) {
this.userService = userService;
}
@PostMapping(URL_LOGIN)
public String signup(@RequestBody @Valid UserSignupDto userSignupDto) {
try {
final User user = userService.createUser(
userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
return user.getLogin();
} catch (ValidationException e) {
return "error";
}
}
}

View File

@ -0,0 +1,38 @@
package ru.ulstu.is.sbapp.repair.dtos;
import ru.ulstu.is.sbapp.repair.model.Component;
import java.util.List;
public class ComponentDTO {
private long id;
private String componentName;
private Integer amount;
private List<FavorDTO> favorsDTOListFromComponents;
public ComponentDTO(Component component){
this.id =component.getId();
this.componentName = component.getComponentName();
this.amount = component.getAmount();
this.favorsDTOListFromComponents = component.getFavors() == null ? null: component.getFavors()
.stream()
.filter(x -> x.getComponents().contains(component.getId()))
.map(y -> new FavorDTO(y))
.toList();
}
public ComponentDTO(){
}
public long getId() {
return id;
}
public String getComponentName(){
return componentName;
}
public Integer getAmount(){
return amount;
}
public List<FavorDTO> getFavorsDTOListFromComponents() {
return favorsDTOListFromComponents;
}
}

View File

@ -0,0 +1,65 @@
package ru.ulstu.is.sbapp.repair.dtos;
import ru.ulstu.is.sbapp.repair.model.Component;
import ru.ulstu.is.sbapp.repair.model.Favor;
import java.util.ArrayList;
import java.util.List;
public class FavorDTO {
private long id;
private String favorName;
private Integer price;
private List<ComponentDTO> componentsDTOList;
private List<OrderDTO> ordersDTOList;
private List<Long> componentIds;
public FavorDTO(Favor favor){
this.id =favor.getId();
this.favorName = favor.getFavorName();
this.price = favor.getPrice();
if (favor.getComponents() == null){
this. componentIds = new ArrayList<>();
}
else {
this.componentIds = new ArrayList<>();
List<Component> components = favor.getComponents();
for (Component component : components) {
componentIds.add(component.getId());
}
}
this.componentsDTOList = favor.getComponents() == null ? null: favor.getComponents()
.stream()
.filter(x -> x.getFavors().contains(favor.getId()))
.map(y -> new ComponentDTO(y))
.toList();
this.ordersDTOList = favor.getOrders() == null ? null: favor.getOrders()
.stream()
.filter(x -> x.getFavorsList().contains(favor.getId()))
.map(y -> new OrderDTO(y))
.toList();
}
public FavorDTO(){
}
public long getId() {
return id;
}
public String getFavorName(){
return favorName;
}
public Integer getPrice(){
return price;
}
public List<ComponentDTO> getComponentsDTOList() {
return componentsDTOList;
}
public List<OrderDTO> getOrdersDTOList() {
return ordersDTOList;
}
public List<Long> getcomponentIds() { return this.componentIds; }
public void setcomponentIds(List<Long> componentIds) { this.componentIds = componentIds; }
}

View File

@ -0,0 +1,53 @@
package ru.ulstu.is.sbapp.repair.dtos;
import ru.ulstu.is.sbapp.repair.dtos.FavorDTO;
import ru.ulstu.is.sbapp.repair.model.Component;
import ru.ulstu.is.sbapp.repair.model.Favor;
import ru.ulstu.is.sbapp.repair.model.Order;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class OrderDTO {
private long id;
private Date date;
private List<FavorDTO> favorsDTOList;
private List<Long> favorIds;
public OrderDTO(Order order){
this.id =order.getId();
this.date = order.getDate();
if (order.getFavorsList() == null){
this. favorIds = new ArrayList<>();
}
else {
this.favorIds = new ArrayList<>();
List<Favor> favors = order.getFavorsList();
for (Favor favor : favors) {
favorIds.add(favor.getId());
}
}
this.favorsDTOList = order.getFavorsList() == null ? null: order.getFavorsList()
.stream()
.filter(x -> x.getOrders().contains(order.getId()))
.map(y -> new FavorDTO(y))
.toList();
}
public OrderDTO(){
}
public long getId() {
return id;
}
public Date getDate(){
return date;
}
public List<FavorDTO> getFavorsDTOList() {
return favorsDTOList;
}
public List<Long> getfavorIds() { return this.favorIds; }
public void setfavorIds(List<Long> favorIds) { this.favorIds = favorIds; }
}

View File

@ -0,0 +1,23 @@
package ru.ulstu.is.sbapp.repair.dtos;
import ru.ulstu.is.sbapp.repair.model.User;
import javax.validation.constraints.NotEmpty;
public class UserDto {
@NotEmpty
private String login;
@NotEmpty
private String password;
public UserDto() {}
UserDto(User user) {
login = user.getLogin();
password = user.getPassword();
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
}

View File

@ -0,0 +1,34 @@
package ru.ulstu.is.sbapp.repair.dtos;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public class UserSignupDto {
@NotBlank
@Size(min = 3, max = 64)
private String login;
@NotBlank
@Size(min = 6, max = 64)
private String password;
@NotBlank
@Size(min = 6, max = 64)
private String passwordConfirm;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.repair.exception;
public class ComponentNotFoundException extends RuntimeException{
public ComponentNotFoundException(Long id) {
super(String.format("Component with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.repair.exception;
public class FavorNotFoundException extends RuntimeException{
public FavorNotFoundException(Long id) {
super(String.format("Favor with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.repair.exception;
public class OrderNotFoundException extends RuntimeException{
public OrderNotFoundException(Long id) {
super(String.format("Order with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.repair.exception;
public class UserExistsException extends RuntimeException {
public UserExistsException(String login) {
super(String.format("User '%s' already exists", login));
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.repair.exception;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String login) {
super(String.format("User not found '%s'", login));
}
}

View File

@ -0,0 +1,91 @@
package ru.ulstu.is.sbapp.repair.model;
import org.springframework.cache.interceptor.CacheableOperation;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "components")
public class Component {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name")
private String componentName;
@Column(name = "amount")
private Integer amount;
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "componentsList", cascade = {CascadeType.MERGE})
private List<Favor> favorsListFromComponents;
public Component() {
favorsListFromComponents = new ArrayList<>();
}
public Component(Integer amount, String componentName) {
this.componentName = componentName;
this.amount = amount;
favorsListFromComponents = new ArrayList<>();
}
public Long getId() {
return id;
}
public String getComponentName() {
return componentName;
}
public void setComponentName(String componentName) {
this.componentName = componentName;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public List<Favor> getFavors() {
return favorsListFromComponents;
}
public void addFavor(Favor favor) {
if (favorsListFromComponents == null)
favorsListFromComponents = new ArrayList<>();
if (!favorsListFromComponents.contains(favor)){
favorsListFromComponents.add(favor);
}
if (!favor.getComponents().contains(this)) {
favor.addComponent(this);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Component component = (Component) o;
return Objects.equals(id, component.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Component{" +
"id=" + id +
", componentName='" + componentName + '\'' +
", amount='" + amount + '\'' +
'}';
}
}

View File

@ -0,0 +1,117 @@
package ru.ulstu.is.sbapp.repair.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "favors")
public class Favor {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name")
private String favorName;
@Column(name = "price")
private Integer price;
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE})
private List<Order> ordersList;
@ManyToMany(cascade = {CascadeType.MERGE})
@LazyCollection(LazyCollectionOption.FALSE)
private List<Component> componentsList;
public Favor() {
componentsList = new ArrayList<>();
ordersList = new ArrayList<>();
}
public Favor(String favorName, Integer price) {
this.favorName = favorName;
this.price = price;
componentsList = new ArrayList<>();
ordersList = new ArrayList<>();
}
public Long getId() {
return id;
}
public String getFavorName() {
return favorName;
}
public void setFavorName(String favorName) {
this.favorName = favorName;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public List<Order> getOrders() {
return ordersList;
}
public List<Component> getComponents() {return componentsList;}
public void addOrder(Order order) {
if (ordersList == null)
ordersList = new ArrayList<>();
if (!ordersList.contains(order)){
ordersList.add(order);
}
if (!order.getFavorsList().contains(this)) {
order.addFavor(this);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Favor favor = (Favor) o;
return Objects.equals(id, favor.id);
}
public void addComponent(Component component){
if (componentsList == null)
componentsList = new ArrayList<>();
if (!componentsList.contains(component)){
componentsList.add(component);
}
if (!component.getFavors().contains(this)) {
component.addFavor(this);
}
}
public void deleteComponent(Component comp){
componentsList.remove(comp);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", productName='" + favorName + '\'' +
", price='" + price + '\'' +
'}';
}
}

View File

@ -0,0 +1,69 @@
package ru.ulstu.is.sbapp.repair.model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "date")
private Date date;
@ManyToMany (fetch = FetchType.EAGER, mappedBy = "ordersList", cascade = {CascadeType.REFRESH})
private List<Favor> favorsList;
public Order(){
}
public Order(Date date) {
this.date = date;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Order order)) return false;
return Objects.equals(getId(), order.getId()) && Objects.equals(getDate(), order.getDate());
}
public List<Favor> getFavorsList() {
return favorsList;
}
public void addFavor(Favor favor){
if (favorsList == null)
favorsList = new ArrayList<>();
if (!favorsList.contains(favor)) {
favorsList.add(favor);
}
favor.addOrder(this);
}
@Override
public int hashCode() {
return Objects.hash(getId(), getDate());
}
}

View File

@ -0,0 +1,70 @@
package ru.ulstu.is.sbapp.repair.model;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Objects;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true, length = 64)
@NotBlank
@Size(min = 3, max = 64)
private String login;
@Column(nullable = false, length = 64)
@NotBlank
@Size(min = 6, max = 64)
private String password;
private UserRole role;
public User() {
}
public User(String login, String password) {
this(login, password, UserRole.USER);
}
public User(String login, String password, UserRole role) {
this.login = login;
this.password = password;
this.role = role;
}
public Long getId() {
return id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRole getRole() {
return role;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", login='" + login + '\'' +
", password='" + password + '\'' +
'}';
}
}

View File

@ -0,0 +1,17 @@
package ru.ulstu.is.sbapp.repair.model;
import org.springframework.security.core.GrantedAuthority;
public enum UserRole implements GrantedAuthority {
ADMIN,
USER;
private static final String PREFIX = "ROLE_";
@Override
public String getAuthority() {
return PREFIX + this.name();
}
public static final class AsString {
public static final String ADMIN = PREFIX + "ADMIN";
public static final String USER = PREFIX + "USER";
}
}

View File

@ -0,0 +1,15 @@
package ru.ulstu.is.sbapp.repair.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ru.ulstu.is.sbapp.repair.model.Component;
import java.util.List;
public interface ComponentRepository extends JpaRepository<Component, Long> {
@Query(value = "select s from Component s where (s.id = :id or :id is Null) and (s.amount = :amount or :amount = 0) and (s.componentName = :componentName or :componentName is Null)")
public List<Component> findFilteredComponents(@Param("id") Long id,
@Param("componentName") String componentName,
@Param("amount") Integer amount );
}

View File

@ -0,0 +1,22 @@
package ru.ulstu.is.sbapp.repair.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ru.ulstu.is.sbapp.repair.model.Favor;
import java.util.List;
public interface FavorRepository extends JpaRepository<Favor, Long> {
@Query(value = "select s from Favor s where (s.id = :id or :id is Null) and (s.favorName = :favorName or :favorName is Null) and (s.price = :price or :price = 0)")
public List<Favor> findFilteredFavors(@Param("id") Long id,
@Param("favorName") String favorName,
@Param("price") int price);
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.repair.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.sbapp.repair.model.Order;
public interface OrderRepository extends JpaRepository<Order, Long> {
}

View File

@ -0,0 +1,8 @@
package ru.ulstu.is.sbapp.repair.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.sbapp.repair.model.User;
public interface UserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,72 @@
package ru.ulstu.is.sbapp.repair.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.is.sbapp.repair.exception.ComponentNotFoundException;
import ru.ulstu.is.sbapp.repair.model.Component;
import ru.ulstu.is.sbapp.repair.repository.ComponentRepository;
import ru.ulstu.is.sbapp.repair.util.validation.ValidatorUtil;
import java.util.List;
import java.util.Optional;
@Service
public class ComponentService {
// @Autowired
private final ComponentRepository componentRepository;
//@Autowired
private final ValidatorUtil validatorUtil;
public ComponentService(ComponentRepository componentRepository, ValidatorUtil validatorUtil) {
this.componentRepository = componentRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Component addComponent(String name, int amount) {
final Component component = new Component(amount, name);
validatorUtil.validate(component);
return componentRepository.save(component);
}
@Transactional(readOnly = true)
public List<Component> findFilteredComponents(Long id, String componentName, Integer amount) {
return componentRepository.findFilteredComponents(id, componentName,Optional.ofNullable(amount).orElse(0));
}
@Transactional(readOnly = true)
public Component findComponent(Long id) {
final Optional <Component> component = componentRepository.findById(id);
return component.orElseThrow(() -> new ComponentNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Component> findAllComponent() {
return componentRepository.findAll();
}
@Transactional
public Component updateComponent(Long id, String name, int amount) {
final Component currentComponent = findComponent(id);
currentComponent.setComponentName(name);
currentComponent.setAmount(amount);
validatorUtil.validate(currentComponent);
return componentRepository.save(currentComponent);
}
@Transactional
public Component deleteComponent(Long id) {
final Component currentComponent = findComponent(id);
componentRepository.delete(currentComponent);
return currentComponent;
}
@Transactional
public void deleteAllComponent() {
componentRepository.deleteAll();
}
}

View File

@ -0,0 +1,90 @@
package ru.ulstu.is.sbapp.repair.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.is.sbapp.repair.exception.FavorNotFoundException;
import ru.ulstu.is.sbapp.repair.model.Component;
import ru.ulstu.is.sbapp.repair.model.Favor;
import ru.ulstu.is.sbapp.repair.repository.FavorRepository;
import ru.ulstu.is.sbapp.repair.util.validation.ValidatorUtil;
import javax.persistence.criteria.CriteriaBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class FavorService {
private final FavorRepository favorRepository;
private final ValidatorUtil validatorUtil;
private final ComponentService componentService;
public FavorService(FavorRepository favorRepository, ValidatorUtil validatorUtil, ComponentService componentService){
this.favorRepository = favorRepository;
this.validatorUtil = validatorUtil;
this.componentService = componentService;
}
@Transactional
public Favor addFavor(String name, int price) {
final Favor favor = new Favor(name, price);
validatorUtil.validate(favor);
return favorRepository.save(favor);
}
@Transactional(readOnly = true)
public Favor findFavor(Long id) {
final Optional<Favor> favor = favorRepository.findById(id);
return favor.orElseThrow(() -> new FavorNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Favor> findAllFavor() {
return favorRepository.findAll();
}
@Transactional
public Favor updateFavor(Long id, String name, int price) {
final Favor currentFavor = findFavor(id);
currentFavor.setFavorName(name);
currentFavor.setPrice(price);
validatorUtil.validate(currentFavor);
return favorRepository.save(currentFavor);
}
@Transactional
public Favor deleteFavor(Long id) {
final Favor currentFavor = findFavor(id);
favorRepository.delete(currentFavor);
return currentFavor;
}
@Transactional
public Favor deleteComponentfromFavor(Long id, Long compId){
final Favor currentFavor = findFavor(id);
final Component currentComponent = componentService.findComponent(compId);
currentFavor.deleteComponent(currentComponent);
return currentFavor;
}
@Transactional
public Favor addComponentToFavor(Long FavorId, Long ComponentID){
final Favor currentFavor = findFavor(FavorId);
final Component currentComponent = componentService.findComponent(ComponentID);
currentFavor.addComponent(currentComponent);
return currentFavor;
}
@Transactional
public void deleteAllFavor() {
favorRepository.deleteAll();
}
@Transactional(readOnly = true)
public List<Favor> findFilteredFavors(Long id, String favorName, Integer price) {
return favorRepository.findFilteredFavors(id, favorName, Optional.ofNullable(price).orElse(0));
}
}

View File

@ -0,0 +1,87 @@
package ru.ulstu.is.sbapp.repair.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.is.sbapp.repair.exception.OrderNotFoundException;
import ru.ulstu.is.sbapp.repair.model.Favor;
import ru.ulstu.is.sbapp.repair.model.Order;
import ru.ulstu.is.sbapp.repair.repository.OrderRepository;
import ru.ulstu.is.sbapp.repair.util.validation.ValidatorUtil;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final ValidatorUtil validatorUtil;
private final FavorService favorService;
public OrderService(OrderRepository orderRepository, ValidatorUtil validatorUtil, FavorService favorService){
this.orderRepository = orderRepository;
this.validatorUtil = validatorUtil;
this.favorService = favorService;
}
@Transactional
public Order addOrder() {
Date today = new Date();
final Order order = new Order(today);
validatorUtil.validate(order);
return orderRepository.save(order);
}
public Date getDate(String date) {
SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("dd.MM.yyyy");
Date newDate;
try {
newDate = format.parse(date);
} catch (Exception exception) {
newDate = new Date();
}
return newDate;
}
@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 updateOrder(Long id) {
final Order currentOrder = findOrder(id);
validatorUtil.validate(currentOrder);
return orderRepository.save(currentOrder);
}
@Transactional
public Order deleteOrder(Long id) {
final Order currentOrder = findOrder(id);
orderRepository.delete(currentOrder);
return currentOrder;
}
@Transactional
public Order addFavorToOrder(Long orderId, Long favorId){
final Order currentOrder = findOrder(orderId);
final Favor currentFavor = favorService.findFavor(favorId);
currentOrder.addFavor(currentFavor);
validatorUtil.validate(currentOrder);
orderRepository.save(currentOrder);
return currentOrder;
}
@Transactional
public void deleteAllOrder() {
orderRepository.deleteAll();
}
}

View File

@ -0,0 +1,91 @@
package ru.ulstu.is.sbapp.repair.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import ru.ulstu.is.sbapp.repair.configuration.jwt.JwtException;
import ru.ulstu.is.sbapp.repair.configuration.jwt.JwtProvider;
import ru.ulstu.is.sbapp.repair.dtos.UserDto;
import ru.ulstu.is.sbapp.repair.exception.UserExistsException;
import ru.ulstu.is.sbapp.repair.exception.UserNotFoundException;
import ru.ulstu.is.sbapp.repair.model.User;
import ru.ulstu.is.sbapp.repair.model.UserRole;
import ru.ulstu.is.sbapp.repair.repository.UserRepository;
import ru.ulstu.is.sbapp.repair.util.validation.ValidationException;
import ru.ulstu.is.sbapp.repair.util.validation.ValidatorUtil;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@Service
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final ValidatorUtil validatorUtil;
private final JwtProvider jwtProvider;
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder,
ValidatorUtil validatorUtil,
JwtProvider jwtProvider) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.validatorUtil = validatorUtil;
this.jwtProvider = jwtProvider;
}
public Page<User> findAllPages(int page, int size) {
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
}
public List<User> findAllUsers() {
return userRepository.findAll();
}
public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
public User createUser(String login, String password, String passwordConfirm) {
return createUser(login, password, passwordConfirm, UserRole.USER);
}
public User createUser(String login, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) {
throw new UserExistsException(login);
}
final User user = new User(login, passwordEncoder.encode(password), role);
validatorUtil.validate(user);
if (!Objects.equals(password, passwordConfirm)) {
throw new ValidationException("Passwords not equals");
}
return userRepository.save(user);
}
public String loginAndGetToken(UserDto userDto) {
final User user = findByLogin(userDto.getLogin());
if (user == null) {
throw new UserNotFoundException(userDto.getLogin());
}
if (!passwordEncoder.matches(userDto.getPassword(), user.getPassword())) {
throw new UserNotFoundException(user.getLogin());
}
return jwtProvider.generateToken(user.getLogin());
}
public UserDetails loadUserByToken(String token) throws UsernameNotFoundException {
if (!jwtProvider.isTokenValid(token)) {
throw new JwtException("Bad token");
}
final String userLogin = jwtProvider.getLoginFromToken(token)
.orElseThrow(() -> new JwtException("Token is not contain Login"));
return loadUserByUsername(userLogin);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final User userEntity = findByLogin(username);
if (userEntity == null) {
throw new UsernameNotFoundException(username);
}
return new org.springframework.security.core.userdetails.User(
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
}
}

View File

@ -0,0 +1,43 @@
package ru.ulstu.is.sbapp.repair.util.error;
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 ru.ulstu.is.sbapp.repair.exception.ComponentNotFoundException;
import ru.ulstu.is.sbapp.repair.exception.FavorNotFoundException;
import ru.ulstu.is.sbapp.repair.exception.OrderNotFoundException;
import ru.ulstu.is.sbapp.repair.util.validation.ValidationException;
import java.util.stream.Collectors;
@ControllerAdvice
public class AdviceController {
@ExceptionHandler({
ValidationException.class,
ComponentNotFoundException.class,
FavorNotFoundException.class,
OrderNotFoundException.class,
ValidationException.class
})
public ResponseEntity<Object> handleException(Throwable e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException e) {
final ValidationException validationException = new ValidationException(
e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toSet()));
return handleException(validationException);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleUnknownException(Throwable e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@ -0,0 +1,10 @@
package ru.ulstu.is.sbapp.repair.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException{
public ValidationException(String message) {
super(message);
}
public ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}}

View File

@ -0,0 +1,30 @@
package ru.ulstu.is.sbapp.repair.util.validation;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
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

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

View File

@ -0,0 +1,65 @@
package ru.ulstu.is.sbapp;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.sbapp.repair.model.*;
import ru.ulstu.is.sbapp.repair.service.*;
import javax.persistence.EntityNotFoundException;
import java.util.List;
@SpringBootTest
class SbappApplicationTests {
// @Autowired
// private ComponentService componentService;
// @Autowired
// private FavorService favorService;
// @Autowired
// private OrderService orderService;
//
// @Test
// void testOrder(){
// componentService.deleteAllComponent();
// orderService.deleteAllOrder();
// favorService.deleteAllFavor();
//
// final Favor favor = favorService.addFavor("Favor1", 100);
//
// final Order order0 = orderService.addOrder("11.02.2023");
// final Order order1 = orderService.findOrder(order0.getId());
// final Component component1 = componentService.addComponent("comp", 10);
// favor.addComponent(component1);
// Assertions.assertEquals(order0, order1);
//
// orderService.addFavorToOrder(order0.getId(), favor);
// Assertions.assertEquals(favorService.findFavor(favor.getId()).getOrders().size(), 1);
// Assertions.assertEquals(orderService.findOrder(order0.getId()).getFavorsList().size(), 1);
//
// orderService.deleteOrder(order0.getId());
// Assertions.assertThrows(EntityNotFoundException.class, () -> orderService.findOrder(order0.getId()));
// }
//
// @Test
// void testFavor(){
// componentService.deleteAllComponent();
// orderService.deleteAllOrder();
// favorService.deleteAllFavor();
//
// final Component component = componentService.addComponent("Favor1", 100);
//
// final Favor favor0 = favorService.addFavor("fvr", 100);
// final Favor favor1 = favorService.findFavor(favor0.getId());
// Assertions.assertEquals(favor0, favor1);
//
//
// favorService.addComponentToFavor(favor0.getId(), component);
// Assertions.assertEquals(favorService.findFavor(favor0.getId()).getComponents().size(), 1);
// Assertions.assertEquals(componentService.findComponent(component.getId()).getFavors().size(), 1);
//
// favorService.deleteFavor(favor0.getId());
// Assertions.assertThrows(EntityNotFoundException.class, () -> favorService.findFavor(favor0.getId()));
//
// }
}