Compare commits

...

14 Commits
main ... Lab04

57 changed files with 12082 additions and 23 deletions

Binary file not shown.

View File

@ -4,7 +4,7 @@ plugins {
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}
group = 'ru.ulstu.is'
group = 'ru.ulsru.is'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
@ -14,6 +14,9 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

BIN
data.mv.db Normal file

Binary file not shown.

24
frontend/.gitignore vendored Normal file
View 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?

19
frontend/data.json Normal file
View File

@ -0,0 +1,19 @@
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"profile": {
"name": "typicode"
}
}

32
frontend/index.html Normal file
View File

@ -0,0 +1,32 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="/node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"
integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.min.js"
integrity="sha384-IDwe1+LCz02ROU9k972gdyvl+AESN10+x7tBKgc9I5HFtuNz0wWnPclzo6p9vxnk"
crossorigin="anonymous"
></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>Кашин Максим ПИбд-22</title>
</head>
<body class="d-flex flex-column h-100">
<div id="app"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

9838
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

29
frontend/package.json Normal file
View File

@ -0,0 +1,29 @@
{
"name": "spa-react",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"fake-server": "json-server --watch data.json -p 8081",
"start": "npm-run-all --parallel dev fake-server",
"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",
"npm-run-all": "^4.1.5",
"json-server": "^0.17.1"
}
}

93
frontend/src/App.css Normal file
View File

