Compare commits
79 Commits
Author | SHA1 | Date | |
---|---|---|---|
1828a03a3f | |||
4374781d72 | |||
0b9e283f67 | |||
b9dd9c6d9b | |||
1f973eec1d | |||
bbf08f2a71 | |||
02342f4b1d | |||
50946a1014 | |||
7d85282929 | |||
c7a0109c00 | |||
a8e6af5269 | |||
ac35178e4b | |||
b0184fcf44 | |||
c30e8182f9 | |||
6012934a86 | |||
a79f51ffb3 | |||
2a9507f646 | |||
32f3e9483f | |||
620d48c88d | |||
48558c6fc8 | |||
7e0c1e988e | |||
bcac1c3159 | |||
cf4869f664 | |||
cbd7fa1127 | |||
f0784bdfcb | |||
c61553b284 | |||
dcb1c381c9 | |||
a22ff8d8bb | |||
ee165d350a | |||
62627de1ee | |||
58188e1dbe | |||
23af234a27 | |||
534654ffd5 | |||
bd695a00ba | |||
4977f33ed1 | |||
12d79028c6 | |||
d45c220d50 | |||
3acc25cbc6 | |||
6aa51bc74e | |||
ab9181004e | |||
e40639a883 | |||
18ee5ece77 | |||
26f94dab02 | |||
9cd8ce211d | |||
c88068f489 | |||
688fd255c6 | |||
4b9638ad2f | |||
62d5bd2394 | |||
1335f82494 | |||
eecfe393e4 | |||
6a071071e2 | |||
419eb0b15a | |||
08dad1b6a4 | |||
0c1764ab47 | |||
ee923e986d | |||
cbf337eea6 | |||
33f6f1dd21 | |||
55b8db56c7 | |||
b016ee75a3 | |||
32498b023a | |||
c1a8b9fe81 | |||
45a590f145 | |||
071d001e08 | |||
2cb40754c1 | |||
ca9a45d0b8 | |||
b620bbf62d | |||
6bee6f84ee | |||
b24242b20f | |||
903e6051e8 | |||
5ca10677cf | |||
b43f9e4ffa | |||
58bf3c0d25 | |||
a55af823c6 | |||
c65125a48e | |||
f0e3f4374b | |||
0df1eca957 | |||
41fff9ad53 | |||
23bb2f4187 | |||
843cf0b815 |
4
.gitignore
vendored
@ -4,7 +4,9 @@ build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
node_modules
|
||||
data.mv.db
|
||||
data.trace.db
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
|
24
FrontEnd/.gitignore
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
BIN
FrontEnd/Ped.pdf
Normal file
BIN
FrontEnd/Rasp(1-4).pdf
Normal file
BIN
FrontEnd/Rasp(5-11).pdf
Normal file
53
FrontEnd/build.gradle
Normal file
@ -0,0 +1,53 @@
|
||||
import com.github.gradle.node.util.PlatformHelper
|
||||
import groovy.text.SimpleTemplateEngine
|
||||
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'com.github.node-gradle.node' version '3.5.1'
|
||||
id "de.undercouch.download" version '5.3.1'
|
||||
}
|
||||
|
||||
node {
|
||||
version = '18.15.0'
|
||||
download = true
|
||||
}
|
||||
|
||||
jar.dependsOn 'npmBuild'
|
||||
|
||||
clean.dependsOn 'npmClean'
|
||||
|
||||
nodeSetup.dependsOn 'downloadNode'
|
||||
|
||||
jar {
|
||||
from 'dist'
|
||||
into 'static'
|
||||
}
|
||||
|
||||
task downloadNode(type: Download) {
|
||||
final helper = new PlatformHelper()
|
||||
final templateData = [
|
||||
"url" : node.distBaseUrl.get(),
|
||||
"version": node.version.get(),
|
||||
"os" : helper.osName,
|
||||
"arch" : helper.osArch,
|
||||
"ext" : helper.windows ? 'zip' : 'tar.gz'
|
||||
]
|
||||
final urlTemplate = '${url}/v${version}/node-v${version}-${os}-${arch}.${ext}'
|
||||
final engine = new SimpleTemplateEngine()
|
||||
final url = engine.createTemplate(urlTemplate).make(templateData).toString()
|
||||
final String destDir = '.gradle/'
|
||||
file(destDir).mkdirs()
|
||||
src url
|
||||
dest destDir
|
||||
overwrite false
|
||||
}
|
||||
|
||||
tasks.register('npmBuild', NpmTask) {
|
||||
dependsOn npmInstall
|
||||
args = ['run-script', 'build']
|
||||
}
|
||||
|
||||
tasks.register('npmClean', NpmTask) {
|
||||
dependsOn npmInstall
|
||||
args = ['run-script', 'clean']
|
||||
}
|
BIN
FrontEnd/img/6666.png
Normal file
After Width: | Height: | Size: 60 KiB |
BIN
FrontEnd/img/Emblema.png
Normal file
After Width: | Height: | Size: 77 KiB |
BIN
FrontEnd/img/Rasp.png
Normal file
After Width: | Height: | Size: 67 KiB |
BIN
FrontEnd/img/Shkola.jpg
Normal file
After Width: | Height: | Size: 166 KiB |
BIN
FrontEnd/img/banner1.png
Normal file
After Width: | Height: | Size: 522 KiB |
BIN
FrontEnd/img/banner2.png
Normal file
After Width: | Height: | Size: 903 KiB |
BIN
FrontEnd/img/banner3.png
Normal file
After Width: | Height: | Size: 471 KiB |
BIN
FrontEnd/img/icon.png
Normal file
After Width: | Height: | Size: 54 KiB |
BIN
FrontEnd/img/owl.png
Normal file
After Width: | Height: | Size: 147 KiB |
16
FrontEnd/index.html
Normal file
@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="img/icon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<script src="/node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
|
||||
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="/node_modules/@fortawesome/fontawesome-free/css/all.min.css">
|
||||
<title>МБОУ средняя общеобразовательная школа №10</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
</html>
|
18
FrontEnd/js/banner.js
Normal file
@ -0,0 +1,18 @@
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
console.info('Loaded');
|
||||
const banners = document.querySelectorAll("#banner img");
|
||||
var old = banners.length - 1;
|
||||
var current = 0;
|
||||
function loop() {
|
||||
banners[current].setAttribute('className', 'show');
|
||||
banners[old].setAttribute('className', 'hide');
|
||||
console.info('Banner changed');
|
||||
old = current;
|
||||
current++;
|
||||
if (current === banners.length) {
|
||||
current = 0;
|
||||
}
|
||||
setTimeout(loop, 5000);
|
||||
}
|
||||
loop();
|
||||
});
|
1641
FrontEnd/package-lock.json
generated
Normal file
26
FrontEnd/package.json
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "spa-react",
|
||||
"private": true,
|
||||
"source": "index.html",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.4.4",
|
||||
"axios": "^1.1.3",
|
||||
"bootstrap": "^5.2.2",
|
||||
"@fortawesome/fontawesome-free": "^6.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.0.24",
|
||||
"@types/react-dom": "^18.0.8",
|
||||
"vite": "^3.2.3",
|
||||
"@vitejs/plugin-react": "^2.2.0"
|
||||
}
|
||||
}
|
1
FrontEnd/public/favicon.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M96 0C43 0 0 43 0 96V416c0 53 43 96 96 96H384h32c17.7 0 32-14.3 32-32s-14.3-32-32-32V384c17.7 0 32-14.3 32-32V32c0-17.7-14.3-32-32-32H384 96zm0 384H352v64H96c-17.7 0-32-14.3-32-32s14.3-32 32-32zm32-240c0-8.8 7.2-16 16-16H336c8.8 0 16 7.2 16 16s-7.2 16-16 16H144c-8.8 0-16-7.2-16-16zm16 48H336c8.8 0 16 7.2 16 16s-7.2 16-16 16H144c-8.8 0-16-7.2-16-16s7.2-16 16-16z"/></svg>
|
After Width: | Height: | Size: 611 B |
48
FrontEnd/src/App.jsx
Normal file
@ -0,0 +1,48 @@
|
||||
|
||||
import { useRoutes, Outlet, BrowserRouter } from 'react-router-dom';
|
||||
import Header from './components/common/Header';
|
||||
import Catalogs from './components/catalogs/MainPage';
|
||||
import CatalogGroups from './components/catalogs/Autorize';
|
||||
import CatalogStudents from './components/catalogs/News';
|
||||
import Post from './components/catalogs/Post';
|
||||
import Reports from './components/catalogs/RezhimRaboty';
|
||||
import ReportGroupStudents from './components/catalogs/Raspisanie';
|
||||
import Footer from './components/common/Footer';
|
||||
|
||||
function Router(props) {
|
||||
return useRoutes(props.rootRoute);
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const routes = [
|
||||
{ index: true, element: <Catalogs /> },
|
||||
{ path: 'Main_page', element: <Catalogs />, label: 'Главная' },
|
||||
{ path: 'News', element: <CatalogStudents/>, label:'Новости' },
|
||||
{ path: 'Autorize', element: <CatalogGroups />, label:'Авторизация'},
|
||||
{ path: 'RezhimRaboty', element: <Reports />, label: 'Режим работы' },
|
||||
{ path: 'Raspisanie', element: <ReportGroupStudents />,label:'Расписание' },
|
||||
{ path: 'Post', element: <Post/>}
|
||||
];
|
||||
const links = routes.filter(route => route.hasOwnProperty('label'));
|
||||
const rootRoute = [
|
||||
{ path: '/', element: render(links), children: routes }
|
||||
];
|
||||
|
||||
function render(links) {
|
||||
return (
|
||||
<div className='body_app'>
|
||||
<Header links={links} />
|
||||
<div className="d-flex text-white bg-info bg-gradient fw-bold">
|
||||
<Outlet />
|
||||
</div>
|
||||
<Footer links={links}/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Router rootRoute={ rootRoute } />
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
22
FrontEnd/src/ModalEdit.module.css
Normal file
@ -0,0 +1,22 @@
|
||||
.myModal {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
left: 0;
|
||||
display: none;
|
||||
background: rgba(0,0,0, 0.5);
|
||||
}
|
||||
|
||||
.myModalContent {
|
||||
padding: 25px;
|
||||
background: white;
|
||||
border-radius: 16px;
|
||||
max-width: 600px;
|
||||
}
|
||||
|
||||
.myModal.active {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
146
FrontEnd/src/components/catalogs/Autorize.jsx
Normal file
@ -0,0 +1,146 @@
|
||||
import React from "react";
|
||||
import { useState } from 'react';
|
||||
import {useEffect} from 'react';
|
||||
import UserDto from '../../models/UserDto';
|
||||
export default function CatalogGroups(props) {
|
||||
const formRef = React.createRef();
|
||||
const [output, setOutput] = useState([]);
|
||||
const FirstInput = document.getElementById("validationCustom01");
|
||||
const LastInput = document.getElementById("validationCustom02");
|
||||
const emailInput = document.getElementById("validationCustomMail");
|
||||
const getAll = async function () {
|
||||
const requestUrl = "http://localhost:8080/user";
|
||||
const response = await fetch(requestUrl);
|
||||
const users = await response.json();
|
||||
setOutput(users);
|
||||
}
|
||||
useEffect(() => {
|
||||
getAll();
|
||||
}, []);
|
||||
const remove = async function(id){
|
||||
const requestParams = {
|
||||
method: "DELETE",
|
||||
headers:{
|
||||
"Content-Type":"application/json",
|
||||
}
|
||||
};
|
||||
const requestUrl = "http://localhost:8080" + "/user/" + id;
|
||||
const response=await fetch(requestUrl,requestParams);
|
||||
return await response.json;
|
||||
};
|
||||
const create = async function (firstName, lastName,Email) {
|
||||
const requestParams = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
};
|
||||
const response = await fetch("http://localhost:8080" + `/user?firstName=${firstName}&lastName=${lastName}&email=${Email}`, requestParams);
|
||||
return await response.json();
|
||||
}
|
||||
const refresh = async function(id,firstName, lastName,Email)
|
||||
{
|
||||
const requestParams={
|
||||
method:"PUT",
|
||||
headers:{
|
||||
"Content-Type":"application/json",
|
||||
}
|
||||
};
|
||||
const response=await fetch(`http://localhost:8080/user/${id}?firstName=${firstName}&lastName=${lastName}&email=${Email}`,requestParams);
|
||||
return await response.json();
|
||||
}
|
||||
const add_but = function(event)
|
||||
{
|
||||
event.preventDefault();
|
||||
create(FirstInput.value, LastInput.value,emailInput.value).then((result) => {
|
||||
getAll();
|
||||
FirstInput.value = "";
|
||||
LastInput.value = "";
|
||||
emailInput.value="";
|
||||
alert(`User[id=${result.id}, firstName=${result.firstName}, lastName=${result.lastName},email=${result.email}]`);
|
||||
});
|
||||
}
|
||||
const edit_btn = function(id,event)
|
||||
{
|
||||
console.log("Обновление")
|
||||
refresh(id,FirstInput.value, LastInput.value,emailInput.value).then((result)=>{
|
||||
getAll();
|
||||
FirstInput.value = "";
|
||||
LastInput.value = "";
|
||||
emailInput.value="";
|
||||
});
|
||||
}
|
||||
const rem_but = function(id,event)
|
||||
{
|
||||
console.log("Удаление")
|
||||
remove(id).then((result)=>{
|
||||
getAll();
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-2">
|
||||
<form className="row g-3 needs-validation">
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="validationCustom01">Имя</label>
|
||||
<input className="form-control" id="validationCustom01" type="text" defaultValue="" required/>
|
||||
<div className="valid-feedback">Отлично!</div>
|
||||
<div className="invalid-feedback">Введите имя!</div>
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="validationCustom02">Фамилия</label>
|
||||
<input className="form-control" id="validationCustom02" type="text" defaultValue="" required/>
|
||||
<div className="valid-feedback">Отлично! </div>
|
||||
<div className="invalid-feedback">Введите Фамилию!</div>
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="validationCustomMail">Почта</label>
|
||||
<div className="input-group has-validation">
|
||||
<input className="form-control" id="validationCustomMail" type="email" aria-describedby="inputGroupPrepend" required/>
|
||||
<div className="valid-feedback">Отлично!</div>
|
||||
<div className="invalid-feedback">Введите почту!</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-12">
|
||||
<div className="form=check">
|
||||
<input className="form-check-input" id="invalidCheck" type="checkbox" defaultValue="" required/>
|
||||
<label className="form-check-label" htmlFor="invalidCheck">Согласие на обработку персональных данных</label>
|
||||
<div className="valid-feedback">Отлично!</div>
|
||||
<div className="invalid-feedback">Введите пароль!</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-12 d-flex">
|
||||
<div className="d-grid col-sm-4 mx-auto">
|
||||
<button type="button" id="add_btn" className="btn btn-outline-light btn-lg float-end" onClick={add_but}>Add</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<div className="row table-responsive mx-2">
|
||||
<table className="table mt-3">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">#</th>
|
||||
<th scope="col">Last Name</th>
|
||||
<th scope="col">First Name</th>
|
||||
<th scope="col">Email</th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tbody">
|
||||
{output.map((user) => (
|
||||
<tr key={user.id}>
|
||||
<th scope="row">{user.id}</th>
|
||||
<td>{user.firstName}</td>
|
||||
<td>{user.lastName}</td>
|
||||
<td>{user.email}</td>
|
||||
<td><button type="button" className="btn btn-outline-light text-center mx-2" onClick={(e) => edit_btn(user.id, e)}><i className="fa-sharp fa-solid fa-pen"></i></button></td>
|
||||
<td><button type="button" className="btn btn-outline-light text-center mx-2" onClick={(e) => rem_but(user.id, e)}><i className="fa-sharp fa-solid fa-trash"></i></button></td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
150
FrontEnd/src/components/catalogs/Catalog.jsx
Normal file
@ -0,0 +1,150 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import Toolbar from "../common/Toolbar";
|
||||
import Table from "../common/Card";
|
||||
import Modal from "../common/Modal";
|
||||
|
||||
export default function Catalog(props) {
|
||||
const [items, setItems] = useState([]);
|
||||
const [modalHeader, setModalHeader] = useState('');
|
||||
const [modalConfirm, setModalConfirm] = useState('');
|
||||
const [modalVisible, setModalVisible] = useState(false);
|
||||
const [isEdit, setEdit] = useState(false);
|
||||
const [userId,setUserId] = useState(0);
|
||||
const [value,setvalue]=useState('');
|
||||
useEffect(() => {
|
||||
loadItems();
|
||||
}, []);
|
||||
|
||||
useEffect(()=>
|
||||
{
|
||||
loadItems();
|
||||
},[userId])
|
||||
|
||||
|
||||
useEffect(()=>
|
||||
{
|
||||
loadItems2();
|
||||
},[value])
|
||||
const setUserIDd = async function(id)
|
||||
{
|
||||
setUserId(id);
|
||||
}
|
||||
const loadItems = async function() {
|
||||
const requestUrl = `http://localhost:8080/user/${userId}/posts`;
|
||||
const response = await fetch(requestUrl);
|
||||
const posts = await response.json();
|
||||
setItems(posts);
|
||||
}
|
||||
|
||||
const loadItems2 = async function() {
|
||||
const requestUrl = `http://localhost:8080/post/filteredposts?Text=${value}`;
|
||||
const response = await fetch(requestUrl);
|
||||
const posts = await response.json();
|
||||
console.log(posts);
|
||||
setItems(posts);
|
||||
}
|
||||
|
||||
const saveItem = async function() {
|
||||
if (!isEdit) {
|
||||
const requestUrl = `http://localhost:8080/user/${userId}/Post`;
|
||||
const temppost=JSON.stringify(props.data)
|
||||
const requestParams = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: temppost,
|
||||
};
|
||||
await fetch(requestUrl,requestParams).then(() => loadItems());
|
||||
|
||||
} else {
|
||||
const requestUrl = "http://localhost:8080/post/"+props.data.id;
|
||||
const temppost=JSON.stringify(props.data)
|
||||
const requestParams = {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: temppost,
|
||||
};
|
||||
await fetch(requestUrl,requestParams).then(() => loadItems());
|
||||
}
|
||||
}
|
||||
|
||||
function handleAdd() {
|
||||
setEdit(false);
|
||||
setModalHeader('Добавление элемента');
|
||||
setModalConfirm('Добавить');
|
||||
setModalVisible(true);
|
||||
props.onAdd();
|
||||
}
|
||||
|
||||
|
||||
const edit = async function(editedId) {
|
||||
const requestUrl = "http://localhost:8080/post/"+editedId;
|
||||
const requestParams = {
|
||||
mode: 'cors'
|
||||
}
|
||||
await fetch(requestUrl,requestParams)
|
||||
.then(data => {
|
||||
setEdit(true);
|
||||
setModalHeader('Редактирование элемента');
|
||||
setModalConfirm('Сохранить');
|
||||
setModalVisible(true);
|
||||
//props.onEdit(data);
|
||||
return data.json();
|
||||
}).then(data =>{
|
||||
props.onEdit(data);
|
||||
});
|
||||
}
|
||||
|
||||
const handleRemove = async function(id) {
|
||||
if (confirm('Удалить выбранные элементы?')) {
|
||||
const requestUrl = `http://localhost:8080/user/${userId}/Post/`+id;
|
||||
const requestParams = {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
};
|
||||
await fetch(requestUrl,requestParams).then(()=>loadItems());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
function handleModalHide() {
|
||||
setModalVisible(false);
|
||||
}
|
||||
|
||||
function handleModalDone() {
|
||||
saveItem();
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mx-3 my-2"><input type="text" id="search" className="form-control" required onChange={(event)=> setvalue(event.target.value)}/></div>
|
||||
<Toolbar
|
||||
onAdd={handleAdd}
|
||||
getUser={setUserIDd}
|
||||
/>
|
||||
<Table
|
||||
headers={props.headers}
|
||||
items={items}
|
||||
value={value}
|
||||
userId={userId}
|
||||
selectable={true}
|
||||
onEdit={edit}
|
||||
onRemove={handleRemove}/>
|
||||
<Modal
|
||||
header={modalHeader}
|
||||
confirm={modalConfirm}
|
||||
visible={modalVisible}
|
||||
onHide={handleModalHide}
|
||||
onDone={handleModalDone}>
|
||||
{props.children}
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
23
FrontEnd/src/components/catalogs/MainPage.jsx
Normal file
@ -0,0 +1,23 @@
|
||||
import { useEffect } from "react";
|
||||
import { useState } from "react";
|
||||
import Banner from '../common/Banner'
|
||||
|
||||
export default function Catalogs(props) {
|
||||
return (
|
||||
<div className="container-fluid">
|
||||
<Banner />
|
||||
<div className="lp"><img className="img-fluid img-school float-start my-2" src="img/Shkola.jpg" alt="shkola"/>
|
||||
<div>
|
||||
<p className="fs-4">Мы расположены по адресу: 423228, г. Нижневратовск, ул. Корзинова, д. 37</p>
|
||||
<div>
|
||||
<div className="fs-4">Контактные телефоны
|
||||
<p>(8228) 13-77-85</p>
|
||||
<p>(8800) 55-53-50</p>
|
||||
<p>факс (8911) 22-44-96</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div><a className="fs-4" href="mailto:Nizhnev.school10@mail.ru">email: Nizhnev.school10@mail.ru</a>
|
||||
</div>
|
||||
);
|
||||
}
|
61
FrontEnd/src/components/catalogs/News.jsx
Normal file
@ -0,0 +1,61 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import Catalog from './Catalog';
|
||||
import New from '../../models/NewDto';
|
||||
|
||||
export default function News(props) {
|
||||
const url = 'post/';
|
||||
const transformer = (data) => new New(data);
|
||||
const catalogStudHeaders = [
|
||||
{ name: 'image', label: 'Картинка' },
|
||||
{ name: 'heading', label: 'Заголовок' },
|
||||
{ name: 'content', label: 'Новости' },
|
||||
];
|
||||
|
||||
const [data, setData] = useState(new New());
|
||||
const fileReader=new FileReader();
|
||||
fileReader.onloadend=()=>{
|
||||
const tempval=fileReader.result;
|
||||
setData({ ...data, ['image']: tempval})
|
||||
}
|
||||
const handleOnChange=(event)=>{
|
||||
event.preventDefault();
|
||||
const file=event.target.files[0];
|
||||
fileReader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
function handleOnAdd() {
|
||||
setData(new New());
|
||||
}
|
||||
|
||||
function handleOnEdit(data) {
|
||||
setData(new New(data));
|
||||
}
|
||||
function handleFormChange(event) {
|
||||
setData({ ...data, [event.target.id]: event.target.value })
|
||||
}
|
||||
|
||||
return (
|
||||
<Catalog
|
||||
headers={catalogStudHeaders}
|
||||
url={url}
|
||||
transformer={transformer}
|
||||
data={data}
|
||||
onAdd={handleOnAdd}
|
||||
onEdit={handleOnEdit}>
|
||||
<div className="mb-3 text-black">
|
||||
<label htmlFor="image" className="form-label">Изображение</label>
|
||||
<input type="file" id="image" className="form-control" required onChange={handleOnChange}/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="heading" className="form-label text-black">Заголовок</label>
|
||||
<input type="text" id="heading" className="form-control" required
|
||||
value={data.heading} onChange={handleFormChange}/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="content" className="form-label text-black">Содержание</label>
|
||||
<input type="text" id="content" className="form-control" required
|
||||
value={data.content} onChange={handleFormChange}/>
|
||||
</div>
|
||||
</Catalog>
|
||||
);
|
||||
}
|
159
FrontEnd/src/components/catalogs/Post.jsx
Normal file
@ -0,0 +1,159 @@
|
||||
import React from "react";
|
||||
import { useState } from 'react';
|
||||
import {useEffect} from 'react';
|
||||
import New from '../../models/NewDto';
|
||||
import TableComment from "../common/TableComment";
|
||||
|
||||
export default function Post(props) {
|
||||
useEffect(() => {
|
||||
getAll();
|
||||
}, []);
|
||||
const [output, setOutput] = useState([]);
|
||||
const [userId,setUserId] = useState();
|
||||
const commentInput = document.getElementById("commentText");
|
||||
|
||||
|
||||
|
||||
const getAll = async function () {
|
||||
const queryString=window.location.search;
|
||||
const urlParams=new URLSearchParams(queryString);
|
||||
const id=urlParams.get('id');
|
||||
getCurrentPost(id).then(curPost => setad(curPost));
|
||||
getComments(id)
|
||||
|
||||
const requestUrl = "http://localhost:8080/user";
|
||||
const response = await fetch(requestUrl);
|
||||
const users = await response.json();
|
||||
setOutput(users);
|
||||
}
|
||||
|
||||
|
||||
|
||||
const refresh = async function(id,text)
|
||||
{
|
||||
const requestParams={
|
||||
method:"PUT",
|
||||
headers:{
|
||||
"Content-Type":"application/json",
|
||||
}
|
||||
};
|
||||
const response=await fetch(`http://localhost:8080/comment/${id}?Text=${text}`,requestParams);
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
|
||||
|
||||
const create = async function (text, id) {
|
||||
const requestParams = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
};
|
||||
const response = await fetch(`http://localhost:8080/post/${ad.id}/Comment/${id}?Text=${text}`,requestParams);
|
||||
}
|
||||
|
||||
|
||||
|
||||
const getCurrentPost = async function (id) {
|
||||
const requestUrl = "http://localhost:8080/post/"+id;
|
||||
const response = await fetch(requestUrl);
|
||||
const product = await response.json();
|
||||
return product;
|
||||
}
|
||||
|
||||
|
||||
|
||||
const remove = async function(id){
|
||||
const requestParams = {
|
||||
method: "DELETE",
|
||||
headers:{
|
||||
"Content-Type":"application/json",
|
||||
}
|
||||
};
|
||||
const requestUrl = `http://localhost:8080/post/${ad.id}/Comment/${id}`;
|
||||
const response=await fetch(requestUrl,requestParams);
|
||||
return await response.json;
|
||||
};
|
||||
|
||||
|
||||
function getuser(){
|
||||
var selectBox = document.getElementById("selectBox");
|
||||
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
|
||||
setUserId(selectedValue);
|
||||
}
|
||||
|
||||
|
||||
const getComments = async function(id)
|
||||
{
|
||||
const requesturl = "http://localhost:8080/post/"+id+"/comments"
|
||||
const response = await fetch(requesturl);
|
||||
const comments = await response.json();
|
||||
setComments(comments);
|
||||
}
|
||||
const [ad, setad] = useState([]);
|
||||
const [comments,setComments] = useState([]);
|
||||
|
||||
|
||||
const rem_but = function(id,event)
|
||||
{
|
||||
remove(id).then((result)=>{
|
||||
getAll();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
const add_but = function(event)
|
||||
{
|
||||
event.preventDefault();
|
||||
create(commentInput.value, userId).then((result) => {
|
||||
getAll();
|
||||
commentInput.value = "";
|
||||
alert(`Comment[id=${result.id}, text=${result.firstName}]`);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
const edit_btn = function(id,event)
|
||||
{
|
||||
console.log("Обновление")
|
||||
refresh(id, commentInput.value).then((result)=>{
|
||||
getAll();
|
||||
commentInput.value = "";
|
||||
});
|
||||
}
|
||||
return(
|
||||
<div>
|
||||
<div className="da d-flex my-2">
|
||||
<div><img className="imga img-fluid float-start mx-2" style={{width: "500px" ,height: "300px" }} src={ad.image}/></div>
|
||||
<div className="container-fluid my-2 mx-1">
|
||||
<h1>{ad.heading}</h1>
|
||||
<p>{ad.content}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="d-flex mx-2">
|
||||
<select id="selectBox" onChange={getuser}>
|
||||
<option disabled value="">Выбор...</option>
|
||||
{
|
||||
output.map((client) => (
|
||||
<option className='text-black' key={client.id} value={client.id}>{client.firstName}</option>
|
||||
))}
|
||||
</select>
|
||||
<input className="form-control" id="commentText" type="text" defaultValue="" required/>
|
||||
<button type="button" className="btn btn-primary" onClick={(e)=>add_but(e)}>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
<div className="row table-responsive mx-2">
|
||||
<TableComment
|
||||
comments={comments}
|
||||
onRemove={rem_but}
|
||||
onEdit={edit_btn}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
);
|
||||
|
||||
}
|
13
FrontEnd/src/components/catalogs/Raspisanie.jsx
Normal file
@ -0,0 +1,13 @@
|
||||
|
||||
|
||||
export default function ReportGroupStudents(props) {
|
||||
return (
|
||||
<div className="container-fluid justify-content-center align-items-center d-flex flex-column my-2">
|
||||
<div>
|
||||
<h6>Расписание<img className="pdf-size " src="img/Rasp.png" alt="Rasp"/></h6>
|
||||
</div>
|
||||
<div> <a href="Rasp(1-4).pdf" target="_blank"><img className="pdf-size" src="img/6666.png"/></a><a href="Rasp(1-4).pdf" target="_blank">Расписание 1 - 4 кл. (.pdf)</a></div><br/><br/>
|
||||
<div> <a href="Rasp(5-11).pdf" target="_blank"><img className="pdf-size" src="img/6666.png"/></a><a href="Rasp(5-11).pdf" target="_blank">Расписание 5 - 11 кл. (.pdf)</a></div>
|
||||
</div>
|
||||
);
|
||||
}
|
135
FrontEnd/src/components/catalogs/RezhimRaboty.jsx
Normal file
@ -0,0 +1,135 @@
|
||||
|
||||
|
||||
export default function Reports(props) {
|
||||
return (
|
||||
<div className="container-fluid my-2">
|
||||
<div className="float-start me-5">
|
||||
<h3 className="text-wrap">Расписание звонков</h3>
|
||||
<table className="Vnov1 float-start table-bordered">
|
||||
<tbody>
|
||||
<tr>
|
||||
<th colSpan="2">1 смена</th>
|
||||
<th colSpan="2">2 смена</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td></td>
|
||||
<td> </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1 урок</td>
|
||||
<td>8.00-8.45</td>
|
||||
<td>0 урок</td>
|
||||
<td>12.55-13.40</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>2 урок </td>
|
||||
<td>8.55-9.40 </td>
|
||||
<td>1 урок </td>
|
||||
<td>13.50-14.35</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>3 урок </td>
|
||||
<td>10.00-10.45</td>
|
||||
<td>2 урок</td>
|
||||
<td>14.50-15.35</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>4 урок</td>
|
||||
<td>11.05-11.50</td>
|
||||
<td>3 урок</td>
|
||||
<td>12.00-12.45</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>5 урок</td>
|
||||
<td>12.00-12.45</td>
|
||||
<td>4 урок</td>
|
||||
<td>16.45-17.30</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>6 урок</td>
|
||||
<td>12.55-13.40 </td>
|
||||
<td>5 урок</td>
|
||||
<td>17.40-18.25 </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>7 урок</td>class
|
||||
<td>13.50-14.35</td>
|
||||
<td> </td>
|
||||
<td></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div>
|
||||
<h3>Режим работы ОУ:
|
||||
<div className="align-items-justify text-wrap fs-5">Учебный год в МБОУ средняя общеобразовательная школа №10 начинается 2 сентября, состоит из 3-х триместров, включает каникулы по графику. МБОУ средняя общеобразовательная школа №10 работает в две смены. Школа работает в течение 5 дней в неделю с понедельника по пятницу, выходной день – суббота и воскресенье — в 1-11 классах. Продолжительность учебного года – 33 учебных недели для учащихся 1-х классов, 34 учебных недель для учащихся 2-11 классов. Для учащихся, обучающихся на дому, продолжительность учебного года составляет 34 недели. Начало учебных занятий в 8-00.
|
||||
<table className="table-bordered">
|
||||
|
||||
<tbody>
|
||||
<th>Триместр</th>
|
||||
<th>Дата начала/дата окончания</th>
|
||||
<th colSpan="2">Каникулы</th>
|
||||
<tr>
|
||||
<td>I</td>
|
||||
<td>02.09.2022 - 19.11.2022</td>
|
||||
<td>08.10.2022 - 13.10.2022</td>
|
||||
<td>20.11.2022 - 25.11.2022</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>II</td>
|
||||
<td>26.11.2022 - 19.02.2023</td>
|
||||
<td>28.12.2022 - 07.01.2023 </td>
|
||||
<td>20.02.2023 - 25.02.2023</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>III</td>
|
||||
<td>26.02.2023 - 29.05.2023</td>
|
||||
<td>10.04.2023 - 15.04.2023</td>
|
||||
<td>30.05.2023 - 31.08.2023</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
24
FrontEnd/src/components/common/Banner.jsx
Normal file
@ -0,0 +1,24 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import '../../style.css'
|
||||
export default function Banner(props) {
|
||||
const[bannerNum,setBanner]=useState(['show','hide','hide']);
|
||||
useEffect(() => {
|
||||
const length=3;
|
||||
var old = length-1;
|
||||
var current = 0;
|
||||
const timer = window.setInterval(()=>{
|
||||
setBanner([...bannerNum, bannerNum[current] = 'show', bannerNum[old] = 'hide']);
|
||||
old = current;
|
||||
current++;
|
||||
if (current ===length) {
|
||||
current = 0;
|
||||
}
|
||||
},5000);
|
||||
return()=>{
|
||||
window.clearInterval(timer);
|
||||
}
|
||||
},[]);
|
||||
return(
|
||||
<div id="banner"><img className={bannerNum[0]} src="img/banner1.png"/><img className={bannerNum[1]} src="img/banner2.png"/><img className={bannerNum[2]} src="img/banner3.png"/></div>
|
||||
);
|
||||
}
|
98
FrontEnd/src/components/common/Card.jsx
Normal file
@ -0,0 +1,98 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import ModalEdit from './ModalComment';
|
||||
import TablePostAndComment from './TablePostAndComment';
|
||||
export default function Card(props) {
|
||||
|
||||
function edit(id) {
|
||||
props.onEdit(id);
|
||||
}
|
||||
|
||||
function remove(id) {
|
||||
props.onRemove(id);
|
||||
}
|
||||
useEffect(() => {
|
||||
getAll();
|
||||
}, []);
|
||||
|
||||
const [clients, setClientst] = useState([]);
|
||||
const getAll = async function () {
|
||||
const requestUrl = "http://localhost:8080/user";
|
||||
const response = await fetch(requestUrl);
|
||||
const users = await response.json();
|
||||
setClientst(users);
|
||||
}
|
||||
const [modalTable, setModalTable] = useState(false);
|
||||
const [currEditItem, setCurrEditItem] = useState(0);
|
||||
const [text, setText] = useState('');
|
||||
function handleEdit(id) {
|
||||
console.info("Start edit script");
|
||||
setCurrEditItem(id);
|
||||
setModalTable(true)
|
||||
console.info('End edit script');
|
||||
};
|
||||
const handleSubmitEdit = async (e, id) => {
|
||||
console.info('Start synchronize edit');
|
||||
e.preventDefault(); // страница перестает перезагружаться
|
||||
const requestUrl = `http://localhost:8080/post/${id}/Comment/${props.userId}?Text=${text}`;
|
||||
const requestParams = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
};
|
||||
await fetch(requestUrl,requestParams);
|
||||
setText('');
|
||||
setModalTable(false);
|
||||
};
|
||||
|
||||
|
||||
return (
|
||||
<div className="container-fluid mt-3">
|
||||
{
|
||||
props.items.map((item, index) =>
|
||||
<div key={item.id}
|
||||
className="card border-dark mb-3 d-flex flex-row text-black justify-content-between">
|
||||
<div className=''>
|
||||
<img className="col" style={{width: "300px" ,height: "200px" }} src={item.image}/>
|
||||
</div>
|
||||
<div className='d-flex flex-grow-1 flex-column'>
|
||||
<div className='flex-grow-1 mx-2'>
|
||||
{
|
||||
props.headers.map(header =>
|
||||
header.name == "image" ? null :
|
||||
<div className="" key={item.id + header.name}>{item[header.name]}</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
<div className="d-flex flex-row justify-content-end ">
|
||||
<button type="button" className="btn btn-outline-primary text-center mx-2" data-bs-toggle="modal" data-bs-target="#redact" onClick={(e) => edit(item.id, e)}>
|
||||
<i className="fa-sharp fa-solid fa-pen"></i>
|
||||
</button>
|
||||
<button href="#"
|
||||
className="btn btn-outline-primary mx-3"
|
||||
onClick={(e) => remove(item.id, e)}><i className="fa-sharp fa-solid fa-trash"></i></button>
|
||||
<a href={`/Post?id=${item.id}`} className='btn btn-outline-primary mx-2'><i className="fa-solid fa-envelopes-bulk"></i></a>
|
||||
</div>
|
||||
<TablePostAndComment
|
||||
comments={item.comments}
|
||||
value={props.value}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
<ModalEdit visible={modalTable} setVisible={setModalTable}>
|
||||
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit" onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
|
||||
<div className="row">
|
||||
<label className="form-label" htmlFor="priceEdit">Комментарий</label>
|
||||
<input value={text} onChange={e => setText(e.target.value)} className="form-control" name='priceEdit' id="priceEdit" type="text" placeholder="Введите содержимое комментария" required />
|
||||
</div>
|
||||
<div className="text-center mt-3">
|
||||
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить изменения</button>
|
||||
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal" onClick={() => setModalTable(false)}>Отмена</button>
|
||||
</div>
|
||||
</form>
|
||||
</ModalEdit>
|
||||
</div>
|
||||
);
|
||||
}
|
7
FrontEnd/src/components/common/Footer.jsx
Normal file
@ -0,0 +1,7 @@
|
||||
import { NavLink } from 'react-router-dom';
|
||||
|
||||
export default function Footer(props) {
|
||||
return (
|
||||
<footer className="container-fluid d-flex text-white bg-primary bg-gradient mt-auto">© 2022 МОУ "СОШ №10"</footer>
|
||||
);
|
||||
}
|
30
FrontEnd/src/components/common/Header.jsx
Normal file
@ -0,0 +1,30 @@
|
||||
import { NavLink } from 'react-router-dom';
|
||||
|
||||
export default function Header(props) {
|
||||
return (
|
||||
<header className="fs-4 fw-bold p-1 text-white bg-primary bg-gradient">
|
||||
<div><img className="img-fluid float-start" src="../img/Emblema.png" alt="Emblema"/>
|
||||
<p className="fs-5 Cont">Муниципальное бюджетное общеобразовательное учреждение средняя общеобразовательная школа №10</p>
|
||||
</div>
|
||||
<nav className="navbar navbar-expand-md navbar-dark">
|
||||
<div className="container-fluid">
|
||||
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span></button>
|
||||
<div className="navbar-collapse collapse justify-content-end" id="navbarNav">
|
||||
<nav className="headers-problem navbar navbar-expand-lg d-flex">
|
||||
{
|
||||
props.links.map(route =>
|
||||
<button key={route.path}
|
||||
className="btn btn-outline-light mx-1">
|
||||
<NavLink className="nav-link" to={route.path}>
|
||||
{route.label}
|
||||
</NavLink>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
);
|
||||
}
|
46
FrontEnd/src/components/common/Modal.jsx
Normal file
@ -0,0 +1,46 @@
|
||||
import React from "react";
|
||||
|
||||
export default function Modal(props) {
|
||||
const formRef = React.createRef();
|
||||
|
||||
function hide() {
|
||||
props.onHide();
|
||||
}
|
||||
|
||||
function done(e) {
|
||||
e.preventDefault();
|
||||
if (formRef.current.checkValidity()) {
|
||||
props.onDone();
|
||||
hide();
|
||||
} else {
|
||||
formRef.current.reportValidity();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="modal fade show" tabIndex="-1" aria-hidden="true"
|
||||
style={{ display: props.visible ? 'block' : 'none' }}>
|
||||
<div className="modal-dialog">
|
||||
<div className="modal-content">
|
||||
<div className="modal-header">
|
||||
<h1 className="modal-title fs-5" id="exampleModalLabel">{props.header}</h1>
|
||||
<button className="btn-close" type="button" aria-label="Close"
|
||||
onClick={hide}></button>
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
<form ref={formRef} onSubmit={done}>
|
||||
{props.children}
|
||||
</form>
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<button className="btn btn-secondary" type="button" onClick={hide}>Закрыть</button>
|
||||
<button className="btn btn-primary" type="button" onClick={done}>
|
||||
{props.confirm}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
18
FrontEnd/src/components/common/ModalComment.jsx
Normal file
@ -0,0 +1,18 @@
|
||||
import { React } from 'react'
|
||||
import classes from '../../ModalEdit.module.css'
|
||||
|
||||
export default function ModalEdit({children, visible, setVisible}) {
|
||||
|
||||
const rootClasses = [classes.myModal]
|
||||
if (visible) {
|
||||
rootClasses.push(classes.active);
|
||||
}
|
||||
//onClick={()=>setVisible(false)}
|
||||
return (
|
||||
<div className={rootClasses.join(' ')} >
|
||||
<div className={classes.myModalContent}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
34
FrontEnd/src/components/common/TableComment.jsx
Normal file
@ -0,0 +1,34 @@
|
||||
export default function TableComment(props) {
|
||||
function edit(id,e) {
|
||||
props.onEdit(id);
|
||||
}
|
||||
|
||||
function remove(id,e) {
|
||||
props.onRemove(id,e);
|
||||
}
|
||||
|
||||
|
||||
return(
|
||||
<table className="table mt-3">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">#</th>
|
||||
<th scope="col">Text</th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tbody">
|
||||
{props.comments.map((comment) => (
|
||||
<tr key={comment.id}>
|
||||
{console.log(comment.user)}
|
||||
<th scope="row">{comment.user}</th>
|
||||
<td>{comment.text}</td>
|
||||
<td><button type="button" className="btn btn-outline-light text-center mx-2" onClick={(e) => edit(comment.id, e)}><i className="fa-sharp fa-solid fa-pen"></i></button></td>
|
||||
<td><button type="button" className="btn btn-outline-light text-center mx-2" onClick={(e) => remove(comment.id, e)}><i className="fa-sharp fa-solid fa-trash"></i></button></td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
26
FrontEnd/src/components/common/TablePostAndComment.jsx
Normal file
@ -0,0 +1,26 @@
|
||||
export default function TablePostAndComment(props) {
|
||||
const filteredads=props.comments.filter(ads=>{
|
||||
return ads.text.includes(props.value);
|
||||
})
|
||||
return(
|
||||
<table className="table mt-3">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tbody">
|
||||
{filteredads.map((comment) => (
|
||||
<tr key={comment.id}>
|
||||
{console.log(comment.user)}
|
||||
<th scope="row">{comment.user}</th>
|
||||
<td>{comment.text}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
43
FrontEnd/src/components/common/Toolbar.jsx
Normal file
@ -0,0 +1,43 @@
|
||||
import { useState } from 'react';
|
||||
import {useEffect} from 'react';
|
||||
|
||||
export default function Toolbar(props) {
|
||||
function add() {
|
||||
props.onAdd();
|
||||
}
|
||||
const [clients, setClientst] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
getAll();
|
||||
}, []);
|
||||
const getAll = async function () {
|
||||
const requestUrl = "http://localhost:8080/user";
|
||||
const response = await fetch(requestUrl);
|
||||
const users = await response.json();
|
||||
setClientst(users);
|
||||
}
|
||||
function getuser(){
|
||||
var selectBox = document.getElementById("selectBox");
|
||||
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
|
||||
props.getUser(selectedValue);
|
||||
}
|
||||
return (
|
||||
<div className="d-flex float-start my-2">
|
||||
<div className="mx-1">
|
||||
<select id="selectBox" onChange={getuser}>
|
||||
<option disabled value="">Выбор...</option>
|
||||
{
|
||||
clients.map((client) => (
|
||||
<option className='text-black' key={client.id} value={client.id}>{client.firstName}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<button type="button" className="btn btn-primary" onClick={add}>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
|
||||
</div >
|
||||
);
|
||||
}
|
10
FrontEnd/src/main.jsx
Normal file
@ -0,0 +1,10 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import App from './App'
|
||||
import './style.css'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('app')).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
)
|
6
FrontEnd/src/models/CommentDto.js
Normal file
@ -0,0 +1,6 @@
|
||||
export default class CommentDto {
|
||||
constructor(args) {
|
||||
this.id = args.id || null;
|
||||
this.text = args.text;
|
||||
}
|
||||
}
|
9
FrontEnd/src/models/NewDto.js
Normal file
@ -0,0 +1,9 @@
|
||||
export default class NewDto {
|
||||
constructor(data) {
|
||||
this.id = data?.id || null;
|
||||
this.image = data?.image;
|
||||
this.heading = data?.heading;
|
||||
this.content = data?.content;
|
||||
}
|
||||
|
||||
}
|
8
FrontEnd/src/models/UserDto.js
Normal file
@ -0,0 +1,8 @@
|
||||
export default class BuyerDto {
|
||||
constructor(args) {
|
||||
this.id = args.id || null;
|
||||
this.firstName = args.firstName;
|
||||
this.lastName = args.lastName;
|
||||
this.email = args.email;
|
||||
}
|
||||
}
|
146
FrontEnd/src/style.css
Normal file
@ -0,0 +1,146 @@
|
||||
html
|
||||
{
|
||||
min-height: 100vh;
|
||||
}
|
||||
header .img-fluid
|
||||
{
|
||||
width:232px;
|
||||
height:100px;
|
||||
}
|
||||
|
||||
article .img-fluid
|
||||
{
|
||||
height:250px;
|
||||
}
|
||||
article .img-fluid1
|
||||
{
|
||||
height:100%;
|
||||
width: 96%;
|
||||
}
|
||||
.owl
|
||||
{
|
||||
width:300px;
|
||||
}
|
||||
.pdf-size
|
||||
{
|
||||
width:70px;
|
||||
}
|
||||
body
|
||||
{
|
||||
min-height: 100vh;
|
||||
}
|
||||
.body_app
|
||||
{
|
||||
display: grid;
|
||||
grid-template-rows:auto 1fr auto;
|
||||
min-height: 100vh;
|
||||
}
|
||||
.lp
|
||||
{
|
||||
padding-left: 30px;
|
||||
}
|
||||
.img-school
|
||||
{
|
||||
margin-right: 1em;
|
||||
float: start;
|
||||
|
||||
}
|
||||
.Vnov
|
||||
{
|
||||
margin-right: 1em;
|
||||
}
|
||||
.Vnov1
|
||||
{
|
||||
margin-right: 1em;
|
||||
}
|
||||
.Cont
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 800px) {
|
||||
.owl {
|
||||
display:none;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 1164px) {
|
||||
.img-school
|
||||
{
|
||||
margin-right: 170px;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 554px) {
|
||||
.img-school
|
||||
{
|
||||
height: 20% !important;
|
||||
width: 75%;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 727px) {
|
||||
.headers-problem
|
||||
{
|
||||
|
||||
flex-direction: column;
|
||||
}
|
||||
.navbar
|
||||
{
|
||||
align-items: flex-start !important;
|
||||
}
|
||||
|
||||
}
|
||||
@media only screen and (max-width: 959px) {
|
||||
.navbar
|
||||
{
|
||||
float:left !important;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 463px) {
|
||||
.Vnov
|
||||
{
|
||||
margin-right: 140px;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 575px) {
|
||||
.Vnov1
|
||||
{
|
||||
margin-right: 200px;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 585px) {
|
||||
.Cont
|
||||
{
|
||||
margin-right: 200px;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#banner {
|
||||
margin: 15px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
#banner img {
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
#banner img.show {
|
||||
height: 40%;
|
||||
width: 60%;
|
||||
opacity: 1;
|
||||
transition: opacity 1s, visibility 0s;
|
||||
}
|
||||
|
||||
#banner img.hide {
|
||||
height: 0;
|
||||
width: 0;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: opacity 1s, visibility 0s 1s;
|
||||
}
|
||||
|
||||
.Pole_height
|
||||
{
|
||||
height: 80px;
|
||||
}
|
7
FrontEnd/vite.config.js
Normal file
@ -0,0 +1,7 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()]
|
||||
})
|
27
build.gradle
@ -4,19 +4,40 @@ plugins {
|
||||
id 'io.spring.dependency-management' version '1.1.0'
|
||||
}
|
||||
|
||||
group = 'ru.ulstu.is'
|
||||
group = 'np'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
sourceCompatibility = '17'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
jar {
|
||||
enabled = false
|
||||
}
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
|
||||
implementation 'org.springframework.boot:spring-boot-devtools'
|
||||
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
|
||||
|
||||
implementation 'org.webjars:bootstrap:5.1.3'
|
||||
implementation 'org.webjars:jquery:3.6.0'
|
||||
implementation 'org.webjars:font-awesome:6.1.0'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'com.h2database:h2:2.1.210'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
|
||||
|
||||
implementation 'org.hibernate.validator:hibernate-validator'
|
||||
|
||||
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
}
|
BIN
reports/Отчёт 1.docx
Normal file
BIN
reports/Отчёт 2.docx
Normal file
BIN
reports/Отчёт 3.docx
Normal file
BIN
reports/Отчёт 4.docx
Normal file
BIN
reports/Отчёт 5.docx
Normal file
BIN
reports/Отчёт 6.docx
Normal file
@ -1 +1 @@
|
||||
rootProject.name = 'sbapp'
|
||||
rootProject.name = 'sbapp'
|
@ -0,0 +1,40 @@
|
||||
package ru.ulstu.is.sbapp.Comment.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.ulstu.is.sbapp.Comment.model.CommentDto;
|
||||
import ru.ulstu.is.sbapp.Comment.service.CommentService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/comment")
|
||||
public class CommentController {
|
||||
private final CommentService commentService;
|
||||
public CommentController(CommentService commentService) {
|
||||
this.commentService = commentService;
|
||||
}
|
||||
@GetMapping("/{id}")
|
||||
public CommentDto getComment(@PathVariable Long id) {
|
||||
return new CommentDto(commentService.findComment(id));
|
||||
}
|
||||
@GetMapping
|
||||
public List<CommentDto> getComments() {
|
||||
return commentService.findAllComments().stream()
|
||||
.map(CommentDto::new)
|
||||
.toList();
|
||||
}
|
||||
@PostMapping
|
||||
public CommentDto createComment(@RequestParam("Text") String Text){
|
||||
return new CommentDto(commentService.addComment(Text));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public CommentDto updateComment(@PathVariable Long id,
|
||||
@RequestParam("Text") String Text){
|
||||
return new CommentDto(commentService.updateComment(id,Text));
|
||||
}
|
||||
@DeleteMapping("/{id}")
|
||||
public CommentDto deleteComment(@PathVariable Long id) {
|
||||
return new CommentDto(commentService.deleteComment(id));
|
||||
}
|
||||
}
|
81
src/main/java/ru/ulstu/is/sbapp/Comment/model/Comment.java
Normal file
@ -0,0 +1,81 @@
|
||||
package ru.ulstu.is.sbapp.Comment.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
public class Comment {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
@NotBlank(message = "Text cannot be null")
|
||||
private String Text;
|
||||
|
||||
@ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.MERGE)
|
||||
private Post post;
|
||||
|
||||
@ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.MERGE)
|
||||
private User user;
|
||||
|
||||
public Comment()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public Comment(String text)
|
||||
{
|
||||
this.Text=text;
|
||||
}
|
||||
public Long getId()
|
||||
{
|
||||
return id;
|
||||
}
|
||||
public String getText() {return Text;}
|
||||
public void setText(String text){this.Text=text;}
|
||||
public User getUser()
|
||||
{
|
||||
return user;
|
||||
}
|
||||
public Post getPost()
|
||||
{
|
||||
return post;
|
||||
}
|
||||
public void setPost(Post post, User user){
|
||||
if(post!=null)
|
||||
{
|
||||
post.getComments().add(this);
|
||||
this.post = post;
|
||||
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Comment comment = (Comment) o;
|
||||
return Objects.equals(id, comment.id);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Comment{" +
|
||||
"id=" + id +
|
||||
", Text='" + Text + '\'' +
|
||||
'}';
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package ru.ulstu.is.sbapp.Comment.model;
|
||||
|
||||
|
||||
public class CommentDto {
|
||||
private Long id;
|
||||
private String Text;
|
||||
private String userName;
|
||||
|
||||
private Long postId;
|
||||
public CommentDto(){}
|
||||
public CommentDto(Comment comment)
|
||||
{
|
||||
this.id= comment.getId();
|
||||
this.Text=comment.getText();
|
||||
this.userName=comment.getUser().getLogin();
|
||||
this.postId=comment.getPost().getId();
|
||||
}
|
||||
public Long getId()
|
||||
{
|
||||
return id;
|
||||
}
|
||||
public String getText() {return Text;}
|
||||
|
||||
public String getUser()
|
||||
{
|
||||
return userName;
|
||||
}
|
||||
|
||||
public Long getPostId()
|
||||
{
|
||||
return postId;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
Text = text;
|
||||
}
|
||||
|
||||
public void setUserName(String userName) {
|
||||
this.userName = userName;
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ru.ulstu.is.sbapp.Comment.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
|
||||
public interface CommentRepository extends JpaRepository<Comment, Long> {
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ru.ulstu.is.sbapp.Comment.service;
|
||||
|
||||
public class CommentNotFoundException extends RuntimeException{
|
||||
public CommentNotFoundException(Long id) {
|
||||
super(String.format("Comment with id [%s] is not found", id));
|
||||
}
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
package ru.ulstu.is.sbapp.Comment.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Comment.repository.CommentRepository;
|
||||
import ru.ulstu.is.sbapp.Util.validation.ValidatorUtil;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class CommentService {
|
||||
private final CommentRepository commentRepository;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public CommentService(CommentRepository commentRepository, ValidatorUtil validatorUtil)
|
||||
{
|
||||
this.commentRepository=commentRepository;
|
||||
this.validatorUtil=validatorUtil;
|
||||
}
|
||||
@Transactional
|
||||
public Comment addComment(String Text) {
|
||||
final Comment comment = new Comment(Text);
|
||||
validatorUtil.validate(comment);
|
||||
return commentRepository.save(comment);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void saveComment(Comment comment) {
|
||||
commentRepository.save(comment);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Comment findComment(Long id) {
|
||||
final Optional<Comment> client = commentRepository.findById(id);
|
||||
return client.orElseThrow(() -> new CommentNotFoundException(id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<Comment> findAllComments() {
|
||||
return commentRepository.findAll();
|
||||
}
|
||||
@Transactional
|
||||
public Comment updateComment(Long id,String Text) {
|
||||
final Comment currentComment = findComment(id);
|
||||
currentComment.setText(Text);
|
||||
validatorUtil.validate(currentComment);
|
||||
return commentRepository.save(currentComment);
|
||||
}
|
||||
@Transactional
|
||||
public Comment deleteComment(Long id) {
|
||||
final Comment currentComment = findComment(id);
|
||||
commentRepository.delete(currentComment);
|
||||
return currentComment;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAllComments() {
|
||||
commentRepository.deleteAll();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package ru.ulstu.is.sbapp.Configuration;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
public class PasswordEncoderConfiguration {
|
||||
@Bean
|
||||
public PasswordEncoder createPasswordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
package ru.ulstu.is.sbapp.Configuration;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import ru.ulstu.is.sbapp.User.controller.UserSignupMvcController;
|
||||
import ru.ulstu.is.sbapp.User.model.UserRole;
|
||||
import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableMethodSecurity(
|
||||
securedEnabled = true
|
||||
)
|
||||
public class SecurityConfiguration {
|
||||
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
|
||||
private static final String LOGIN_URL = "/login";
|
||||
private final UserService userService;
|
||||
|
||||
public SecurityConfiguration(UserService userService) {
|
||||
this.userService = userService;
|
||||
createAdminOnStartup();
|
||||
}
|
||||
|
||||
private void createAdminOnStartup() {
|
||||
final String admin = "admin";
|
||||
if (userService.findByLogin(admin) == null) {
|
||||
log.info("Admin user successfully created");
|
||||
userService.addUser(admin, "adminemail@gmail.com", admin, admin, UserRole.ADMIN);
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http.headers().frameOptions().sameOrigin().and()
|
||||
.cors().and()
|
||||
.csrf().disable()
|
||||
.authorizeHttpRequests()
|
||||
.requestMatchers(UserSignupMvcController.SIGNUP_URL).permitAll()
|
||||
.requestMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.formLogin()
|
||||
.loginPage(LOGIN_URL).permitAll()
|
||||
.and()
|
||||
.logout().permitAll();
|
||||
http.formLogin().defaultSuccessUrl("/index",true);
|
||||
return http.userDetailsService(userService).build();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public WebSecurityCustomizer webSecurityCustomizer() {
|
||||
return (web) -> web.ignoring()
|
||||
.requestMatchers("/css/**")
|
||||
.requestMatchers("/js/**")
|
||||
.requestMatchers("/templates/**")
|
||||
.requestMatchers("/webjars/**")
|
||||
.requestMatchers("/img/Emblema.png");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package ru.ulstu.is.sbapp.Configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
public static final String REST_API = "/api";
|
||||
|
||||
@Override
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
WebMvcConfigurer.super.addViewControllers(registry);
|
||||
registry.addViewController("login");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**").allowedMethods("*");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
package ru.ulstu.is.sbapp.Post.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.ulstu.is.sbapp.Comment.model.CommentDto;
|
||||
import ru.ulstu.is.sbapp.Post.model.PostDto;
|
||||
import ru.ulstu.is.sbapp.Post.service.PostService;
|
||||
import ru.ulstu.is.sbapp.Configuration.WebConfiguration;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(WebConfiguration.REST_API + "/post")
|
||||
public class PostController {
|
||||
private final PostService postService;
|
||||
public PostController(PostService postService) {
|
||||
this.postService = postService;
|
||||
}
|
||||
@GetMapping("/{id}")
|
||||
public PostDto getPost(@PathVariable Long id) {
|
||||
return new PostDto(postService.findPost(id));
|
||||
}
|
||||
@GetMapping
|
||||
public List<PostDto> getPosts() {
|
||||
return postService.findAllPosts().stream()
|
||||
.map(PostDto::new)
|
||||
.toList();
|
||||
}
|
||||
@GetMapping("/{id}/comments")
|
||||
public List<CommentDto> getComments(@PathVariable Long id) {
|
||||
return postService.GetPostComments(id).stream()
|
||||
.map(CommentDto::new)
|
||||
.toList();
|
||||
}
|
||||
@PostMapping
|
||||
public PostDto createPost(@RequestBody @Valid PostDto postDto){
|
||||
return new PostDto(postService.addPost(postDto));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public PostDto updatePost(@PathVariable Long id,
|
||||
@RequestBody @Valid PostDto postDto){
|
||||
return new PostDto(postService.updatePost(id,postDto));
|
||||
}
|
||||
@PostMapping("/{id}/Comment/{userId}")
|
||||
public void addComment(@PathVariable Long id,
|
||||
@PathVariable Long userId,
|
||||
@RequestParam("Text") String Text) {
|
||||
postService.addCommentToPost(id, userId,Text);
|
||||
}
|
||||
@DeleteMapping("/{id}/Comment/{commentId}")
|
||||
public void removeComment(@PathVariable Long id,
|
||||
@PathVariable Long commentId)
|
||||
{
|
||||
postService.removeCommentFromPost(id,commentId);
|
||||
}
|
||||
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public void deletePost(@PathVariable Long id) {
|
||||
postService.deletePost(id);
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
public void deleteall()
|
||||
{
|
||||
postService.deleteAllPosts();
|
||||
}
|
||||
|
||||
@GetMapping("/filteredposts")
|
||||
public List<PostDto> getPostsAndComments(@RequestParam("Text") String Text){
|
||||
return postService.getPostsAndComments(Text).stream()
|
||||
.map(PostDto::new)
|
||||
.toList();
|
||||
}
|
||||
}
|
@ -0,0 +1,184 @@
|
||||
package ru.ulstu.is.sbapp.Post.controller;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Comment.model.CommentDto;
|
||||
import ru.ulstu.is.sbapp.Comment.service.CommentService;
|
||||
import ru.ulstu.is.sbapp.Post.model.PostDto;
|
||||
import ru.ulstu.is.sbapp.Post.service.PostService;
|
||||
import ru.ulstu.is.sbapp.User.model.UserDto;
|
||||
import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.Principal;
|
||||
import java.util.Base64;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/index")
|
||||
public class PostMvcController {
|
||||
private final PostService postService;
|
||||
private final UserService userService;
|
||||
private final CommentService commentService;
|
||||
public PostMvcController(PostService postService,UserService userService,CommentService commentService)
|
||||
{
|
||||
this.postService = postService;
|
||||
this.userService = userService;
|
||||
this.commentService=commentService;
|
||||
}
|
||||
@GetMapping("/{id}")
|
||||
public String getPost(@PathVariable Long id,Model model)
|
||||
{
|
||||
model.addAttribute("post",
|
||||
new PostDto(postService.findPost(id)));
|
||||
model.addAttribute("users",
|
||||
userService.findAllUsers().stream()
|
||||
.map(UserDto::new)
|
||||
.toList());
|
||||
model.addAttribute("comments",
|
||||
postService.GetPostComments(id).stream()
|
||||
.map(CommentDto::new)
|
||||
.toList());
|
||||
return "post-page";
|
||||
}
|
||||
@GetMapping
|
||||
public String getPosts(Model model) {
|
||||
model.addAttribute("posts",
|
||||
postService.findAllPosts().stream()
|
||||
.map(PostDto::new)
|
||||
.toList());
|
||||
model.addAttribute("users",
|
||||
userService.findAllUsers().stream()
|
||||
.map(UserDto::new)
|
||||
.toList());
|
||||
return "index";
|
||||
}
|
||||
@GetMapping("/filter")
|
||||
public String getFileteredPosts(@RequestParam(value = "searchValue") String searchValue,Model model)
|
||||
{
|
||||
model.addAttribute("posts",
|
||||
postService.getPostsAndComments(searchValue).stream()
|
||||
.map(PostDto::new)
|
||||
.toList());
|
||||
model.addAttribute("users",
|
||||
userService.findAllUsers().stream()
|
||||
.map(UserDto::new)
|
||||
.toList());
|
||||
return "index";
|
||||
}
|
||||
@GetMapping(value = {"/edit/{id}"})
|
||||
public String editPost(@PathVariable(required = false) Long id,
|
||||
Model model) {
|
||||
model.addAttribute("postId", id);
|
||||
model.addAttribute("postDto", new PostDto(postService.findPost(id)));
|
||||
return "post-edit";
|
||||
}
|
||||
|
||||
@PostMapping(value = {"/{id}"})
|
||||
public String savePost(@PathVariable(required = false) Long id,
|
||||
@RequestParam(value = "multipartFile") MultipartFile multipartFile,
|
||||
@ModelAttribute @Valid PostDto postDto,
|
||||
BindingResult bindingResult,
|
||||
Model model) throws IOException {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||
return "post-edit";
|
||||
}
|
||||
postDto.setImage("data:" + multipartFile.getContentType() + ";base64," + Base64.getEncoder().encodeToString(multipartFile.getBytes()));
|
||||
postService.updatePost(id, postDto);
|
||||
return "redirect:/user";
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{postId}")
|
||||
public String deletePost(
|
||||
@PathVariable Long postId) {
|
||||
postService.deletePost(postId);
|
||||
return "redirect:/user";
|
||||
}
|
||||
@PostMapping("/deleteComment/{postId}/{commentId}")
|
||||
public String deleteComment(@PathVariable Long postId,
|
||||
@PathVariable Long commentId,
|
||||
Principal principal,Model model) {
|
||||
Comment comment = commentService.findComment(commentId);
|
||||
if(!comment.getUser().getLogin().equals(principal.getName())){
|
||||
model.addAttribute("error", new Exception("Вы не можете удалить не ваш комментарий"));
|
||||
return "error";
|
||||
}
|
||||
postService.removeCommentFromPost(postId,commentId);
|
||||
return "redirect:/index/{postId}";
|
||||
}
|
||||
|
||||
@GetMapping("/userPosts")
|
||||
public String getUserPosts(@RequestParam(value = "userId") Long userId,Model model)
|
||||
{
|
||||
model.addAttribute("posts",
|
||||
userService.GetUserPosts(userId).stream()
|
||||
.map(PostDto::new)
|
||||
.toList());
|
||||
model.addAttribute("users",
|
||||
userService.findAllUsers().stream()
|
||||
.map(UserDto::new)
|
||||
.toList());
|
||||
return "index";
|
||||
}
|
||||
|
||||
|
||||
@GetMapping("/addComment/{postId}")
|
||||
public String showCreateCommentInfo(@PathVariable(value = "postId") Long postId, Model model) {
|
||||
model.addAttribute("postId", postId);
|
||||
model.addAttribute("commentDto", new CommentDto());
|
||||
return "comment-create.html";
|
||||
}
|
||||
@PostMapping("/createComment/{postId}")
|
||||
public String createPost(@PathVariable(value = "postId") Long postId,
|
||||
@ModelAttribute @Valid CommentDto commentDto,
|
||||
BindingResult bindingResult,
|
||||
Principal principal,
|
||||
Model model) throws IOException
|
||||
{
|
||||
Long userId = userService.findByLogin(principal.getName()).getId();
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||
return "post-create";
|
||||
}
|
||||
postService.addCommentToPost(postId,userId,commentDto.getText());
|
||||
return "redirect:/index";
|
||||
}
|
||||
|
||||
@GetMapping("/editComment/{Id}")
|
||||
public String showEditCommentInfo(@PathVariable(value = "Id") Long Id, Model model,Principal principal) throws Exception {
|
||||
model.addAttribute("Id", Id);
|
||||
CommentDto commentDto = new CommentDto(commentService.findComment(Id));
|
||||
model.addAttribute("commentDto",commentDto);
|
||||
if(!commentDto.getUser().equals(principal.getName())){
|
||||
model.addAttribute("error", new Exception("Вы не можете изменить не ваш комментарий"));
|
||||
return "error";
|
||||
}
|
||||
else
|
||||
{
|
||||
return "comment-edit";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@PostMapping("/updateComment/{Id}")
|
||||
public String updateComment(@PathVariable(value = "Id") Long Id,
|
||||
@ModelAttribute @Valid CommentDto commentDto,
|
||||
BindingResult bindingResult,
|
||||
Principal principal,
|
||||
Model model) throws IOException
|
||||
{
|
||||
Long userId = userService.findByLogin(principal.getName()).getId();
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||
return "comment-edit";
|
||||
}
|
||||
commentService.updateComment(Id,commentDto.getText());
|
||||
return "redirect:/user";
|
||||
}
|
||||
}
|
108
src/main/java/ru/ulstu/is/sbapp/Post/model/Post.java
Normal file
@ -0,0 +1,108 @@
|
||||
package ru.ulstu.is.sbapp.Post.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
public class Post {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Column
|
||||
@NotBlank(message = "heading cannot be null")
|
||||
private String heading;
|
||||
|
||||
@NotBlank(message = "content cannot be null")
|
||||
private String content;
|
||||
|
||||
@Lob
|
||||
private byte[] image;
|
||||
|
||||
@ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.MERGE)
|
||||
private User user;
|
||||
|
||||
@OneToMany(mappedBy = "post",fetch = FetchType.EAGER,cascade = {CascadeType.MERGE,CascadeType.REMOVE},orphanRemoval = true)
|
||||
private List<Comment> comments=new ArrayList<>();
|
||||
|
||||
public Post(){}
|
||||
public Post(String Heading, String Content,byte[] image)
|
||||
{
|
||||
this.heading = Heading;
|
||||
this.content = Content;
|
||||
this.image=image;
|
||||
}
|
||||
public Post(PostDto postDto) {
|
||||
this.heading = postDto.getHeading();
|
||||
this.content = postDto.getContent();
|
||||
this.image = postDto.getImage().getBytes();
|
||||
}
|
||||
public Long getId()
|
||||
{
|
||||
return id;
|
||||
}
|
||||
public String getHeading()
|
||||
{
|
||||
return heading;
|
||||
}
|
||||
public String getContent()
|
||||
{
|
||||
return content;
|
||||
}
|
||||
public void setHeading(String Heading){
|
||||
this.heading =Heading;
|
||||
}
|
||||
public void setContent(String Content)
|
||||
{
|
||||
this.content = Content;
|
||||
}
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
public User getUser()
|
||||
{
|
||||
return user;
|
||||
}
|
||||
public byte[] getImage() {
|
||||
return image;
|
||||
}
|
||||
|
||||
public void setImage(byte[] image) {
|
||||
this.image = image;
|
||||
}
|
||||
|
||||
public void deleteUser() {
|
||||
this.user = null;
|
||||
}
|
||||
public List<Comment> getComments()
|
||||
{
|
||||
return comments;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Post post = (Post) o;
|
||||
return Objects.equals(id, post.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Post{" +
|
||||
"id=" + id +
|
||||
", heading='" + heading + '\'' +
|
||||
", content ='" + content + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
78
src/main/java/ru/ulstu/is/sbapp/Post/model/PostDto.java
Normal file
@ -0,0 +1,78 @@
|
||||
package ru.ulstu.is.sbapp.Post.model;
|
||||
|
||||
import ru.ulstu.is.sbapp.Comment.model.CommentDto;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class PostDto {
|
||||
private Long id;
|
||||
|
||||
private String heading;
|
||||
|
||||
private String content;
|
||||
|
||||
private Long userId;
|
||||
private List<CommentDto> comments = new ArrayList<>();
|
||||
private String image;
|
||||
|
||||
|
||||
public PostDto(){}
|
||||
public PostDto(Post post) {
|
||||
this.id = post.getId();
|
||||
this.heading = post.getHeading();
|
||||
this.content = post.getContent();
|
||||
this.image = new String(post.getImage(), StandardCharsets.UTF_8);
|
||||
if (post.getComments() != null) {
|
||||
comments = post.getComments().stream()
|
||||
.map(CommentDto::new).toList();
|
||||
}
|
||||
userId=post.getUser().getId();
|
||||
}
|
||||
|
||||
|
||||
public Long getId()
|
||||
{
|
||||
return id;
|
||||
}
|
||||
public String getHeading()
|
||||
{
|
||||
return heading;
|
||||
}
|
||||
public String getContent()
|
||||
{
|
||||
return content;
|
||||
}
|
||||
|
||||
public Long getUserId(){return userId;}
|
||||
|
||||
public List<CommentDto> getComments()
|
||||
{
|
||||
return comments;
|
||||
}
|
||||
public String getImage() {
|
||||
return image;
|
||||
}
|
||||
|
||||
public void setHeading(String Heading)
|
||||
{
|
||||
this.heading=Heading;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public void setComments(List<CommentDto> comments) {
|
||||
this.comments = comments;
|
||||
}
|
||||
|
||||
public void setImage(String image) {
|
||||
this.image = image;
|
||||
}
|
||||
public void setUserId(Long id){this.userId=id;}
|
||||
|
||||
public void setId(Long id){this.id=id;}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package ru.ulstu.is.sbapp.Post.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface PostRepository extends JpaRepository<Post, Long>{
|
||||
@Query("Select c from Comment c where post.id = :id")
|
||||
List<Comment> getPostComments(Long id);
|
||||
|
||||
@Query("Select p from Post p join p.comments c Where p.content Like concat('%', :text, '%') or c.Text Like concat('%', :text, '%')")
|
||||
List<Post> getPostsAndComments(String text);
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ru.ulstu.is.sbapp.Post.service;
|
||||
|
||||
public class PostNotFoundException extends RuntimeException{
|
||||
public PostNotFoundException(Long id) {
|
||||
super(String.format("Post with id [%s] is not found", id));
|
||||
}
|
||||
}
|
106
src/main/java/ru/ulstu/is/sbapp/Post/service/PostService.java
Normal file
@ -0,0 +1,106 @@
|
||||
package ru.ulstu.is.sbapp.Post.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Comment.service.CommentService;
|
||||
import ru.ulstu.is.sbapp.Post.model.PostDto;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.Post.repository.PostRepository;
|
||||
import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
import ru.ulstu.is.sbapp.Util.validation.ValidatorUtil;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class PostService {
|
||||
private final PostRepository postRepository;
|
||||
private final CommentService commentService;
|
||||
private final UserService userService;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public PostService(PostRepository postRepository, CommentService commentService, ValidatorUtil validatorUtil, UserService userService)
|
||||
{
|
||||
this.postRepository=postRepository;
|
||||
this.commentService = commentService;
|
||||
this.validatorUtil=validatorUtil;
|
||||
this.userService = userService;
|
||||
}
|
||||
@Transactional
|
||||
public Post addPost(PostDto postDto) {
|
||||
final Post post = new Post(postDto);
|
||||
validatorUtil.validate(post);
|
||||
return postRepository.save(post);
|
||||
}
|
||||
|
||||
|
||||
@Transactional
|
||||
public void savePost(Post post) {
|
||||
postRepository.save(post);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Post findPost(Long id) {
|
||||
final Optional<Post> post = postRepository.findById(id);
|
||||
return post.orElseThrow(() -> new PostNotFoundException(id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<Post> findAllPosts() {
|
||||
return postRepository.findAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Post updatePost(Long id, PostDto postDto) {
|
||||
final Post currentPost = findPost(id);
|
||||
currentPost.setHeading(postDto.getHeading());
|
||||
currentPost.setContent(postDto.getContent());
|
||||
currentPost.setImage(postDto.getImage().getBytes(StandardCharsets.UTF_8));
|
||||
validatorUtil.validate(currentPost);
|
||||
return postRepository.save(currentPost);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<Comment> GetPostComments(Long id)
|
||||
{
|
||||
return postRepository.getPostComments(id);
|
||||
}
|
||||
@Transactional
|
||||
public void deletePost(Long id) {
|
||||
postRepository.deleteById(id);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAllPosts() {
|
||||
commentService.deleteAllComments();
|
||||
postRepository.deleteAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void addCommentToPost(Long id, Long userId, String text){
|
||||
Optional<Post> optionalPost = postRepository.findById(id);
|
||||
if(optionalPost.isPresent()) {
|
||||
Comment comment = new Comment(text);
|
||||
comment.setPost(optionalPost.get(), userService.findUser(userId));
|
||||
commentService.saveComment(comment);
|
||||
}
|
||||
postRepository.save(optionalPost.get());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void removeCommentFromPost(Long id, Long commentId){
|
||||
Comment optionalComment = commentService.findComment(commentId);
|
||||
optionalComment.setPost(null, null);
|
||||
Optional <Post> postOptional = postRepository.findById(id);
|
||||
postOptional.get().getComments().remove(optionalComment);
|
||||
commentService.deleteComment(commentId);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<Post> getPostsAndComments(String text)
|
||||
{
|
||||
return postRepository.getPostsAndComments(text);
|
||||
}
|
||||
}
|
@ -2,20 +2,10 @@ 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
|
||||
@RestController
|
||||
public class SbappApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SbappApplication.class, args);
|
||||
}
|
||||
@GetMapping("/String")
|
||||
public String Vvod(@RequestParam(value = "str", defaultValue = "none") String str) {
|
||||
return String.format("Вы ввели %s!", str);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,67 @@
|
||||
package ru.ulstu.is.sbapp.User.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.ulstu.is.sbapp.Post.model.PostDto;
|
||||
import ru.ulstu.is.sbapp.User.model.UserDto;
|
||||
import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
import ru.ulstu.is.sbapp.Configuration.WebConfiguration;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(WebConfiguration.REST_API + "/user")
|
||||
public class UserController {
|
||||
private final UserService userService;
|
||||
public UserController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
@GetMapping("/{id}")
|
||||
public UserDto getUser(@PathVariable Long id) {
|
||||
return new UserDto(userService.findUser(id));
|
||||
}
|
||||
@GetMapping
|
||||
public List<UserDto> getUsers() {
|
||||
return userService.findAllUsers().stream()
|
||||
.map(UserDto::new)
|
||||
.toList();
|
||||
}
|
||||
@GetMapping("/{id}/posts")
|
||||
public List<PostDto> getPosts(@PathVariable Long id) {
|
||||
return userService.GetUserPosts(id).stream()
|
||||
.map(PostDto::new)
|
||||
.toList();
|
||||
}
|
||||
@PostMapping
|
||||
public UserDto createUser(@RequestParam("firstName") String firstName,
|
||||
@RequestParam("lastName") String lastname,
|
||||
@RequestParam("email") String email,
|
||||
@RequestParam("password") String password){
|
||||
return new UserDto(userService.addUser(firstName, lastname,email,password));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public UserDto updateClient(@PathVariable Long id,
|
||||
@RequestParam("firstName") String login,
|
||||
@RequestParam("email") String email,
|
||||
@RequestParam("password") String password){
|
||||
return new UserDto(userService.updateUser(id, login,email,password));
|
||||
}
|
||||
@PostMapping("/{id}/Post")
|
||||
public void addPost(@PathVariable Long id,
|
||||
@RequestBody @Valid PostDto postDto) {
|
||||
userService.addNewPost(id, postDto);
|
||||
}
|
||||
@DeleteMapping("/{id}/Post/{postId}")
|
||||
public void removePost(@PathVariable Long id,
|
||||
@PathVariable Long postId)
|
||||
{
|
||||
userService.deletePost(id,postId);
|
||||
}
|
||||
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public void deleteUser(@PathVariable Long id) {
|
||||
userService.deleteUser(id);
|
||||
}
|
||||
}
|
@ -0,0 +1,117 @@
|
||||
package ru.ulstu.is.sbapp.User.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.ValidationException;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import ru.ulstu.is.sbapp.Comment.model.CommentDto;
|
||||
import ru.ulstu.is.sbapp.Post.model.PostDto;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
import ru.ulstu.is.sbapp.User.model.UserDto;
|
||||
import ru.ulstu.is.sbapp.User.model.UserRole;
|
||||
import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.Principal;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/user")
|
||||
public class UserMvcController {
|
||||
private final UserService userService;
|
||||
public UserMvcController(UserService userService)
|
||||
{
|
||||
this.userService=userService;
|
||||
}
|
||||
@GetMapping(value = "/all")
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public String getUsers(@RequestParam(defaultValue = "1") int page,
|
||||
@RequestParam(defaultValue = "5") int size,
|
||||
Principal principal, Model model) {
|
||||
final Page<UserDto> users = userService.findAllPages(page, size)
|
||||
.map(UserDto::new);
|
||||
model.addAttribute("users", users);
|
||||
final int totalPages = users.getTotalPages();
|
||||
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
|
||||
.boxed()
|
||||
.toList();
|
||||
model.addAttribute("pages", pageNumbers);
|
||||
model.addAttribute("totalPages", totalPages);
|
||||
return "users";
|
||||
}
|
||||
@GetMapping
|
||||
public String showUpdateUserForm(Principal principal, Model model) {
|
||||
UserDto userDto = new UserDto(userService.findByLogin(principal.getName()));
|
||||
Long id = userService.findByLogin(principal.getName()).getId();
|
||||
model.addAttribute("userId",id);
|
||||
model.addAttribute("userDto", userDto);
|
||||
model.addAttribute("posts",userService.GetUserPosts(id).stream()
|
||||
.map(PostDto::new)
|
||||
.toList());
|
||||
return "user";
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public String updateUser(@ModelAttribute @Valid UserDto userDto,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||
return "user";
|
||||
}
|
||||
try {
|
||||
userService.updateUser(userDto);
|
||||
@SuppressWarnings("unchecked")
|
||||
Collection<SimpleGrantedAuthority> nowAuthorities =
|
||||
(Collection<SimpleGrantedAuthority>)SecurityContextHolder.getContext()
|
||||
.getAuthentication()
|
||||
.getAuthorities();
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(userDto.getLogin(), userDto.getPassword(), nowAuthorities);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
} catch (ValidationException e) {
|
||||
model.addAttribute("errors", e.getMessage());
|
||||
}
|
||||
return "user";
|
||||
}
|
||||
|
||||
@GetMapping("/post")
|
||||
public String showCreatePostInfo(Principal principal, Model model) {
|
||||
Long id = userService.findByLogin(principal.getName()).getId();
|
||||
model.addAttribute("userId",id);
|
||||
model.addAttribute("postDto", new PostDto());
|
||||
return "post-create";
|
||||
}
|
||||
@PostMapping("/createPost/{userId}")
|
||||
public String createPost(@PathVariable(value = "userId") Long id,
|
||||
@ModelAttribute @Valid PostDto postDto,
|
||||
@RequestParam(value = "multipartFile") MultipartFile multipartFile,
|
||||
BindingResult bindingResult,
|
||||
Model model) throws IOException
|
||||
{
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||
return "post-create";
|
||||
}
|
||||
postDto.setImage("data:" + multipartFile.getContentType() + ";base64," + Base64.getEncoder().encodeToString(multipartFile.getBytes()));
|
||||
userService.addNewPost(id,postDto);
|
||||
return "redirect:/user";
|
||||
}
|
||||
@PostMapping("/delete/{id}")
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public String deleteUser(@PathVariable Long id) {
|
||||
userService.deleteUser(id);
|
||||
return "redirect:/user";
|
||||
}
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package ru.ulstu.is.sbapp.User.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.ValidationException;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
import ru.ulstu.is.sbapp.User.model.UserRole;
|
||||
import ru.ulstu.is.sbapp.User.model.UserSignupDto;
|
||||
import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(UserSignupMvcController.SIGNUP_URL)
|
||||
public class UserSignupMvcController
|
||||
{
|
||||
public static final String SIGNUP_URL = "/signup";
|
||||
private final UserService userService;
|
||||
|
||||
public UserSignupMvcController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String showSignupForm(Model model) {
|
||||
model.addAttribute("userDto", new UserSignupDto());
|
||||
return "signup";
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public String signup(@ModelAttribute("userDto") @Valid UserSignupDto userSignupDto,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||
return "signup";
|
||||
}
|
||||
try {
|
||||
final User user = userService.addUser(userSignupDto.getLogin(),userSignupDto.getEmail(),
|
||||
userSignupDto.getPassword(), userSignupDto.getPasswordConfirm(), UserRole.USER);
|
||||
return "redirect:/login?created=" + user.getLogin();
|
||||
} catch (ValidationException e) {
|
||||
model.addAttribute("errors", e.getMessage());
|
||||
return "signup";
|
||||
}
|
||||
}
|
||||
}
|
127
src/main/java/ru/ulstu/is/sbapp/User/model/User.java
Normal file
@ -0,0 +1,127 @@
|
||||
package ru.ulstu.is.sbapp.User.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Table(name="tab_user")
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
@NotBlank(message = "Login can't be null or empty")
|
||||
@Size(min = 3, max = 64, message = "Incorrect login length")
|
||||
private String login;
|
||||
|
||||
@NotBlank(message = "email cannot be null")
|
||||
@Pattern(regexp = "^(.+)@(\\S+)$", message = "Incorrect email value")
|
||||
private String email;
|
||||
|
||||
@Column(nullable = false, length = 64)
|
||||
@NotBlank
|
||||
@Size(min = 6, max = 64)
|
||||
private String password;
|
||||
|
||||
private UserRole role;
|
||||
|
||||
@OneToMany(mappedBy ="user",cascade = {CascadeType.MERGE,CascadeType.REMOVE},fetch = FetchType.EAGER)
|
||||
private List<Post> posts =new ArrayList<>();
|
||||
|
||||
@OneToMany(mappedBy ="user",cascade = {CascadeType.MERGE,CascadeType.REMOVE},fetch = FetchType.EAGER)
|
||||
private List<Comment> comments =new ArrayList<>();
|
||||
|
||||
public User() {
|
||||
}
|
||||
public User(String login,String email, String password) {
|
||||
this(login,email, password, UserRole.USER);
|
||||
}
|
||||
public User(String login,String email,String password,UserRole role) {
|
||||
this.login=login;
|
||||
this.email=email;
|
||||
this.password=password;
|
||||
this.role=role;
|
||||
}
|
||||
public User(UserSignupDto userSignupDto) {
|
||||
this.login = userSignupDto.getLogin();
|
||||
this.email = userSignupDto.getEmail();
|
||||
this.password = userSignupDto.getPassword();
|
||||
this.role = UserRole.USER;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public List<Post> getPosts()
|
||||
{
|
||||
return posts;
|
||||
}
|
||||
public List<Comment> getComments()
|
||||
{
|
||||
return comments;
|
||||
}
|
||||
public void addNewPost(Post post) {
|
||||
posts.add(post);
|
||||
post.setUser(this);
|
||||
}
|
||||
|
||||
public String getEmail()
|
||||
{
|
||||
return email;
|
||||
}
|
||||
public void setEmail(String email){
|
||||
this.email=email;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Client{" +
|
||||
"id=" + id +
|
||||
", login='" + login + '\'' +
|
||||
", email='" + email + '\'' +
|
||||
", password='" + password + '\'' +
|
||||
", posts=" + posts +'\''+
|
||||
'}';
|
||||
}
|
||||
|
||||
}
|
86
src/main/java/ru/ulstu/is/sbapp/User/model/UserDto.java
Normal file
@ -0,0 +1,86 @@
|
||||
package ru.ulstu.is.sbapp.User.model;
|
||||
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class UserDto {
|
||||
private Long id;
|
||||
|
||||
private String login;
|
||||
|
||||
private String email;
|
||||
|
||||
private UserRole role;
|
||||
|
||||
private String password;
|
||||
|
||||
private List<Post> posts = new ArrayList<>();
|
||||
|
||||
private List<Comment> comments = new ArrayList<>();
|
||||
|
||||
public UserDto(){}
|
||||
public UserDto(User user) {
|
||||
this.id=user.getId();
|
||||
this.login = user.getLogin();
|
||||
this.email= user.getEmail();
|
||||
this.role=user.getRole();
|
||||
this.password=user.getPassword();
|
||||
}
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public String getPassword(){
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public List<Post> getPosts()
|
||||
{
|
||||
return posts;
|
||||
}
|
||||
public List<Comment> getComments()
|
||||
{
|
||||
return comments;
|
||||
}
|
||||
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
public String getEmail()
|
||||
{
|
||||
return email;
|
||||
}
|
||||
public void setEmail(String email)
|
||||
{
|
||||
this.email=email;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
|
||||
public void setComments(List<Comment> comments) {
|
||||
this.comments = comments;
|
||||
}
|
||||
|
||||
public void setPosts(List<Post> posts) {
|
||||
this.posts = posts;
|
||||
}
|
||||
}
|
20
src/main/java/ru/ulstu/is/sbapp/User/model/UserRole.java
Normal file
@ -0,0 +1,20 @@
|
||||
package ru.ulstu.is.sbapp.User.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";
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package ru.ulstu.is.sbapp.User.model;
|
||||
|
||||
public class UserSignupDto {
|
||||
private String login;
|
||||
private String email;
|
||||
private String password;
|
||||
private String passwordConfirm;
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package ru.ulstu.is.sbapp.User.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
@Query("Select p from Post p where user.id = :id")
|
||||
List<Post> getUsersPosts(Long id);
|
||||
|
||||
User findOneByLoginIgnoreCase(String login);
|
||||
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ru.ulstu.is.sbapp.User.service;
|
||||
|
||||
public class UserNotFoundException extends RuntimeException{
|
||||
public UserNotFoundException(Long id) {
|
||||
super(String.format("User with id [%s] is not found", id));
|
||||
}
|
||||
}
|
164
src/main/java/ru/ulstu/is/sbapp/User/service/UserService.java
Normal file
@ -0,0 +1,164 @@
|
||||
package ru.ulstu.is.sbapp.User.service;
|
||||
|
||||
import jakarta.validation.ValidationException;
|
||||
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.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.ulstu.is.sbapp.Comment.service.CommentService;
|
||||
import ru.ulstu.is.sbapp.Post.model.PostDto;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.Post.repository.PostRepository;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import ru.ulstu.is.sbapp.User.model.UserDto;
|
||||
import ru.ulstu.is.sbapp.User.model.UserRole;
|
||||
import ru.ulstu.is.sbapp.User.model.UserSignupDto;
|
||||
import ru.ulstu.is.sbapp.User.repository.UserRepository;
|
||||
import ru.ulstu.is.sbapp.Util.validation.ValidatorUtil;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class UserService implements UserDetailsService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
private final PostRepository postRepository;
|
||||
|
||||
private final CommentService commentService;
|
||||
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public UserService(UserRepository userRepository, ValidatorUtil validatorUtil, PostRepository postRepository, CommentService commentService,PasswordEncoder passwordEncoder)
|
||||
{
|
||||
this.userRepository=userRepository;
|
||||
this.validatorUtil=validatorUtil;
|
||||
this.postRepository = postRepository;
|
||||
this.commentService = commentService;
|
||||
this.passwordEncoder=passwordEncoder;
|
||||
}
|
||||
public User findByLogin(String login) {
|
||||
return userRepository.findOneByLoginIgnoreCase(login);
|
||||
}
|
||||
public Page<User> findAllPages(int page, int size) {
|
||||
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
|
||||
}
|
||||
public User addUser(String firstName, String lastName, String email, String password) {
|
||||
return addUser(firstName,lastName, email, password, UserRole.USER);
|
||||
}
|
||||
@Transactional
|
||||
public User addUser(String login, String email, String password,String passwordConfirm, UserRole role) {
|
||||
if (findByLogin(login) != null) {
|
||||
throw new ValidationException(String.format("User '%s' already exists", login));
|
||||
}
|
||||
if (!Objects.equals(password, passwordConfirm)) {
|
||||
throw new ValidationException("Passwords not equals");
|
||||
}
|
||||
final User user = new User(login,email,passwordEncoder.encode(password),role);
|
||||
validatorUtil.validate(user);
|
||||
return userRepository.save(user);
|
||||
}
|
||||
@Transactional
|
||||
public User addUser(UserSignupDto userSignupDto) {
|
||||
if (findByLogin(userSignupDto.getLogin()) != null) {
|
||||
throw new ValidationException(String.format("User '%s' already exists", userSignupDto.getLogin()));
|
||||
}
|
||||
if (!Objects.equals(userSignupDto.getPassword(), userSignupDto.getPasswordConfirm())) {
|
||||
throw new ValidationException("Passwords not equals");
|
||||
}
|
||||
final User user = new User(userSignupDto);
|
||||
validatorUtil.validate(user);
|
||||
return userRepository.save(user);
|
||||
}
|
||||
|
||||
|
||||
@Transactional
|
||||
public User findUser(Long id) {
|
||||
final Optional<User> user = userRepository.findById(id);
|
||||
return user.orElseThrow(() -> new UserNotFoundException(id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<User> findAllUsers() {
|
||||
return userRepository.findAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public User updateUser(Long id, String firstName, String email,String password) {
|
||||
final User currentUser = findUser(id);
|
||||
currentUser.setLogin(firstName);
|
||||
currentUser.setEmail(email);
|
||||
currentUser.setPassword(password);
|
||||
validatorUtil.validate(currentUser);
|
||||
return userRepository.save(currentUser);
|
||||
}
|
||||
@Transactional
|
||||
public User updateUser(UserDto userDto) {
|
||||
final User currentUser = findUser(userDto.getId());
|
||||
final User sameUser = findByLogin(userDto.getLogin());
|
||||
if (sameUser != null && !Objects.equals(sameUser.getId(), currentUser.getId())) {
|
||||
throw new ValidationException(String.format("User '%s' already exists", userDto.getLogin()));
|
||||
}
|
||||
if (!passwordEncoder.matches(userDto.getPassword(), currentUser.getPassword())) {
|
||||
throw new ValidationException("Incorrect password");
|
||||
}
|
||||
currentUser.setLogin(userDto.getLogin());
|
||||
currentUser.setEmail(userDto.getEmail());
|
||||
validatorUtil.validate(currentUser);
|
||||
return userRepository.save(currentUser);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteUser(Long id) {
|
||||
userRepository.deleteById(id);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void addNewPost(Long id, PostDto postDto)
|
||||
{
|
||||
Optional<User> currentUser = userRepository.findById(id);
|
||||
if(currentUser.isPresent())
|
||||
{
|
||||
Post post = new Post(postDto);
|
||||
post.setUser(currentUser.get());
|
||||
postRepository.save(post);
|
||||
}
|
||||
}
|
||||
@Transactional
|
||||
public void deleteAllUsers() {
|
||||
commentService.deleteAllComments();
|
||||
userRepository.deleteAll();
|
||||
}
|
||||
|
||||
|
||||
@Transactional
|
||||
public List<Post> GetUserPosts(Long id)
|
||||
{
|
||||
return userRepository.getUsersPosts(id);
|
||||
}
|
||||
|
||||
|
||||
@Transactional
|
||||
public void deletePost(Long id, Long postId) {
|
||||
postRepository.deleteById(postId);
|
||||
}
|
||||
|
||||
@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()));
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package ru.ulstu.is.sbapp.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.Comment.service.CommentNotFoundException;
|
||||
import ru.ulstu.is.sbapp.Post.service.PostNotFoundException;
|
||||
import ru.ulstu.is.sbapp.User.service.UserNotFoundException;
|
||||
import ru.ulstu.is.sbapp.Util.validation.ValidationException;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/*@ControllerAdvice*/
|
||||
public class AdviceController {
|
||||
@ExceptionHandler({
|
||||
CommentNotFoundException.class,
|
||||
UserNotFoundException.class,
|
||||
PostNotFoundException.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);
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package ru.ulstu.is.sbapp.Util.validation;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class ValidationException extends RuntimeException {
|
||||
public ValidationException(Set<String> errors) {
|
||||
super(String.join("\n", errors));
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package ru.ulstu.is.sbapp.Util.validation;
|
||||
|
||||
import jakarta.validation.ConstraintViolation;
|
||||
import jakarta.validation.Validation;
|
||||
import jakarta.validation.Validator;
|
||||
import jakarta.validation.ValidatorFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class ValidatorUtil {
|
||||
private final Validator validator;
|
||||
|
||||
public ValidatorUtil() {
|
||||
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
|
||||
this.validator = factory.getValidator();
|
||||
}
|
||||
}
|
||||
|
||||
public <T> void validate(T object) {
|
||||
final Set<ConstraintViolation<T>> errors = validator.validate(object);
|
||||
if (!errors.isEmpty()) {
|
||||
throw new ValidationException(errors.stream()
|
||||
.map(ConstraintViolation::getMessage)
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
}
|
||||
}
|
@ -1,13 +0,0 @@
|
||||
package ru.ulstu.is.sbapp;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry)
|
||||
{
|
||||
registry.addMapping("/**").allowedMethods("*");
|
||||
}
|
||||
}
|
@ -1 +1,11 @@
|
||||
|
||||
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
|
||||
|
146
src/main/resources/public/css/style.css
Normal file
@ -0,0 +1,146 @@
|
||||
html
|
||||
{
|
||||
min-height: 100vh;
|
||||
}
|
||||
header .img-fluid
|
||||
{
|
||||
width:232px;
|
||||
height:100px;
|
||||
}
|
||||
|
||||
article .img-fluid
|
||||
{
|
||||
height:250px;
|
||||
}
|
||||
article .img-fluid1
|
||||
{
|
||||
height:100%;
|
||||
width: 96%;
|
||||
}
|
||||
.owl
|
||||
{
|
||||
width:300px;
|
||||
}
|
||||
.pdf-size
|
||||
{
|
||||
width:70px;
|
||||
}
|
||||
body
|
||||
{
|
||||
min-height: 100vh;
|
||||
}
|
||||
.body_app
|
||||
{
|
||||
display: grid;
|
||||
grid-template-rows:auto 1fr auto;
|
||||
min-height: 100vh;
|
||||
}
|
||||
.lp
|
||||
{
|
||||
padding-left: 30px;
|
||||
}
|
||||
.img-school
|
||||
{
|
||||
margin-right: 1em;
|
||||
float: start;
|
||||
|
||||
}
|
||||
.Vnov
|
||||
{
|
||||
margin-right: 1em;
|
||||
}
|
||||
.Vnov1
|
||||
{
|
||||
margin-right: 1em;
|
||||
}
|
||||
.Cont
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 800px) {
|
||||
.owl {
|
||||
display:none;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 1164px) {
|
||||
.img-school
|
||||
{
|
||||
margin-right: 170px;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 554px) {
|
||||
.img-school
|
||||
{
|
||||
height: 20% !important;
|
||||
width: 75%;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 727px) {
|
||||
.headers-problem
|
||||
{
|
||||
|
||||
flex-direction: column;
|
||||
}
|
||||
.navbar
|
||||
{
|
||||
align-items: flex-start !important;
|
||||
}
|
||||
|
||||
}
|
||||
@media only screen and (max-width: 959px) {
|
||||
.navbar
|
||||
{
|
||||
float:left !important;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 463px) {
|
||||
.Vnov
|
||||
{
|
||||
margin-right: 140px;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 575px) {
|
||||
.Vnov1
|
||||
{
|
||||
margin-right: 200px;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 585px) {
|
||||
.Cont
|
||||
{
|
||||
margin-right: 200px;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#banner {
|
||||
margin: 15px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
#banner img {
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
#banner img.show {
|
||||
height: 40%;
|
||||
width: 60%;
|
||||
opacity: 1;
|
||||
transition: opacity 1s, visibility 0s;
|
||||
}
|
||||
|
||||
#banner img.hide {
|
||||
height: 0;
|
||||
width: 0;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: opacity 1s, visibility 0s 1s;
|
||||
}
|
||||
|
||||
.Pole_height
|
||||
{
|
||||
height: 80px;
|
||||
}
|
1
src/main/resources/public/favicon.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M96 0C43 0 0 43 0 96V416c0 53 43 96 96 96H384h32c17.7 0 32-14.3 32-32s-14.3-32-32-32V384c17.7 0 32-14.3 32-32V32c0-17.7-14.3-32-32-32H384 96zm0 384H352v64H96c-17.7 0-32-14.3-32-32s14.3-32 32-32zm32-240c0-8.8 7.2-16 16-16H336c8.8 0 16 7.2 16 16s-7.2 16-16 16H144c-8.8 0-16-7.2-16-16zm16 48H336c8.8 0 16 7.2 16 16s-7.2 16-16 16H144c-8.8 0-16-7.2-16-16s7.2-16 16-16z"/></svg>
|
After Width: | Height: | Size: 611 B |
BIN
src/main/resources/public/img/Emblema.png
Normal file
After Width: | Height: | Size: 77 KiB |
27
src/main/resources/templates/comment-create.html
Normal file
@ -0,0 +1,27 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="mx-auto my-3">
|
||||
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
|
||||
<form action="#" th:action="@{'/index/createComment/' + ${postId}}" th:object="${commentDto}" method="post">
|
||||
<div class="mb-3">
|
||||
<div>
|
||||
<input class="form-control" id="commentText" th:field="${commentDto.text}" type="text" defaultValue="" required/>
|
||||
</div>
|
||||
<div>
|
||||
<button type="submit" class="btn btn-primary button-fixed">
|
||||
Добавить
|
||||
</button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
27
src/main/resources/templates/comment-edit.html
Normal file
@ -0,0 +1,27 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="mx-auto my-3">
|
||||
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
|
||||
<form action="#" th:action="@{/index/updateComment/{Id}(Id=${Id})}" th:object="${commentDto}" method="post">
|
||||
<div class="mb-3">
|
||||
<div>
|
||||
<input class="form-control" id="commentText" th:field="${commentDto.text}" type="text" defaultValue="" required/>
|
||||
</div>
|
||||
<div>
|
||||
<button type="submit" class="btn btn-primary button-fixed">
|
||||
Обновить
|
||||
</button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
53
src/main/resources/templates/default.html
Normal file
@ -0,0 +1,53 @@
|
||||
<html lang="ru"
|
||||
xmlns:th="http://www.thymeleaf.org"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:sec="">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<title>Школа</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<link rel="icon" href="/favicon.svg">
|
||||
<script type="text/javascript" src="/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
|
||||
<link rel="stylesheet" href="/webjars/bootstrap/5.1.3/css/bootstrap.min.css"/>
|
||||
<link rel="stylesheet" href="/webjars/font-awesome/6.1.0/css/all.min.css"/>
|
||||
<link rel="stylesheet" href="/css/style.css"/>
|
||||
</head>
|
||||
|
||||
<body class="body_app">
|
||||
<header class="fs-4 fw-bold p-1 text-white bg-primary bg-gradient">
|
||||
<div><img class="img-fluid float-start" src="/img/Emblema.png" alt="Emblema"/>
|
||||
<p class="fs-5 Cont">Муниципальное бюджетное общеобразовательное учреждение средняя общеобразовательная школа №10</p>
|
||||
</div>
|
||||
<nav class="navbar navbar-expand-md navbar-dark" sec:authorize="isAuthenticated()">
|
||||
<div class="container-fluid">
|
||||
<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 className="navbar-toggler-icon"></span></button>
|
||||
<nav class="headers-problem navbar navbar-expand-lg d-flex">
|
||||
<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">
|
||||
<a class="btn btn-outline-light mx-1" href="/user/all" sec:authorize="hasRole('ROLE_ADMIN')"
|
||||
th:classappend="${#strings.equals(activeLink, '/user')} ? 'active' : ''">
|
||||
Пользователи
|
||||
</a>
|
||||
<a class="btn btn-outline-light mx-1" href="/user"
|
||||
th:classappend="${#strings.equals(activeLink, '/user')} ? 'active' : ''">
|
||||
Профиль
|
||||
</a>
|
||||
<a class="btn btn-outline-light mx-1" href="/index">Новости</a>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="d-flex text-white bg-info bg-gradient fw-bold">
|
||||
<div class="container container-padding" layout:fragment="content">
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<th:block layout:fragment="scripts">
|
||||
</th:block>
|
||||
</html>
|
13
src/main/resources/templates/error.html
Normal file
@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div><span th:text="${error}"></span></div>
|
||||
<a href="/index">На главную</a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
79
src/main/resources/templates/index.html
Normal file
@ -0,0 +1,79 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<script type="text/javascript" src="/webjars/jquery/3.6.0/jquery.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div layout:fragment="content">
|
||||
<div class="d-flex float-start my-1">
|
||||
<form th:action="@{/index/filter}" class="d-flex">
|
||||
<div class="mx-3"><input type="text" th:name="searchValue" id="search" class="form-control" required /></div>
|
||||
<button type="submit" class="btn btn-outline-primary text-center mx-2">
|
||||
<i class="fa-solid fa-magnifying-glass"></i>
|
||||
</button>
|
||||
</form>
|
||||
<form th:action="@{/index/userPosts}" id="myForm" class="d-flex">
|
||||
<div class="mx-3">
|
||||
<select id="selectBox" th:name="userId">
|
||||
<option value="" disabled selected>Select your option</option>
|
||||
<option th:each="value: ${users}" th:selected="${selectBox} == ${value}" th:text="${value.login}" th:value="${value.Id}">
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="my-5">
|
||||
<!--здесь тоже надо сделать нормальный вывод-->
|
||||
<div class="container-fluid">
|
||||
<div th:each="post, iterator: ${posts}" class="card border-dark mb-3 d-flex flex-row text-black justify-content-between">
|
||||
<div>
|
||||
<img class="col" style="width:300px;height:200px" th:src="${post.image}"/>
|
||||
</div>
|
||||
<div class="d-flex flex-grow-1 flex-column">
|
||||
<div class="flex-grow-1 mx-2">
|
||||
<h th:text="${post.heading}"></h>
|
||||
</div>
|
||||
<div class="flex-grow-1 mx-2">
|
||||
<p th:text="${post.content}"></p>
|
||||
</div>
|
||||
<div class="flex-grow-1 mx-2">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">#</th>
|
||||
<th scope="col">Пользователь</th>
|
||||
<th scope="col">Текст</th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr th:each="comment, iterator: ${post.comments}">
|
||||
<th scope="row" th:text="${iterator.index} + 1"/>
|
||||
<td th:text="${comment.user}" style="width: 60%"/>
|
||||
<td th:text="${comment.text}" style="width: 60%"/>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="d-flex flex-row justify-content-end ">
|
||||
<a th:href=@{/index/{id}(id=${post.id})} class='btn btn-outline-primary mx-2'><i class="fa-solid fa-envelopes-bulk"></i></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<th:block layout:fragment="scripts">
|
||||
<script>
|
||||
$(document).ready(function() {
|
||||
$('#selectBox').on('change', function() {
|
||||
this.form.submit();
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</th:block>
|
||||
</html>
|
41
src/main/resources/templates/login.html
Normal file
@ -0,0 +1,41 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div th:if="${param.error}" class="alert alert-danger margin-bottom">
|
||||
User not found
|
||||
</div>
|
||||
<div th:if="${param.logout}" class="alert alert-success margin-bottom">
|
||||
Logout success
|
||||
</div>
|
||||
<div th:if="${param.created}" class="alert alert-success margin-bottom">
|
||||
User '<span th:text="${param.created}"></span>' was successfully created
|
||||
</div>
|
||||
<form th:action="@{/login}" method="post">
|
||||
<div class="mb-3">
|
||||
<p class="mb-1">Login</p>
|
||||
<input name="username" id="username" class="form-control"
|
||||
type="text" required autofocus />
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<p class="mb-1">Password</p>
|
||||
<input name="password" id="password" class="form-control"
|
||||
type="password" required />
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<button type="submit" class="btn btn-success">
|
||||
Sing in
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
<p>
|
||||
<span>Not a member yet?</span>
|
||||
<a href="/signup">Sing Up here</a>
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
34
src/main/resources/templates/post-create.html
Normal file
@ -0,0 +1,34 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
|
||||
<form action="#" th:action="@{/user/createPost/{userId}(userId=${userId})}" th:object="${postDto}" method="post" enctype="multipart/form-data">
|
||||
<div class="mb-3">
|
||||
<label for="image" class="form-label">Картинка</label>
|
||||
<input type="file" th:name="multipartFile" class="form-control" id="image" required="true">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="heading" class="form-label">Заголовок</label>
|
||||
<input type="text" class="form-control" id="heading" th:field="${postDto.heading}" required="true">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="content" class="form-label">Содержание</label>
|
||||
<input type="text" class="form-control" id="content" th:field="${postDto.content}" required="true">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<button type="submit" class="btn btn-primary button-fixed">
|
||||
<span>Добавить</span>
|
||||
</button>
|
||||
<a class="btn btn-secondary button-fixed" th:href="@{/post}">
|
||||
Назад
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
34
src/main/resources/templates/post-edit.html
Normal file
@ -0,0 +1,34 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
|
||||
<form action="#" th:action="@{/index/{id}(id=${id})}" th:object="${postDto}" method="post" enctype="multipart/form-data">
|
||||
<div class="mb-3">
|
||||
<label for="image" class="form-label">Картинка</label>
|
||||
<input type="file" th:name="multipartFile" class="form-control" id="image" required="true">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="heading" class="form-label">Заголовок</label>
|
||||
<input type="text" class="form-control" id="heading" th:field="${postDto.heading}" required="true">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="content" class="form-label">Содержание</label>
|
||||
<input type="text" class="form-control" id="content" th:field="${postDto.content}" required="true">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<button type="submit" class="btn btn-primary button-fixed">
|
||||
<span th:if="${id != null}">Обновить</span>
|
||||
</button>
|
||||
<a class="btn btn-secondary button-fixed" th:href="@{/post}">
|
||||
Назад
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
68
src/main/resources/templates/post-page.html
Normal file
@ -0,0 +1,68 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div layout:fragment="content">
|
||||
<div class="da d-flex my-2">
|
||||
<div><img class="imga img-fluid float-start mx-2" style="width:500px;height:300px" th:src="${post.image}"/></div>
|
||||
<div class="container-fluid my-2 mx-1">
|
||||
<h1 th:text="${post.heading}"></h1>
|
||||
<p>[[${post.content}]]</p>
|
||||
</div>
|
||||
</div>
|
||||
<!--Вот тут кнопка для добавления комментариев (для будущего тебя)-->
|
||||
<a class="btn btn-outline-primary text-center mx-2"
|
||||
th:href="@{/index/addComment/{postId}(postId=${post.id})}">
|
||||
+
|
||||
</a>
|
||||
<div className="d-flex mx-2">
|
||||
<div class="table-responsive">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">#</th>
|
||||
<th scope="col">Пользователь</th>
|
||||
<th scope="col">Содержимое</th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr th:each="comment, iterator: ${comments}">
|
||||
<th scope="row" th:text="${iterator.index} + 1"/>
|
||||
<td th:text="${comment.user}" style="width: 60%"/>
|
||||
<td th:text="${comment.text}" style="width: 60%"/>
|
||||
<td style="width: 10%">
|
||||
<div class="btn-group" role="group" aria-label="Basic example">
|
||||
<!--НУЖНО СДЕЛАТЬ!!!-->
|
||||
<a class="btn btn-outline-light text-center mx-2" th:href="@{/index/editComment/{Id}(Id=${comment.id})}">
|
||||
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
|
||||
</a>
|
||||
<button type="button" class="btn btn-outline-light text-center mx-2"
|
||||
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${comment.id}').click()|">
|
||||
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
|
||||
</button>
|
||||
</div>
|
||||
<form th:action="@{'/index/deleteComment/' + ${comment.postId} + '/' + ${comment.id}}" method="post">
|
||||
<button th:id="'remove-' + ${comment.id}" type="submit" style="display: none">
|
||||
Удалить
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<th:block layout:fragment="scripts">
|
||||
<script>
|
||||
|
||||
</script>
|
||||
</th:block>
|
||||
</html>
|
43
src/main/resources/templates/signup.html
Normal file
@ -0,0 +1,43 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div th:if="${errors}" th:text="${errors}" class="margin-bottom alert alert-danger"></div>
|
||||
<form action="#" th:action="@{/signup}" th:object="${userDto}" method="post">
|
||||
<div class="mb-3">
|
||||
<label for="login" class="mb-1">Login</label>
|
||||
<input id="login" th:field="${userDto.login}" class="form-control"
|
||||
type="text" required maxlength="64" />
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="email" class="mb-1">Email</label>
|
||||
<input id="email" th:field="${userDto.email}" class="form-control"
|
||||
type="text" required />
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="password" class="mb-1">Password</label>
|
||||
<input id="password" th:field="${userDto.password}" class="form-control"
|
||||
type="password" required minlength="3" maxlength="64" />
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="passwordConfirm" class="mb-1">Confirm Password</label>
|
||||
<input id="passwordConfirm" th:field="${userDto.passwordConfirm}" class="form-control"
|
||||
type="password" required minlength="3" maxlength="64" />
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<button type="submit" class="btn btn-success">
|
||||
Create account
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
<p>
|
||||
<span>Already have an account?</span>
|
||||
<a href="/login">Sing In here</a>
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
108
src/main/resources/templates/user.html
Normal file
@ -0,0 +1,108 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}"
|
||||
xmlns:th="http://www.w3.org/1999/xhtml">
|
||||
|
||||
<head>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="border-bottom pb-3 mb-3 mx-2">
|
||||
<a class="btn btn-primary" href="/logout">
|
||||
Log Out
|
||||
</a>
|
||||
</div>
|
||||
<h4>Данные профиля</h4>
|
||||
<div th:if="${errors}" th:text="${errors}" class="margin-bottom alert alert-danger"></div>
|
||||
<form action="/user" th:object="${userDto}" method="post">
|
||||
<input th:field="${userDto.id}" type="number" style="display: none;" />
|
||||
<div class="mb-3">
|
||||
<label for="login" class="form-label">Логин</label>
|
||||
<input id="login" th:field="${userDto.login}" class="form-control"
|
||||
required type="text" />
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="email" class="form-label">Почта</label>
|
||||
<input id="email" th:field="${userDto.email}" class="form-control"
|
||||
required type="text" />
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="password" class="form-label">Пароль (введите для подтверждения изменения данных)</label>
|
||||
<input id="password" th:field="${userDto.password}" class="form-control"
|
||||
required type="password" />
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<button type="submit" class="btn btn-success">
|
||||
Изменить
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<div>
|
||||
<a class="btn btn-outline-primary text-center mx-2"
|
||||
th:href="@{/user/post}">
|
||||
<!--Сам понимаешь что здесь надо сделать-->
|
||||
+
|
||||
</a>
|
||||
</div>
|
||||
<div class="my-5">
|
||||
<!--здесь тоже надо сделать нормальный вывод-->
|
||||
<div class="container-fluid">
|
||||
<div th:each="post, iterator: ${posts}" class="card border-dark mb-3 d-flex flex-row text-black justify-content-between">
|
||||
<div>
|
||||
<img class="col" style="width:300px;height:200px" th:src="${post.image}"/>
|
||||
</div>
|
||||
<div class="d-flex flex-grow-1 flex-column">
|
||||
<div class="flex-grow-1 mx-2">
|
||||
<h th:text="${post.heading}"></h>
|
||||
</div>
|
||||
<div class="flex-grow-1 mx-2">
|
||||
<p th:text="${post.content}"></p>
|
||||
</div>
|
||||
<div class="flex-grow-1 mx-2">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">#</th>
|
||||
<th scope="col">Пользователь</th>
|
||||
<th scope="col">Текст</th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr th:each="comment, iterator: ${post.comments}">
|
||||
<th scope="row" th:text="${iterator.index} + 1"/>
|
||||
<td th:text="${comment.user}" style="width: 60%"/>
|
||||
<td th:text="${comment.text}" style="width: 60%"/>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="d-flex flex-row justify-content-end ">
|
||||
<a class="btn btn-outline-primary text-center mx-2"
|
||||
th:href="@{/index/edit/{id}(id=${post.id})}">
|
||||
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
|
||||
</a>
|
||||
<button type="button" class="btn btn-outline-primary text-center mx-2"
|
||||
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${post.id}').click()|">
|
||||
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
|
||||
</button>
|
||||
<form th:action="@{'/index/delete/' + ${post.id}}" method="post">
|
||||
<button th:id="'remove-' + ${post.id}" type="submit" style="display: none">
|
||||
Удалить
|
||||
</button>
|
||||
</form>
|
||||
<a th:href=@{/index/{id}(id=${post.id})} class='btn btn-outline-primary mx-2'><i class="fa-solid fa-envelopes-bulk"></i></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
<th:block layout:fragment="scripts">
|
||||
<script type="module">
|
||||
</script>
|
||||
</th:block>
|
||||
|
||||
</html>
|
54
src/main/resources/templates/users.html
Normal file
@ -0,0 +1,54 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="table-responsive">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">#</th>
|
||||
<th scope="col">ID</th>
|
||||
<th scope="col">Логин</th>
|
||||
<th scope="col">Почта</th>
|
||||
<th scope="col">Пароль</th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr th:each="user, iterator: ${users}">
|
||||
<th scope="row" th:text="${iterator.index} + 1"/>
|
||||
<td th:text="${user.id}"/>
|
||||
<td th:text="${user.login}" style="width: 60%"/>
|
||||
<td th:text="${user.email}" style="width: 60%"/>
|
||||
<td style="width: 10%">
|
||||
<div class="btn-group" role="group" aria-label="Basic example">
|
||||
<button type="button" class="btn btn-outline-light text-center mx-2"
|
||||
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${user.id}').click()|">
|
||||
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
|
||||
</button>
|
||||
</div>
|
||||
<form th:action="@{/user/delete/{id}(id=${user.id})}" method="post">
|
||||
<button th:id="'remove-' + ${user.id}" type="submit" style="display: none">
|
||||
Удалить
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div th:if="${totalPages > 0}" class="pagination">
|
||||
<span style="float: left; padding: 5px 5px;">Pages:</span>
|
||||
<a th:each="page : ${pages}"
|
||||
th:href="@{/user/all(page=${page}, size=${users.size})}"
|
||||
th:text="${page}"
|
||||
th:class="${page == users.number + 1} ? active">
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
112
src/test/java/ru/ulstu/is/sbapp/JpaClientTests.java
Normal file
@ -0,0 +1,112 @@
|
||||
/*
|
||||
package ru.ulstu.is.sbapp;
|
||||
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.Post.service.PostNotFoundException;
|
||||
import ru.ulstu.is.sbapp.Post.service.PostService;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
import ru.ulstu.is.sbapp.User.service.UserNotFoundException;
|
||||
import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@SpringBootTest
|
||||
public class JpaClientTests {
|
||||
private static final Logger log = LoggerFactory.getLogger(JpaClientTests.class);
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
@Autowired
|
||||
private PostService postService;
|
||||
|
||||
@Test
|
||||
void testClientCreate() {
|
||||
userService.deleteAllUsers();
|
||||
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
|
||||
log.info("testUserCreate: " + user.toString());
|
||||
Assertions.assertNotNull(user.getId());
|
||||
|
||||
userService.deleteAllUsers();
|
||||
}
|
||||
@Test
|
||||
void testReadClient()
|
||||
{
|
||||
userService.deleteAllUsers();
|
||||
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
|
||||
log.info("testUserRead[0]: " + user.toString());
|
||||
final User curuser=userService.findUser(user.getId());
|
||||
log.info("testUserRead[1]: " + curuser.toString());
|
||||
Assertions.assertEquals(user, curuser);
|
||||
userService.deleteAllUsers();
|
||||
}
|
||||
@Test
|
||||
void testClientReadNotFound() {
|
||||
userService.deleteAllUsers();
|
||||
Assertions.assertThrows(UserNotFoundException.class, () -> userService.findUser(-1L));
|
||||
}
|
||||
@Test
|
||||
void testClientReadAll() {
|
||||
userService.deleteAllUsers();
|
||||
userService.addUser("Pupa","Lupa","sasdfdsf@gmail.com");
|
||||
userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
|
||||
final List<User> users = userService.findAllUsers();
|
||||
log.info("testUserReadAll: " + users.toString());
|
||||
Assertions.assertEquals(users.size(), 2);
|
||||
|
||||
userService.deleteAllUsers();
|
||||
}
|
||||
@Test
|
||||
void testClientReadAllEmpty() {
|
||||
userService.deleteAllUsers();
|
||||
final List<User> users = userService.findAllUsers();
|
||||
log.info("testUserReadAllEmpty: " + users.toString());
|
||||
Assertions.assertEquals(users.size(), 0);
|
||||
}
|
||||
@Test
|
||||
void testDeletePostwithcomments()
|
||||
{
|
||||
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
|
||||
final User user12 = userService.addUser("Anton","Sorokin","zxcv@gmail.com");
|
||||
userService.addNewPost(user.getId(),"text","tezt");
|
||||
final List<Post> post = postService.findAllPosts();
|
||||
final Post post1 = post.get(0);
|
||||
postService.addCommentToPost(post1.getId(),user12.getId(),"Da");
|
||||
userService.deleteUser(user.getId());
|
||||
}
|
||||
@Test
|
||||
void testAddAndDeletePost()
|
||||
{
|
||||
postService.deleteAllPosts();
|
||||
userService.deleteAllUsers();
|
||||
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
|
||||
final User user12 = userService.addUser("Anton","Sorokin","zxcv@gmail.com");
|
||||
userService.addNewPost(user.getId(),"Text1","Text2"); //post
|
||||
userService.addNewPost(user.getId(),"Привет","Да"); //post1
|
||||
final List<Post> posts =postService.findAllPosts();
|
||||
final User user1 = userService.findUser(user.getId());
|
||||
final List<Post> posts1 = user1.getPosts();
|
||||
log.info("testAddAndDeletePost :: ADD " + posts.toString() + " and " + posts1.toString());
|
||||
Assertions.assertEquals(posts.get(0).getUser(), user);
|
||||
Assertions.assertEquals(posts.toString(), posts1.toString());
|
||||
log.info("testAddAndDeletePost :: Delete ");
|
||||
userService.deletePost(user.getId(),posts.get(0).getId());
|
||||
final User us = userService.findUser(user.getId());
|
||||
Assertions.assertThrows(PostNotFoundException.class, () -> postService.findPost(posts.get(0).getId()));
|
||||
final List<Post> postss =postService.findAllPosts();
|
||||
log.info(us.getPosts().toString());
|
||||
log.info(postss.toString());
|
||||
userService.deleteAllUsers();
|
||||
postService.deleteAllPosts();
|
||||
}
|
||||
//посты и коментарии содержащие определенный текст
|
||||
|
||||
}.
|
||||
*/
|