@ -0,0 +1,93 @@
nav {
background-color: #708090;
}
main {
background-color: #ffffff;
/* min-height: 90vh; */
}
footer {
background-color: #708090;
color: black;
position: absolute;
bottom: 0;
width: 100vw;
}
.size {
overflow-x: hidden;
}
.card {
background-color: #bdb1b1;
border-color: #8c7b7b;
}
.card-body {
background-color: #8c7b7b;
}
h1 {
word-wrap: break-word;
}
#banner {
margin: 0px 15px 15px 15px;
padding-top: 15px;
display: flex;
align-items: center;
flex-direction: column;
}
#banner img {
border-radius: 5px;
}
#banner img.show {
width: 100%;
opacity: 1;
transition: opacity 1s, visibility 0s;
}
#banner img.hide {
height: 0;
width: 0;
opacity: 0;
visibility: hidden;
transition: opacity 1s, visibility 0s 1s;
}
@media (max-width: 767px) {
.btn {
padding: 1px 5px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.btn {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.btn {
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
border-radius: 4px;
}
}
@media (min-width: 1200px) {
.btn {
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px;
}
}
@media (max-width: 600px) {
.tem {
padding-right: 50px;
}
}
.vl {
border-left: 5px solid;
height: 100vh;
}

47
frontend/src/App.jsx Normal file
View File

@ -0,0 +1,47 @@
import './App.css';
import { useRoutes, Outlet, BrowserRouter } from 'react-router-dom';
import Header from './components/common/Header';
import Footer from "./components/common/Footer";
import CatalogBuyers from './components/catalogs/CatalogBuyers';
import { useState } from 'react';
import CarInfo from './components/catalogs/CarInfo';
import CatalogStores from './components/catalogs/CatalogStores';
import Find from './components/catalogs/Find';
function Router(props) {
return useRoutes(props.rootRoute);
}
export default function App() {
const [car,setCar] = useState([]);
const routes = [
{ index: true, element: <CatalogBuyers /> },
{ path: "catalogs/store", element: <CatalogStores/> , label: "Магазины" },
{ path: "catalogs/buyer", element: <CatalogBuyers />, label: "Покупатели" },
{ path: "catalogs/car", element: <CarInfo car={car} setCar={setCar}/>, label: "Машины" },
{ path: "catalogs/find", element: <Find/>, label: "Поиск" }
];
const links = routes.filter(route => route.hasOwnProperty('label'));
const rootRoute = [
{ path: '/', element: render(links), children: routes }
];
function render(links) {
return (
<>
<Header links={links} />
<div className="container-fluid p-0">
<Outlet />
</div>
<Footer></Footer>
</>
);
}
return (
<BrowserRouter>
<Router rootRoute={ rootRoute } />
</BrowserRouter>
);
}

View File

@ -0,0 +1,135 @@
import { useState, useEffect, Component } from "react";
import CatalogCar from "./CatalogCars";
import Store from "../../models/Store";
import Buyer from "../../models/Buyer";
import Car from "../../models/Car";
import DataService from "../../services/DataService";
export default function Menustores(props) {
const url = "/car";
const prodUrl = "/store";
const workUrl = "/buyer"
const transformer = (data) => new Car(data);
const catalogProdHeaders = [
{ name: "storeName", label: "Название магазина" },
];
const catalogWorkHeaders = [
{ name: "buyerFirstName", label: "Имя" },
{ name: "buyerSecondName", label: "Фамилия" },
];
const [data, setData] = useState(new Car());
const [store, setStore] = useState([]);
const [workStore, setWorkStore] = useState([]);
const [buyer, setBuyer] = useState([]);
const [workBuyer, setWorkBuyer] = useState([]);
useEffect(() => {
DataService.readAll(prodUrl, (data) => new Store(data)).then(
(data) => setStore(data)
);
DataService.readAll(workUrl, (data) => new Buyer(data)).then(
(data) => setBuyer(data)
);
}, []);
function handleOnAdd() {
setData(new Car());
setWorkStore([]);
setWorkBuyer([]);
}
function handleOnEdit(data) {
setData(new Car(data));
}
function handleFormChange(event) {
setData({ ...data, [event.target.id]: event.target.value });
}
function handleUpdateStores(value) {
let temp = data.storeDTOList.filter((x) => x.id != value.id);
data.storeDTOList = [];
for (let i = 0; i < temp.length; i++) {
data.storeDTOList.push(temp[i]);
}
data.storeDTOList.push(value);
setData(data);
console.log(data);
setWorkStore();
}
function setCar() {
data.storeDTOList = [];
for (let i = 0; i < workStore.length; i++) {
data.storeDTOList.push(workStore[i]);
}
data.buyerDTOList = [];
for (let i = 0; i < workBuyer.length; i++) {
data.buyerDTOList.push(workBuyer[i]);
}
setData(data);
}
function handleDeleteStores(value) {
let temp = data.storeDTOList.filter((x) => x.id != value);
data.storeDTOList = [];
for (let i = 0; i < temp.length; i++) {
data.storeDTOList.push(temp[i]);
}
console.log(data);
setData(data);
setWorkStore(workStore.filter((x) => x.id !== value));
console.log(workStore);
}
function handleUpdateBuyers(value){
let temp = data.buyerDTOList.filter((x) => x.id != value.id);
data.buyerDTOList = [];
for (let i = 0; i < temp.length; i++) {
data.buyerDTOList.push(temp[i]);
}
data.buyerDTOList.push(value);
setData(data);
console.log(data);
setWorkBuyer(data.buyerDTOList);
console.log(workBuyer);
}
function handleDeleteBuyers(value) {
let temp = data.buyerDTOList.filter((x) => x.id != value);
data.buyerDTOList = [];
for (let i = 0; i < temp.length; i++) {
data.buyerDTOList.push(temp[i]);
}
console.log(data);
setData(data);
setWorkBuyer(workBuyer.filter((x) => x.id !== value));
console.log(workBuyer);
}
return (
<main className="flex-shrink-0">
<CatalogCar
url={url}
transformer={transformer}
data={data}
onAdd={handleOnAdd}
onEdit={handleOnEdit}
handleFormChange={handleFormChange}
set={setCar}
car={props.car}
setCar={props.setCar}
store={store}
catalogProdHeaders={catalogProdHeaders}
workStore={workStore}
setWorkStore={setWorkStore}
updateStores={handleUpdateStores}
deleteStores={handleDeleteStores}
buyer={buyer}
catalogWorkHeaders={catalogWorkHeaders}
workBuyer={workBuyer}
setWorkBuyer={setWorkBuyer}
updateBuyers={handleUpdateBuyers}
deleteBuyers={handleDeleteBuyers}
/>
</main>
);
}

View File

@ -0,0 +1,114 @@
import { useState, useEffect } from "react";
import Toolbar from "../common/Toolbar";
import Table from "../common/Table";
import Modal from "../common/Modal";
import DataService from '../../services/DataService';
export default function CatalogW(props) {
const [items, setItems] = useState([]);
const [modalHeader, setModalHeader] = useState('');
const [modalConfirm, setModalConfirm] = useState('');
const [modalVisible, setModalVisible] = useState(false);
const [isEdit, setEdit] = useState(false);
let selectedItems = [];
useEffect(() => {
loadItems();
}, []);
function loadItems() {
DataService.readAll(props.getAllUrl, props.transformer)
.then(data => setItems(data));
}
function saveItem() {
console.log(props.data);
if (!isEdit) {
DataService.create(props.getAllUrl, props.data).then(() => loadItems());
} else {
DataService.update(props.url + props.data.id, props.data).then(() => loadItems());
}
}
function handleAdd() {
setEdit(false);
setModalHeader('Добавление элемента');
setModalConfirm('Добавить');
setModalVisible(true);
props.onAdd();
}
function handleEdit() {
if (selectedItems.length === 0) {
return;
}
edit(selectedItems[0]);
}
function edit(editedId) {
DataService.read(props.url + editedId, props.transformer)
.then(data => {
setEdit(true);
setModalHeader('Редактирование элемента');
setModalConfirm('Сохранить');
setModalVisible(true);
props.onEdit(data);
});
}
function handleRemove() {
if (selectedItems.length === 0) {
return;
}
if (confirm('Удалить выбранные элементы?')) {
const promises = [];
selectedItems.forEach(item => {
promises.push(DataService.delete(props.url + item));
});
Promise.all(promises).then((results) => {
selectedItems.length = 0;
loadItems();
});
}
}
function handleTableClick(tableSelectedItems) {
selectedItems = tableSelectedItems;
}
function handleTableDblClick(tableSelectedItem) {
edit(tableSelectedItem);
}
function handleModalHide() {
setModalVisible(false);
}
function handleModalDone() {
saveItem();
}
return (
<>
<Toolbar
onAdd={handleAdd}
onEdit={handleEdit}
onRemove={handleRemove}/>
<Table
headers={props.headers}
items={items}
selectable={true}
onClick={handleTableClick}
onDblClick={handleTableDblClick}/>
<Modal
header={modalHeader}
confirm={modalConfirm}
visible={modalVisible}
onHide={handleModalHide}
onDone={handleModalDone}>
{props.children}
</Modal>
</>
);
}

View File

@ -0,0 +1,53 @@
import { useState, useEffect } from 'react';
import Catalog from './Catalog';
import Buyer from '../../models/Buyer';
import DataService from '../../services/DataService';
export default function CatalogBuyers(props) {
const getAllUrl = '/buyer';
const url = '/buyer/';
const transformer = (data) => new Buyer(data);
const catalogBuyerHeaders = [
{ name: 'buyerFirstName', label: 'Имя' },
{ name: 'buyerSecondName', label: 'Фамилия' },
];
const [data, setData] = useState(new Buyer());
function handleOnAdd() {
console.log("create buyer: " + data.buyerFirstName + "|" + data.buyerSecondName);
setData(new Buyer());
}
function handleOnEdit(data) {
setData(new Buyer(data));
}
function handleFormChange(event) {
setData({ ...data, [event.target.id]: event.target.value })
}
return (
<main className="flex-shrink-0" style={{ backgroundColor: "white" }}>
<Catalog
headers={catalogBuyerHeaders}
getAllUrl={getAllUrl}
url={url}
transformer={transformer}
data={data}
onAdd={handleOnAdd}
onEdit={handleOnEdit}>
<div className="mb-3">
<label htmlFor="buyerFirstName" className="form-label">Имя покупателя</label>
<input type="text" id="buyerFirstName" className="form-control" required
value={data.buyerFirstName} onChange={handleFormChange}/>
</div>
<div className="mb-3">
<label htmlFor="buyerSecondName" className="form-label">Фамилия покупателя</label>
<input type="text" id="buyerSecondName" className="form-control" required
value={data.buyerSecondName} onChange={handleFormChange}/>
</div>
</Catalog>
</main>
);
}

View File

@ -0,0 +1,313 @@
import { useState, useEffect, Component } from "react";
import ToolbarStore from "../common/ToolbarStore";
import Card from "../common/Card";
import Modal from "../common/Modal";
import DataService from "../../services/DataService";
import Table from "../common/Table";
import Toolbar from "../common/Toolbar";
export default function catalogP(props) {
const [items, setItems] = useState([]);
const [modalHeader, setModalHeader] = useState("");
const [modalConfirm, setModalConfirm] = useState("");
const [modalVisible, setModalVisible] = useState(false);
const [isEdit, setEdit] = useState(false);
const [StoreL, setStoreL] = useState({});
const [BuyerL, setBuyerL] = useState({});
useEffect(() => {
loadItems();
}, []);
function loadItems() {
DataService.readAll(props.url, props.transformer).then((data) =>{
setItems(data);
});
DataService.readAll(props.url, props.transformer).then((data) =>
setItems(data));
}
const catalogCarHeaders = [
{ name: 'carName', label: 'Название' },
// { name: 'storeDTOList.length', label: 'Количество магазинов'}
];
let selectedItems = [];
async function saveItem() {
console.log(props.data);
if (!isEdit) {
await props.set();
DataService.create(props.url, props.data).then(() => loadItems());
} else {
await props.set();
DataService.update(props.url + "/" + props.data.id, props.data).then(() =>
loadItems()
);
}
}
function handleRemoveCard(id) {
if (confirm("Удалить выбранные элементы?")) {
DataService.delete(props.url + "/" + id).then(() => {
loadItems();
});
}
}
function handleRemove() {
if (selectedItems.length === 0) {
return;
}
if (confirm('Удалить выбранные элементы?')) {
const promises = [];
selectedItems.forEach(item => {
promises.push(DataService.delete(props.url + "/" + item));
});
Promise.all(promises).then((results) => {
selectedItems.length = 0;
loadItems();
});
}
}
function handleAdd() {
setEdit(false);
setModalHeader("Добавление элемента");
setModalConfirm("Добавить");
setModalVisible(true);
props.onAdd();
}
function handleEdit(id) {
if (selectedItems.length === 0) {
return;
}
setStoreL(
props.workStore.filter((x) => x.id == selectedItems[0])[0]
);
}
function edit(editedId) {
DataService.read(props.url+ "/" + editedId, props.transformer).then((data) => {
for(let i = 0; i < data.storeDTOList.length; i++){
props.workStore.push(data.storeDTOList[i]);
props.setWorkStore(props.workStore)
}
for(let i = 0; i < data.buyerDTOList.length; i++){
props.workBuyer.push(data.buyerDTOList[i]);
//props.setworkBuyer(props.workBuyer)
}
setEdit(true);
setModalHeader("Редактирование элемента");
setModalConfirm("Сохранить");
setModalVisible(true);
props.onEdit(data);
});
}
function handleModalDone() {
saveItem();
}
function handleModalHide() {
setModalVisible(false);
props.setWorkStore([]);
props.setWorkBuyer([]);
}
function handleRemoveStore(id, e) {
if (selectedItems.length === 0) {
return;
}
if (confirm("Удалить выбранные элементы?")) {
const promises = [];
selectedItems.forEach((item) => {
props.deleteStores(item);
});
selectedItems.length = 0;
}
}
function handleRemoveBuyer(id, e) {
if (selectedItems.length === 0) {
return;
}
if (confirm("Удалить выбранные элементы?")) {
const promises = [];
selectedItems.forEach((item) => {
props.deleteBuyers(item);
});
selectedItems.length = 0;
}
}
async function handleAddStore() {
if (props.workStore.filter((x) => x.id == StoreL.id).length == 0)
{
await props.updateStores(StoreL);
setStoreL({});
props.workStore.push(StoreL);
await props.setWorkStore(props.workStore);
setStoreL({});
return;
}
}
async function handleAddBuyer() {
if (props.workBuyer.filter((x) => x.id == BuyerL.id).length == 0)
{
await props.updateBuyers(BuyerL);
setBuyerL({});
props.workBuyer.push(BuyerL);
await props.setWorkBuyer(props.workBuyer);
setBuyerL({});
return;
}
}
function handleFormChangeStore(event) {
if (event.target.id === "storeName") {
setStoreL({
...StoreL,
["id"]: event.target.value,
["storeName"]: props.store
.filter((x) => x.id == event.target.value)
.map((x) => x.storeName)[0],
});
return;
}
setStoreL({
...StoreL,
[event.target.id]: Number(event.target.value),
});
return;
}
function handleFormChangeBuyer(event) {
if (event.target.id === "buyerSecondName") {
setBuyerL({
...BuyerL,
["id"]: event.target.value,
["buyerFirstName"]: props.buyer
.filter((x) => x.id == event.target.value)
.map((x) => x.buyerFirstName)[0],
["buyerSecondName"]: props.buyer
.filter((x) => x.id == event.target.value)
.map((x) => x.buyerSecondName)[0],
});
return;
}
setBuyerL({
...BuyerL,
[event.target.id]: Number(event.target.value),
});
return;
}
function handleTableClick(tableSelectedItems) {
selectedItems = tableSelectedItems;
}
function handleTableDblClickModalProd(tableSelectedItem) {
setStoreL(
props.workStore.filter((x) => x.id == tableSelectedItem)[0]
);
}
function handleTableDblClick(tableSelectedItem) {
edit(tableSelectedItem);
}
return (
<>
{/* <ToolbarStore onAdd={handleAdd} />
<Card items={items} onEdit={edit} onRemove={handleRemoveCard} car={props.car} setCar={props.setCar}/> */}
<Modal
header={modalHeader}
confirm={modalConfirm}
visible={modalVisible}
onHide={handleModalHide}
onDone={handleModalDone}
>
<div className="mb-3">
<label htmlFor="name" className="form-label">
Название машины
</label>
<input
type="text"
id="carName"
className="form-control"
required
value={props.data.carName}
onChange={props.handleFormChange}
/>
</div>
<div className="mb-3">
<label htmlFor="groupId" className="form-label">
Магазин
</label>
<select
id="storeName"
className="form-select"
required
value={StoreL.id}
onChange={handleFormChangeStore}
>
<option disabled value="">
Укажите магазин
</option>
{props.store.map((group) => (
<option key={group.id} value={group.id}>
{group.storeName}
</option>
))}
</select>
</div>
<Toolbar
onAdd={handleAddStore}
onEdit={handleEdit}
onRemove={handleRemoveStore}
/>
<Table
headers={props.catalogProdHeaders}
items={props.workStore}
allItems={props.store}
selectable={true}
onClick={handleTableClick}
onDblClick={handleTableDblClickModalProd}
/>
<div className="mb-3">
<label htmlFor="groupId" className="form-label">
Покупатель
</label>
<select
id="buyerSecondName"
className="form-select"
required
value={BuyerL.id}
onChange={handleFormChangeBuyer}
>
<option disabled value="">
Укажите рабочего
</option>
{props.buyer.map((group) => (
<option key={group.id} value={group.id}>
{group.buyerFirstName} {group.buyerSecondName}
</option>
))}
</select>
</div>
<Toolbar
onAdd={handleAddBuyer}
onEdit={handleEdit}
onRemove={handleRemoveBuyer}
/>
<Table
headers={props.catalogWorkHeaders}
items={props.workBuyer}
allItems={props.buyer}
selectable={true}
onClick={handleTableClick}
onDblClick={handleTableDblClickModalProd}
/>
</Modal>
<Toolbar
onAdd={handleAdd}
onEdit={handleEdit}
onRemove={handleRemove}
/>
<Table
headers={catalogCarHeaders}
items={items}
selectable={true}
onClick={handleTableClick}
onDblClick={handleTableDblClick}
/>
</>
);
}

View File

@ -0,0 +1,47 @@
import { useState, useEffect } from 'react';
import Catalog from './Catalog';
import Store from '../../models/Store';
import DataService from '../../services/DataService';
export default function CatalogStores(props) {
const getAllUrl = '/store';
const url = '/store/';
const transformer = (data) => new Store(data);
const catalogStudHeaders = [
{ name: 'storeName', label: 'Название' }
];
const [data, setData] = useState(new Store());
function handleOnAdd() {
setData(new Store());
console.log("create store: " + data.storeName);
}
function handleOnEdit(data) {
setData(new Store(data));
}
function handleFormChange(event) {
setData({ ...data, [event.target.id]: event.target.value })
}
return (
<main className="flex-shrink-0" style={{ backgroundColor: "white" }}>
<Catalog
headers={catalogStudHeaders}
getAllUrl={getAllUrl}
url={url}
transformer={transformer}
data={data}
onAdd={handleOnAdd}
onEdit={handleOnEdit}>
<div className="mb-3">
<label htmlFor="storeName" className="form-label">Название</label>
<input type="text" id="storeName" className="form-control" required
value={data.storeName} onChange={handleFormChange}/>
</div>
</Catalog>
</main>
);
}

View File

@ -0,0 +1,88 @@
import DataService from "../../services/DataService";
import Buyer from "../../models/Buyer";
import Store from "../../models/Store";
import Table from "../common/Table";
import { useState, useEffect, Component } from "react";
import '../../App.css';
export default function Find(props) {
const prodUrl = "/store";
const storeURL ='/store/buyer/';
const [itemsP, setItemsP] = useState([]);
const [StoreL, setStoreL] = useState({});
const [store, setStore] = useState([]);
const catalogBuyerHeaders = [
{ name: 'buyerFirstName', label: 'Имя' },
{ name: 'buyerSecondName', label: 'Фамилия' },
];
const transformer = (data) => new Buyer(data);
function loadItems() {
DataService.readAll(storeURL + StoreL.id, transformer)
.then(data => setItemsP(data));
}
useEffect(() => {
DataService.readAll(prodUrl, (data) => new Store(data)).then(
(data) => setStore(data)
);
}, []);
let selectedItems = [];
function handleTableClick(tableSelectedItems) {
selectedItems = tableSelectedItems;
}
function handleTableDblClick(tableSelectedItem) {
confirm(tableSelectedItem);
}
function handleFormChangeStore(event) {
if (event.target.id === "storeName") {
setStoreL({
...StoreL,
["id"]: event.target.value,
["storeName"]: store
.filter((x) => x.id == event.target.value)
.map((x) => x.storeName)[0],
});
return;
}
setStoreL({
...StoreL,
[event.target.id]: Number(event.target.value),
});
return;
}
return(
<main className="form-group" style={{ backgroundColor: "white" }}>
<select
id="storeName"
className="form-select"
value={StoreL.id}
onChange={handleFormChangeStore}
>
<option disabled selected value="">
Укажите магазин
</option>
{store.map((group) => (
<option key={group.id} value={group.id}>
{group.storeName}
</option>
))}
</select>
<a
class="btn btn-light d-flex justify-content-center align-items-center"
href="#"
type="button"
onClick={(e) => loadItems()}
>
Покупатели, которые пользуются выбранным магазином
</a>
<div className="d-flex ">
<Table className="table"
headers={catalogBuyerHeaders}
items={itemsP}
selectable={false}
onClick={handleTableClick}
onDblClick={handleTableDblClick}/>
</div>
</main>
);
}

View File

@ -0,0 +1,60 @@
import DataService from "../../services/DataService";
export default function Card(props) {
function edit(id) {
props.onEdit(id);
}
function remove(id) {
props.onRemove(id);
}
async function mess(id){
let currentStore = props.store.filter(x => x.id == id.id);
if (currentStore.length != 0){
let temp = props.store.filter(x => x.id != id.id);
currentStore[0].count++;
temp.push(currentStore[0]);
await props.setStore(temp);
return;
}else{
id.count++;
props.store.push(id);
props.setStore(props.store);
}
}
return (
<div className="temp row row-cols-1 row-cols-md-3 g-4" id="tbl-items">
{props.items.map((item) => (
<div className="col" key={item.id}>
<div className="card">
<div
className="container"
style={{ width: "100%", height: "100px", alignItems: "center" }}
>
<p>{item["carName"]}</p>
</div>
<div className="card-body">
<a
href="#"
className="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
onClick={(e) => remove(item.id, e)}
>
Удалить
</a>
<a
href="#"
type="button"
className="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
data-bs-toggle="modal"
data-bs-target="#staticBackdrop"
onClick={(e) => edit(item.id, e)}
>
Изменить
</a>
</div>
</div>
</div>
))}
</div>
);
}

View File

@ -0,0 +1,8 @@
export default function Footer(props) {
return (
<footer class="text-center p-4 p-3 mb-2 bg-light text-dark">
Кашин Максим ПИбд-22
</footer>
);
}

View File

@ -0,0 +1,32 @@
import { NavLink } from "react-router-dom";
export default function Header(props) {
return (
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<div className="container-fluid">
<button
className="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
{props.links.map((route) => (
<li key={route.path} className="nav-item">
<NavLink className="nav-link fs-4" to={route.path}>
{route.label}
</NavLink>
</li>
))}
</ul>
</div>
</div>
</nav>
);
}

View 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-light" type="button" onClick={hide}>Закрыть</button>
<button className="btn btn-light" type="button" onClick={done}>
{props.confirm}
</button>
</div>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,73 @@
import { useState } from 'react';
import styles from './Table.module.css';
export default function Table(props) {
const [tableUpdate, setTableUpdate] = useState(false);
const [selectedItems, setSelectedItems] = useState([]);
function isSelected(id) {
if (!props.selectable) {
return false;
}
return selectedItems.includes(id);
}
function click(id) {
if (!props.selectable) {
return;
}
if (isSelected(id)) {
var index = selectedItems.indexOf(id);
if (index !== -1) {
selectedItems.splice(index, 1);
setSelectedItems(selectedItems);
setTableUpdate(!tableUpdate);
}
} else {
selectedItems.push(id);
setSelectedItems(selectedItems);
setTableUpdate(!tableUpdate);
}
props.onClick(selectedItems);
}
function dblClick(id) {
if (!props.selectable) {
return;
}
props.onDblClick(id);
}
return (
<table className={`table table-hover ${styles.table} ${props.selectable ? styles.selectable : ''}`}>
<thead>
<tr>
<th scope="col">#</th>
{
props.headers.map(header =>
<th key={header.name} scope="col">
{header.label}
</th>
)
}
</tr>
</thead>
<tbody>
{
props.items?.map((item, index) =>
<tr key={item.id}
className={isSelected(item.id) ? styles.selected : ''}
onClick={(e) => click(item.id, e)} onDoubleClick={(e) => dblClick(item.id, e)}>
<th scope="row">{index + 1}</th>
{
props.headers.map(header =>
<td key={item.id + header.name}>{item[header.name]}</td>
)
}
</tr>
)
}
</tbody >
</table >
);
}

View File

@ -0,0 +1,12 @@
.table tbody tr {
user-select: none;
}
.selectable tbody tr:hover {
cursor: pointer;
}
.selected {
background-color: #808080;
opacity: 80%;
}

View File

@ -0,0 +1,29 @@
import styles from './Toolbar.module.css';
export default function Toolbar(props) {
function add() {
props.onAdd();
}
function edit() {
props.onEdit();
}
function remove() {
props.onRemove();
}
return (
<main className="form-group" style={{ backgroundColor: "white" }}>
<a type="button" className="btn btn-light d-flex justify-content-center align-items-center" onClick={add}>
Добавить
</a>
<a type="button" className="btn btn-light d-flex justify-content-center align-items-center" onClick={edit}>
Изменить
</a>
<a type="button" className="btn btn-light d-flex justify-content-center align-items-center" onClick={remove}>
Удалить
</a>
</main>
);
}

View File

@ -0,0 +1,3 @@
.btn {
min-width: 140px;
}

View File

@ -0,0 +1,17 @@
export default function ToolbarStore(props) {
function add() {
props.onAdd();
}
return (
<div className="btn-group mt-2" role="group">
<button
type="button"
className={`btn btn-outline-dark text-center d-flex justify-content-md-center mx-5 mb-3`}
onClick={add}
>
Добавить
</button>
</div>
);
}

8
frontend/src/main.jsx Normal file
View File

@ -0,0 +1,8 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './style.css'
ReactDOM.createRoot(document.getElementById('app')).render(
<App />
)

View File

@ -0,0 +1,8 @@
export default class Buyer {
constructor(data) {
this.id = data?.id;
this.buyerFirstName = data?.buyerFirstName || "";
this.buyerSecondName = data?.buyerSecondName || "";
//this.car = data?.car || null;
}
}

View File

@ -0,0 +1,8 @@
export default class Car {
constructor(data) {
this.id = data?.id;
this.carName = data?.carName || "";
this.storeDTOList = data?.storeDTOList || [];
this.buyerDTOList = data?.buyerDTOList || [];
}
}

View File

@ -0,0 +1,7 @@
export default class Store {
constructor(data) {
this.id = data?.id;
this.storeName = data?.storeName || "";
this.carDTOList = data?.carDTOList || [];
}
}

View File

@ -0,0 +1,46 @@
import axios from 'axios';
export default class DataService {
static dataUrlPrefix = 'http://localhost:8080';
static async readAll(url, transformer) {
const response = await fetch(this.dataUrlPrefix + url);
const data = await response.json();
console.log(data);
return data.map(item => transformer(item));
}
static async read(url, transformer) {
const response = await axios.get(this.dataUrlPrefix + url);
return transformer(response.data);
}
static async create(url, data) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
};
console.log(JSON.stringify(data) + " " + this.dataUrlPrefix + " " + url);
const response = await fetch(this.dataUrlPrefix + url, requestParams);
}
static async update(url, data) {
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
};
const response = await fetch(this.dataUrlPrefix + url, requestParams);
return true;
}
static async delete(url) {
const response = await axios.delete(this.dataUrlPrefix + url);
return response.data.id;
}
}

0
frontend/src/style.css Normal file
View File

7
frontend/vite.config.js Normal file
View File

@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()]
})

View File

@ -1,9 +1,7 @@
package ru.ulstu.is.lab1;
package ru.ulsru.is.lab1;
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
@ -13,9 +11,6 @@ public class Lab1Application {
public static void main(String[] args) {
SpringApplication.run(Lab1Application.class, args);
}
@GetMapping("/name")
public String hello(@RequestParam(value = "n", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}

View File

@ -0,0 +1,28 @@
package ru.ulsru.is.lab1;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**").allowedMethods("*");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
ViewControllerRegistration registration = registry.addViewController("/notFound");
registration.setViewName("forward:/index.html");
registration.setStatusCode(HttpStatus.OK);
}
// @Bean
// public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
// return container -> {
// container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
// };
// }
}

View File

@ -0,0 +1,12 @@
package ru.ulsru.is.lab1.lab3.Respository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ru.ulsru.is.lab1.lab3.model.Buyer;
import java.util.List;
public interface IBuyerRespository extends JpaRepository<Buyer, Long> {
}

View File

@ -0,0 +1,7 @@
package ru.ulsru.is.lab1.lab3.Respository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulsru.is.lab1.lab3.model.Car;
public interface ICarRespository extends JpaRepository<Car, Long> {
}

View File

@ -0,0 +1,14 @@
package ru.ulsru.is.lab1.lab3.Respository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ru.ulsru.is.lab1.lab3.model.Store;
import ru.ulsru.is.lab1.lab3.model.Buyer;
import java.util.List;
public interface IStoreRespository extends JpaRepository<Store, Long> {
@Query("SELECT DISTINCT с.buyers FROM Car с where :store MEMBER OF с.stores")
List<Buyer> getBuyers(@Param("store") Store store);
}

View File

@ -0,0 +1,49 @@
package ru.ulsru.is.lab1.lab3.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulsru.is.lab1.lab3.service.BuyerService;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/buyer")
public class BuyerController {
private final BuyerService buyerService;
public BuyerController(BuyerService buyerService){
this.buyerService = buyerService;
}
@PostMapping
public BuyerDTO addBuyer(@RequestBody @Valid BuyerDTO buyerDTO) {
return new BuyerDTO(buyerService.addBuyer(buyerDTO));
}
@PutMapping("/{id}")
public BuyerDTO updateBuyer(@PathVariable Long id, @RequestBody @Valid BuyerDTO buyerDTO) {
return new BuyerDTO(buyerService.updateBuyer(id, buyerDTO));
}
@DeleteMapping("/{id}")
public BuyerDTO removeBuyer(@PathVariable Long id) {
return new BuyerDTO(buyerService.deleteBuyer(id));
}
@DeleteMapping
public void removeAllBuyers() {
buyerService.deleteAllBuyers();
}
@GetMapping("/{id}")
public BuyerDTO findBuyer(@PathVariable Long id) {
return new BuyerDTO(buyerService.findBuyer(id));
}
@GetMapping
public List<BuyerDTO> findAllBuyer() {
return buyerService.findAllBuyers()
.stream()
.map(x-> new BuyerDTO(x))
.toList();
}
}

View File

@ -0,0 +1,25 @@
package ru.ulsru.is.lab1.lab3.controller;
import ru.ulsru.is.lab1.lab3.model.Buyer;
public class BuyerDTO {
private long id;
private String buyerFirstName;
private String buyerSecondName;
public BuyerDTO(Buyer buyer){
this.id =buyer.getId();
this.buyerFirstName = buyer.getBuyerFirstName();
this.buyerSecondName = buyer.getBuyerSecondName();
}
public BuyerDTO(){
}
public long getId() {
return id;
}
public String getBuyerFirstName(){
return buyerFirstName;
}
public String getBuyerSecondName(){
return buyerSecondName;
}
}

View File

@ -0,0 +1,43 @@
package ru.ulsru.is.lab1.lab3.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulsru.is.lab1.lab3.service.CarService;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/car")
public class CarController {
private final CarService carService;
public CarController(CarService carService){
this.carService = carService;
}
@PostMapping
public CarDTO addCar(@RequestBody @Valid CarDTO carDTO){
return new CarDTO(carService.addCar(carDTO));
}
@PutMapping("/{id}")
public CarDTO updateCar(@PathVariable Long id, @RequestBody @Valid CarDTO carDTO){
return new CarDTO(carService.updateCar(id, carDTO));
}
@DeleteMapping("/{id}")
public CarDTO removeCar(@PathVariable Long id){
return new CarDTO(carService.deleteCar(id));
}
@DeleteMapping
public void removeAllCars(){
carService.deleteAllCars();
}
@GetMapping("/{id}")
public CarDTO findCar(@PathVariable Long id){
return new CarDTO(carService.findCar(id));
}
@GetMapping
public List<CarDTO> findAllCars(){
return carService.findAllCars()
.stream()
.map(x -> new CarDTO(x))
.toList();
}
}

View File

@ -0,0 +1,38 @@
package ru.ulsru.is.lab1.lab3.controller;
import ru.ulsru.is.lab1.lab3.model.Car;
import java.util.List;
public class CarDTO {
private long id;
private String carName;
private List<BuyerDTO> buyerDTOList;
private List<StoreDTO> storeDTOList;
public CarDTO(Car car){
this.id = car.getId();
this.carName = car.getCarName();
this.storeDTOList = car.getStores() == null ? null : car.getStores()
.stream()
.filter(x -> x.getCar().contains(car))
.map(StoreDTO::new)
.toList();
this.buyerDTOList = car.getBuyers() == null ? null : car.getBuyers()
.stream()
.map(BuyerDTO::new)
.toList();
}
public CarDTO(){}
public long getId() {
return id;
}
public String getCarName(){
return carName;
}
public List<BuyerDTO> getBuyerDTOList(){
return buyerDTOList;
}
public List<StoreDTO> getStoreDTOList(){
return storeDTOList;
}
}

View File

@ -0,0 +1,48 @@
package ru.ulsru.is.lab1.lab3.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulsru.is.lab1.lab3.service.StoreService;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/store")
public class StoreController {
private final StoreService storeService;
public StoreController(StoreService storeService){
this.storeService = storeService;
}
@PostMapping
public StoreDTO addStore(@RequestBody @Valid StoreDTO storeDTO) {
return new StoreDTO(storeService.addStore(storeDTO));
}
@PutMapping("/{id}")
public StoreDTO updateStore(@PathVariable Long id, @RequestBody @Valid StoreDTO storeDTO) {
return new StoreDTO(storeService.updateStore(id, storeDTO));
}
@DeleteMapping("/{id}")
public StoreDTO removeStore(@PathVariable Long id) {
return new StoreDTO(storeService.deleteStore(id));
}
@DeleteMapping
public void removeAllStores() {
storeService.deleteAllStores();
}
@GetMapping("/{id}")
public StoreDTO findStore(@PathVariable Long id) {
return new StoreDTO(storeService.findStore(id));
}
@GetMapping("/buyer/{id}")
public List<BuyerDTO> findBuyersOnCar(@PathVariable Long id){
return storeService.findAllBuyersProducedStore(id).stream().map(BuyerDTO::new).toList();
}
@GetMapping
public List<StoreDTO> findAllStore() {
return storeService.findAllStores().stream().map(StoreDTO::new).toList();
}
}

View File

@ -0,0 +1,33 @@
package ru.ulsru.is.lab1.lab3.controller;
import ru.ulsru.is.lab1.lab3.model.Store;
import java.util.List;
public class StoreDTO {
private long id;
private String storeName;
private List<CarDTO> carDTOList;
public StoreDTO(Store store){
this.id = store.getId();
this.storeName = store.getStoreName();
this.carDTOList = store.getCar() == null ? null : store.getCar()
.stream()
.filter(x -> x.getStores().contains(store.getId()))
.map(y -> new CarDTO(y))
.toList();
}
public StoreDTO() {
}
public long getId() {
return id;
}
public String getStoreName() {
return storeName;
}
public List<CarDTO> getCarDTOList(){
return carDTOList;
}
}

View File

@ -0,0 +1,59 @@
package ru.ulsru.is.lab1.lab3.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Objects;
@Entity
@Table(name = "buyer")
public class Buyer {
@Id
@GeneratedValue
private long id;
@NotNull(message = "First name can't be empty")
@Column(name = "first_name")
private String buyerFirstName;
@NotNull(message = "Second name can't be empty")
@Column(name = "second_name")
private String buyerSecondName;
public Buyer(){
}
public Buyer(String buyerFirstName, String buyerSecondName){
this.buyerFirstName = buyerFirstName;
this.buyerSecondName = buyerSecondName;
}
public Long getId(){return id;}
public String getBuyerFirstName(){
return buyerFirstName;
}
public String getBuyerSecondName(){
return buyerSecondName;
}
public void setBuyerFirstName(String buyerFirstName) {
this.buyerFirstName = buyerFirstName;
}
public void setBuyerSecondName(String buyerSecondName) {
this.buyerSecondName = buyerSecondName;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Buyer buyer = (Buyer) o;
return Objects.equals(id, buyer.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Buyer{" +
"id=" + id +
", buyerFirstName='" + buyerFirstName + '\'' +
", buyerSecondName='" + buyerSecondName + '\'' +
'}';
}
}

View File

@ -0,0 +1,105 @@
package ru.ulsru.is.lab1.lab3.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "car")
public class Car {
@Id
@GeneratedValue
private long id;
@NotNull(message = "Name can't be empty")
@Column(name = "name")
private String carName;
@OneToMany(cascade = {CascadeType.MERGE})
@JoinColumn(name = "buyers", nullable = true)
private List<Buyer> buyers;
@ManyToMany(cascade = { CascadeType.MERGE }, fetch = FetchType.EAGER)
@JoinTable(name = "cars_stores",
joinColumns = @JoinColumn(name = "car_fk"),
inverseJoinColumns = @JoinColumn(name = "store_fk"))
private List<Store> stores;
public Car(){
}
public Car(String carName, List<Store> stores, List<Buyer> buyers){
this.carName = carName;
this.stores = stores;
this.buyers = buyers;
}
public Long getId() {
return id;
}
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public List<Store> getStores() {
return stores;
}
public List<Buyer> getBuyers(){return buyers;}
public void setStores(List<Store> stores) {
this.stores = stores;
}
public void setBuyers(List<Buyer> buyers) {
this.buyers = buyers;
}
public void update(Car car){
this.carName = car.carName;
this.stores = car.getStores();
}
public void addStore(Store store){
if (stores == null){
this.stores = new ArrayList<>();
}
if (!stores.contains(store)) {
this.stores.add(store);
store.addCar(this);
}
}
public void removeStore(Store store){
if (stores.contains(store)) {
this.stores.remove(store);
store.removeCar(this);
}
}
public void addBuyer(Buyer buyer){
if (buyers == null){
this.buyers = new ArrayList<>();
}
if (!buyers.contains(buyer)) {
this.buyers.add(buyer);
}
}
public void removeBuyer(Buyer buyer){
if (buyers.contains(buyer)) {
this.buyers.remove(buyer);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Car car = (Car) o;
return Objects.equals(id, car.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Car{" +
"id=" + id +
", carName='" + carName + '\'' +
'}';
}
}

View File

@ -0,0 +1,79 @@
package ru.ulsru.is.lab1.lab3.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
public class Store {
@Id
@GeneratedValue
private Long id;
@NotNull(message = "Name can't be empty")
@Column(name = "storeName")
private String storeName;
@ManyToMany(mappedBy = "stores",cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
private List<Car> car;
public Store() {
}
public Store(String storeName) {
this.storeName = storeName;
}
public Long getId() {
return id;
}
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
public List<Car> getCar() {
return car;
}
public void setCar(List<Car> car) {
this.car = car;
}
public void addCar(Car car) {
if (this.car == null) {
this.car = new ArrayList<>();
}
if (!this.car.contains(car))
this.car.add(car);
}
public void removeCar(Car car) {
if (this.car.contains(car))
this.car.remove(car);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Store store = (Store) o;
return Objects.equals(id, store.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Store{" +
"id=" + id +
", storeName='" + storeName + '\'' +
'}';
}
}

View File

@ -0,0 +1,7 @@
package ru.ulsru.is.lab1.lab3.service;
public class BuyerNotFoundException extends RuntimeException {
public BuyerNotFoundException(Long id){
super(String.format("Buyer with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,67 @@
package ru.ulsru.is.lab1.lab3.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulsru.is.lab1.lab3.Respository.IBuyerRespository;
import ru.ulsru.is.lab1.lab3.controller.BuyerDTO;
import ru.ulsru.is.lab1.lab3.controller.CarDTO;
import ru.ulsru.is.lab1.lab3.model.Buyer;
import java.util.List;
import java.util.Optional;
@Service
public class BuyerService {
private final IBuyerRespository buyerRespository;
public BuyerService(IBuyerRespository buyerRespositroy){
this.buyerRespository = buyerRespositroy;
}
@Transactional
public Buyer addBuyer(BuyerDTO buyerDTO) {
final Buyer buyer = new Buyer(buyerDTO.getBuyerFirstName(), buyerDTO.getBuyerSecondName());
buyerRespository.save(buyer);
return buyer;
}
@Transactional(readOnly = true)
public Buyer findBuyer(Long id) {
final Optional<Buyer> buyer = buyerRespository.findById(id);
return buyer.orElseThrow(()->new BuyerNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Buyer> findAllBuyerByid(CarDTO carDTO) {
return buyerRespository
.findAllById(carDTO
.getBuyerDTOList()
.stream()
.map(x->x.getId())
.toList());
}
@Transactional(readOnly = true)
public List<Buyer> findAllBuyers() {
return buyerRespository
.findAll();
}
@Transactional
public Buyer updateBuyer(Long id, BuyerDTO buyer) {
final Buyer currentBuyer = findBuyer(id);
currentBuyer.setBuyerFirstName(buyer.getBuyerFirstName());
currentBuyer.setBuyerSecondName(buyer.getBuyerSecondName());
buyerRespository.save(currentBuyer);
return currentBuyer;
}
@Transactional
public Buyer deleteBuyer(Long id) {
final Buyer currentBuyer = findBuyer(id);
buyerRespository.delete(currentBuyer);
return currentBuyer;
}
@Transactional
public void deleteAllBuyers() {
buyerRespository.deleteAll();
}
}

View File

@ -0,0 +1,7 @@
package ru.ulsru.is.lab1.lab3.service;
public class CarNotFoundException extends RuntimeException{
public CarNotFoundException(Long id){
super(String.format("Car with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,84 @@
package ru.ulsru.is.lab1.lab3.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulsru.is.lab1.lab3.Respository.ICarRespository;
import ru.ulsru.is.lab1.lab3.controller.CarDTO;
import ru.ulsru.is.lab1.lab3.model.Store;
import ru.ulsru.is.lab1.lab3.model.Buyer;
import ru.ulsru.is.lab1.lab3.model.Car;
import java.util.List;
import java.util.Optional;
@Service
public class CarService {
private final ICarRespository carRespository;
private final StoreService storeService;
private final BuyerService buyerService;
public CarService(ICarRespository carRespository,
StoreService storeService,
BuyerService buyerService
){
this.carRespository = carRespository;
this.storeService = storeService;
this.buyerService = buyerService;
}
@Transactional
public Car addCar(CarDTO carDTO) {
List<Store> stores = storeService.findAllStoresById(carDTO);
List<Buyer> buyers = buyerService.findAllBuyerByid(carDTO);
final Car car = new Car(
carDTO.getCarName(), stores, buyers);
carRespository.save(car);
return car;
}
@Transactional
public Car addBuyer(CarDTO carDTO, List<Buyer> buyers){
final Car currentCar = findCar(carDTO.getId());
currentCar.setBuyers(buyers);
return currentCar;
}
@Transactional
public Car addStore(CarDTO carDTO, List<Store> stores){
final Car currentCar = findCar(carDTO.getId());
currentCar.setStores(stores);
return currentCar;
}
@Transactional(readOnly = true)
public Car findCar(Long id) {
final Optional<Car> car = carRespository.findById(id);
return car.orElseThrow(() -> new CarNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Car> findAllCars() {
return carRespository.findAll();
}
@Transactional
public Car updateCar(Long id, CarDTO carDTO) {
final Car currentCar = findCar(id);
currentCar.setCarName(carDTO.getCarName());
List<Store> newStores = storeService.findAllStoresById(carDTO);
List<Buyer> newBuyers = buyerService.findAllBuyerByid(carDTO);
currentCar.setStores(newStores);
currentCar.setBuyers(newBuyers);
carRespository.save(currentCar);
return currentCar;
}
@Transactional
public Car deleteCar(Long id) {
final Car currentCar = findCar(id);
carRespository.delete(currentCar);
return currentCar;
}
@Transactional
public void deleteAllCars() {
carRespository.deleteAll();
}
}

View File

@ -0,0 +1,7 @@
package ru.ulsru.is.lab1.lab3.service;
public class StoreNotFoundException extends RuntimeException{
public StoreNotFoundException(Long id){
super(String.format("Store with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,75 @@
package ru.ulsru.is.lab1.lab3.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulsru.is.lab1.lab3.Respository.IStoreRespository;
import ru.ulsru.is.lab1.lab3.controller.StoreDTO;
import ru.ulsru.is.lab1.lab3.controller.CarDTO;
import ru.ulsru.is.lab1.lab3.model.Store;
import ru.ulsru.is.lab1.lab3.model.Buyer;
import ru.ulsru.is.lab1.lab3.model.Car;
import java.util.List;
import java.util.Optional;
@Service
public class StoreService {
private final IStoreRespository storeRespository;
public StoreService(IStoreRespository storeRespository){
this.storeRespository = storeRespository;
}
@Transactional
public Store addStore(StoreDTO storeDTO) {
Store store =new Store(storeDTO.getStoreName());
storeRespository.save(store);
return store;
}
@Transactional(readOnly = true)
public Store findStore(Long id) {
final Optional<Store> store = storeRespository.findById(id);
return store.orElseThrow(()->new StoreNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Store> findAllStores() {
return storeRespository.findAll();
}
@Transactional(readOnly = true)
public List<Store> findAllStoresById(CarDTO carDTO) {
return storeRespository
.findAllById(carDTO
.getStoreDTOList()
.stream()
.map(x -> x.getId())
.toList());
}
@Transactional
public Store updateStore(Long id, StoreDTO storeDTO) {
final Store currentStore = findStore(id);
currentStore.setStoreName(storeDTO.getStoreName());
storeRespository.save(currentStore);
return currentStore;
}
@Transactional
public Store deleteStore(Long id) {
final Store currentStore = findStore(id);
int size = currentStore.getCar().size();
for (int i = 0; i < size; i++) {
Car temp = currentStore.getCar().get(i);
temp.removeStore(currentStore);
currentStore.removeCar(temp);
}
storeRespository.delete(currentStore);
return currentStore;
}
@Transactional
public List<Buyer> findAllBuyersProducedStore(Long id){
return storeRespository.getBuyers(findStore(id));
}
@Transactional
public void deleteAllStores() {
storeRespository.deleteAll();
}
}

View File

@ -0,0 +1,41 @@
//package ru.ulsru.is.lab1.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.ulsru.is.lab1.lab3.service.ProductNotFoundException;
//import ru.ulsru.is.lab1.lab3.service.WorkerNotFoundException;
//import ru.ulsru.is.lab1.lab3.service.WorkplaceNotFoundException;
//import ru.ulsru.is.lab1.util.validation.ValidationException;
//import java.util.stream.Collectors;
//
// @ControllerAdvice
// public class AdviceController {
// @ExceptionHandler({
// WorkerNotFoundException.class,
// ProductNotFoundException.class,
// WorkplaceNotFoundException.class,
// ValidationException.class
// })
// public ResponseEntity<Object> handleException(Throwable e) {
// return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
// }
//
// @ExceptionHandler(MethodArgumentNotValidException.class)
// public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException e) {
// final ValidationException validationException = new ValidationException(
// e.getBindingResult().getAllErrors().stream()
// .map(DefaultMessageSourceResolvable::getDefaultMessage)
// .collect(Collectors.toSet()));
// return handleException(validationException);
// }
//
// @ExceptionHandler(Exception.class)
// public ResponseEntity<Object> handleUnknownException(Throwable e) {
// e.printStackTrace();
// return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
// }
// }

View File

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

View File

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

View File

@ -1 +1,12 @@
spring.main.banner-mode=off
server.port=8080
server.tomcat.relaxed-query-chars=|,{,},[,]
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false

View File

@ -1,13 +0,0 @@
package ru.ulstu.is.lab1;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Lab1ApplicationTests {
@Test
void contextLoads() {
}
}