Лаб4 показана

This commit is contained in:
Кашин Максим 2023-04-17 22:54:30 +04:00
parent e9d10a9578
commit 2d6c7a0029
33 changed files with 175 additions and 257 deletions

View File

@ -1,10 +1,10 @@
plugins { plugins {
id 'java' id 'java'
id 'org.springframework.boot' version '2.7.8' id 'org.springframework.boot' version '3.0.2'
id 'io.spring.dependency-management' version '1.0.15.RELEASE' id 'io.spring.dependency-management' version '1.1.0'
} }
group = 'ru.ulstu.is' group = 'com.example'
version = '0.0.1-SNAPSHOT' version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17' sourceCompatibility = '17'

BIN
data.mv.db Normal file

Binary file not shown.

View File

@ -1,4 +1,3 @@
import Main from './components/Main.jsx';
import React from "react"; import React from "react";
import { useRoutes, Outlet, BrowserRouter } from 'react-router-dom'; import { useRoutes, Outlet, BrowserRouter } from 'react-router-dom';
import Cars from './components/Cars.jsx'; import Cars from './components/Cars.jsx';
@ -14,10 +13,10 @@ function Router(props) {
function App() { function App() {
const routes = [ const routes = [
{ index: true, element: <Buyers /> }, { index: true, element: <Buyers /> },
{ path: '/', element: <Buyers />, label: 'ГЛАВНОЕ' }, { path: '/', element: <Buyers />},
{ path: '/cars', element: <Cars />, label: 'Сотрудники' }, { path: '/cars', element: <Cars />, label: 'Машины' },
{ path: '/buyers', element: <Buyers />, label: 'Компании' }, { path: '/buyers', element: <Buyers />, label: 'Покупатель' },
{ path: '/stores', element: <Stores />, label: 'Должности' }, { path: '/stores', element: <Stores />, label: 'Магазины' },
{ path: '/buyer/:id', element: <OneBuyer />}, { path: '/buyer/:id', element: <OneBuyer />},
]; ];
const links = routes.filter(route => route.hasOwnProperty('label')); const links = routes.filter(route => route.hasOwnProperty('label'));

View File

@ -10,12 +10,12 @@ import Store from '../models/Store';
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
export default function Buyers(props) { export default function Companies(props) {
const headers = [ const headers = [
{name: 'name', label: "Название"}, {name: 'name', label: "Название"},
{name: 'countCars', label: "Сотрудники"}, {name: 'countCars', label: "Машины"},
]; ];
const nameCatalog = "Компании"; const nameCatalog = "Покупатели";
const url = '/buyer'; const url = '/buyer';
const requestParams = '?name=nameData'; const requestParams = '?name=nameData';
@ -99,7 +99,7 @@ export default function Buyers(props) {
<Form.Label>Название</Form.Label> <Form.Label>Название</Form.Label>
<Form.Control name="name" value={data.name} type="input" placeholder="Enter text" onChange={handleFormChange} required/> <Form.Control name="name" value={data.name} type="input" placeholder="Enter text" onChange={handleFormChange} required/>
</Form.Group> </Form.Group>
<Button variant="primary" type="submit"> <Button variant="info" type="submit">
Отправить Отправить
</Button> </Button>
</Form>; </Form>;
@ -108,15 +108,15 @@ export default function Buyers(props) {
const [showModalForm, setShowChoosing] = useState(false); const [showModalForm, setShowChoosing] = useState(false);
const formChooseBuyer = <Form onSubmit={redirectToBuyer}> const formChooseBuyer = <Form onSubmit={redirectToBuyer}>
<Form.Group className="mb-3" controlId="name"> <Form.Group className="mb-3" controlId="name">
<Form.Label>Компания</Form.Label> <Form.Label>Покупатель</Form.Label>
<Form.Select name="name_select" type="input" onChange={(e) => {setChosenBuyer(e.target.value)}} required> <Form.Select name="name_select" type="input" onChange={(e) => {setChosenBuyer(e.target.value)}} required>
<option selected disabled>Выберите компанию</option> <option selected disabled>Выберите покупателя</option>
{ {
items.map((buyer) => <option key={`buyer_${buyer.id}`} value={`${buyer.id}`}>{`${buyer.name}`}</option>) items.map((buyer) => <option key={`buyer_${buyer.id}`} value={`${buyer.id}`}>{`${buyer.name}`}</option>)
} }
</Form.Select> </Form.Select>
</Form.Group> </Form.Group>
<Button variant="primary" type="submit"> <Button variant="info" type="submit">
Перейти Перейти
</Button> </Button>
</Form>; </Form>;
@ -137,8 +137,8 @@ export default function Buyers(props) {
} }
return <div className="container-lg pt-5 min-vh-100"> return <div className="container-lg pt-5 min-vh-100">
<Button onClick={showModalFormChoosing} variant="info">Перейти к компании</Button> <Button onClick={showModalFormChoosing} variant="info">Перейти к покупателю</Button>
<ModalForm show={showModalForm} onClose={unshowModalFormChoosing} modalTitle={"Выбор компаниии"} form={formChooseBuyer}></ModalForm> <ModalForm show={showModalForm} onClose={unshowModalFormChoosing} modalTitle={"Выбор покупателя"} form={formChooseBuyer}></ModalForm>
<Catalog name={nameCatalog} <Catalog name={nameCatalog}
headers={headers} headers={headers}
items={items} items={items}

View File

@ -6,15 +6,15 @@ import DataService from '../services/DataService';
import Catalog from "./Catalog.jsx"; import Catalog from "./Catalog.jsx";
export default function Cars(props) { export default function Cars(props) {
const headers = [ const headers = [
{name: 'surname', label: "Фамилия"}, {name: 'surname', label: "Модель"},
{name: 'name', label: "Имя"}, {name: 'name', label: "Марка"},
{name: 'phoneNumber', label: "Номер телефона"}, {name: 'price', label: "Цена"},
{name: 'storesString', label: 'Должности'} {name: 'storesString', label: 'Магазин'}
]; ];
const nameCatalog = "Сотрудники"; const nameCatalog = "Машины";
const [items, setItems] = useState([]); const [items, setItems] = useState([]);
const url = '/car'; const url = '/car';
const requestParams = '?name=nameData&surname=surnameData&phoneNumber=phoneNameData'; const requestParams = '?name=nameData&surname=surnameData&price=phoneNameData';
const [data, setData] = useState(new Car()); const [data, setData] = useState(new Car());
const [isEditing, setEditing] = useState(false); const [isEditing, setEditing] = useState(false);
useEffect(() => { useEffect(() => {
@ -31,7 +31,7 @@ export default function Cars(props) {
DataService.create(url +requestParams DataService.create(url +requestParams
.replace("nameData", data.name) .replace("nameData", data.name)
.replace("surnameData", data.surname) .replace("surnameData", data.surname)
.replace("phoneNameData", data.phoneNumber)) .replace("phoneNameData", data.price))
.then(() => loadItems()); .then(() => loadItems());
} }
@ -48,7 +48,7 @@ export default function Cars(props) {
DataService.update(url + "/" + data.id + requestParams DataService.update(url + "/" + data.id + requestParams
.replace("nameData", data.name) .replace("nameData", data.name)
.replace("surnameData", data.surname) .replace("surnameData", data.surname)
.replace("phoneNameData", data.phoneNumber)).then(() => loadItems()); .replace("phoneNameData", data.price)).then(() => loadItems());
} }
@ -88,18 +88,20 @@ export default function Cars(props) {
// которая передается дальше в абстрактный компонент Catalog в качестве props.form // которая передается дальше в абстрактный компонент Catalog в качестве props.form
const form = <Form onSubmit={submitForm}> const form = <Form onSubmit={submitForm}>
<Form.Group className="mb-3" controlId="name"> <Form.Group className="mb-3" controlId="name">
<Form.Label>Фамилия</Form.Label> <Form.Label>Модель</Form.Label>
<Form.Control name="surname" value={data.surname} type="input" placeholder="Enter text" onChange={handleFormChange} required/> <Form.Control name="surname" value={data.surname} type="input" placeholder="Enter text" onChange={handleFormChange} required/>
<Form.Label>Имя</Form.Label> <Form.Label>Марка</Form.Label>
<Form.Control name="name" value={data.name} type="input" placeholder="Enter text" onChange={handleFormChange} required/> <Form.Control name="name" value={data.name} type="input" placeholder="Enter text" onChange={handleFormChange} required/>
<Form.Label>Номер телефона</Form.Label> <Form.Label>Цена</Form.Label>
<Form.Control name="phoneNumber" value={data.phoneNumber} type="input" placeholder="Enter text" onChange={handleFormChange} required/> <Form.Control name="price" value={data.price} type="input" placeholder="Enter text" onChange={handleFormChange} required/>
</Form.Group> </Form.Group>
<Button variant="primary" type="submit"> <Button variant="info" type="submit">
Отправить Отправить
</Button> </Button>
</Form> </Form>
return <div className="container-lg pt-5 min-vh-100"> return <div className="container-lg pt-5 min-vh-100">
<Catalog name={nameCatalog} <Catalog name={nameCatalog}
headers={headers} headers={headers}

View File

@ -31,7 +31,7 @@ export default function Catalog(props) {
return <> return <>
<div>{props.name}</div> <div>{props.name}</div>
<Button variant="success" onClick={handleAdd}>Добавить</Button> <Button variant="info" onClick={handleAdd}>Добавить</Button>
<Table <Table
headers={props.headers} headers={props.headers}
items={props.items} items={props.items}

View File

@ -1,76 +0,0 @@
import { Button } from "bootstrap";
import { useState, useEffect } from 'react';
import DataService from '../services/DataService';
export default function Main(props) {
const url = 'http://localhost:8080';
const urlRandomNumber = '/getRandomNumber';
const urlCalc = '/sum?val1=num1&val2=num2';
const urlLength = '/length?name=strName';
const urlUpperCase = '/upperCase?word=strWord';
function get(url2) {
fetch(
url + url2,
{
method: 'GET',
headers: { 'Content-Type': 'application/json' },
}
).then(resp => resp.text()).then(alert);
}
function getRandomNumber() {
get(urlRandomNumber);
}
function req_calc() {
get(urlCalc.replace("num1", num1).replace("num2", num2));
}
const [num1, setnum1] = useState('');
const [num2, setnum2] = useState('');
function valueChanged1(event) {
console.log(event.target);
setnum1(event.target.value);
}
function valueChanged2(event) {
setnum2(event.target.value);
}
function req_length() {
get(urlLength.replace("strName", strName));
}
const [strName, setName] = useState('');
function valueChangedName(event) {
setName(event.target.value);
}
function req_upperCase() {
get(urlUpperCase.replace("strWord", strWord));
}
const [strWord, setWord] = useState('');
function valueChangedWord(event) {
setWord(event.target.value);
}
return <div>
<h1>Сайт...</h1>
<div className="row">
<h1>Рандомное число</h1>
<button className="btn primary" onClick={getRandomNumber}>Get Random Number</button>
</div>
<div className="row">
<h1>Калькулятор</h1>
<input type="text" onChange={valueChanged1}></input>
<input type="text" onChange={valueChanged2}></input>
<button onClick={req_calc}>Press</button>
</div>
<div className="row">
<h1>Посчитать длину строки</h1>
<input type="text" onChange={valueChangedName}></input>
<button onClick={req_length}>Press</button>
</div>
<div className="row">
<h1>Перевести слово в верхний регистр</h1>
<input type="text" onChange={valueChangedWord}></input>
<button onClick={req_upperCase}>Press</button>
</div>
</div>
}

View File

@ -31,8 +31,8 @@ export default function OneBuyer(props) {
const headersEmp = [ const headersEmp = [
{name: 'surname', label: "Фамилия"}, {name: 'surname', label: "Фамилия"},
{name: 'name', label: "Имя"}, {name: 'name', label: "Имя"},
{name: 'storesString', label: 'Должности'}, {name: 'storesString', label: 'Магазин'},
{name: 'phoneNumber', label: "Номер телефона"} {name: 'price', label: "Цена"}
]; ];
useEffect(() => { useEffect(() => {
@ -120,7 +120,7 @@ export default function OneBuyer(props) {
const [storesChosen, setStoreEmp] = useState([]); const [storesChosen, setStoreEmp] = useState([]);
function checkBoxChanged(e) { function checkBoxChanged(e) {
// если чекбокс был выбран, то дабавляем в массив должность // если чекбокс был выбран, то дабавляем в массив магазин
if (e.target.checked) if (e.target.checked)
{ {
storesChosen.push(e.target.value); storesChosen.push(e.target.value);
@ -145,7 +145,7 @@ export default function OneBuyer(props) {
for (let i = 0; i < storesEmp.length; i++) { for (let i = 0; i < storesEmp.length; i++) {
if (storesChosen.indexOf(''+storesEmp[i].id) == -1) { if (storesChosen.indexOf(''+storesEmp[i].id) == -1) {
// удаление должности // удаление магазина
DataService.update(urlDelPos.replace("id",car.id) + requestParamsStore DataService.update(urlDelPos.replace("id",car.id) + requestParamsStore
.replace("posId", storesEmp[i].id)) .replace("posId", storesEmp[i].id))
.then(() => loadBuyer()); .then(() => loadBuyer());
@ -155,15 +155,15 @@ export default function OneBuyer(props) {
const formHire = <Form onSubmit={formHireSubmit}> const formHire = <Form onSubmit={formHireSubmit}>
<Form.Group className="mb-3" controlId="car"> <Form.Group className="mb-3" controlId="car">
<Form.Label>Сотрудник</Form.Label> <Form.Label>Машина</Form.Label>
<Form.Select name="car_select" type="input" onChange={carChosenFree} required> <Form.Select name="car_select" type="input" onChange={carChosenFree} required>
<option selected disabled>Выберите сотрудника</option> <option selected disabled>Выберите машину</option>
{ {
itemsEmpFree.map((e) => <option key={`emp_${e.id}`} value={`${e.id}`}>{`${e.surname} ${e.name}`}</option>) itemsEmpFree.map((e) => <option key={`emp_${e.id}`} value={`${e.id}`}>{`${e.surname} ${e.name}`}</option>)
} }
</Form.Select> </Form.Select>
</Form.Group> </Form.Group>
<Button variant="primary" type="submit"> <Button class="btn btn-outline-info" type="submit">
Отправить Отправить
</Button> </Button>
</Form>; </Form>;
@ -171,31 +171,31 @@ export default function OneBuyer(props) {
const formDismiss = <Form onSubmit={formDismissSubmit}> const formDismiss = <Form onSubmit={formDismissSubmit}>
<Form.Group className="mb-3" controlId="car"> <Form.Group className="mb-3" controlId="car">
<Form.Label>Сотрудник</Form.Label> <Form.Label>Машина</Form.Label>
<Form.Select name="car_select" type="input" onChange={carChosenBusy} required> <Form.Select name="car_select" type="input" onChange={carChosenBusy} required>
<option selected disabled>Выберите сотрудника</option> <option selected disabled>Выберите машину</option>
{ {
itemsEmpBuyer.map((e) => <option key={`emp_${e.id}`} value={`${e.id}`}>{`${e.surname} ${e.name}`}</option>) itemsEmpBuyer.map((e) => <option key={`emp_${e.id}`} value={`${e.id}`}>{`${e.surname} ${e.name}`}</option>)
} }
</Form.Select> </Form.Select>
</Form.Group> </Form.Group>
<Button variant="primary" type="submit"> <Button class="btn btn-outline-info" type="submit">
Отправить Отправить
</Button> </Button>
</Form>; </Form>;
const formCheckBoxesStore = <Form onSubmit={formChooseStoresSubmit}> const formCheckBoxesStore = <Form onSubmit={formChooseStoresSubmit}>
<Form.Group className="mb-3" controlId="car"> <Form.Group className="mb-3" controlId="car">
<Form.Label>Сотрудник</Form.Label> <Form.Label>Машина</Form.Label>
<Form.Select name="car_select" type="input" onChange={carChosenBusy} required> <Form.Select name="car_select" type="input" onChange={carChosenBusy} required>
<option selected disabled>Выберите сотрудника</option> <option selected disabled>Выберите машину</option>
{ {
itemsEmpBuyer.map((e) => <option key={`emp_${e.id}`} value={`${e.id}`}>{`${e.surname} ${e.name}`}</option>) itemsEmpBuyer.map((e) => <option key={`emp_${e.id}`} value={`${e.id}`}>{`${e.surname} ${e.name}`}</option>)
} }
</Form.Select> </Form.Select>
</Form.Group> </Form.Group>
<Form.Group className="mb-3" controlId="store"> <Form.Group className="mb-3" controlId="store">
<Form.Label>Должности</Form.Label> <Form.Label>Магазин</Form.Label>
<div className={`${styles.prokrutka}`}> <div className={`${styles.prokrutka}`}>
{ {
itemsPos.map((p) => <div style={{width: `150 px`}}> itemsPos.map((p) => <div style={{width: `150 px`}}>
@ -207,29 +207,19 @@ export default function OneBuyer(props) {
} }
</div> </div>
</Form.Group> </Form.Group>
<Button variant="primary" type="submit"> <Button class="btn btn-outline-info" type="submit">
Отправить Отправить
</Button> </Button>
</Form> </Form>
if (!buyer) {
return <div><h1>Компания не найдена</h1>
<Link to='/buyers'>
<Button variant="info">Назад</Button>
</Link>
</div>
}
return <div className="container-lg pt-5 min-vh-100"> return <div className="container-lg pt-5 min-vh-100">
<Link to='/buyers'>
<Button variant="info">Назад</Button>
</Link>
<h1>Название: {buyer.name}</h1> <h1>Название: {buyer.name}</h1>
<h2>Количество сотрудников: {buyer.countCars}</h2> <h2>Количество машин: {buyer.countCars}</h2>
<Button name="Найм" onClick={showModalFormHire} variant="success">Нанять сотрудника</Button> <Button name="Добавить" variant="info" onClick={showModalFormHire} >Добавить машину</Button>
<Button name='Увольнение' onClick={showModalFormDismiss} variant="danger">Уволить сотрудника</Button> <Button name='Удалить' variant="info" onClick={showModalFormDismiss} >Удалить машину</Button>
<Button name='Назначение должности' onClick={showModalFormChooseStore} variant="info">Назначение должности</Button> <Button name='Назначение магазина'variant="info" onClick={showModalFormChooseStore}>Назначение магазина</Button>
<div > <div >
<table className={`table table-hover`}> <table className={`table table-condensed`}>
<thead> <thead>
<tr> <tr>
{ {
@ -250,7 +240,7 @@ export default function OneBuyer(props) {
</div> </div>
<ModalForm show={isShowHire} onClose={unshowModalFormHire} modalTitle={"Найм"} form={formHire}></ModalForm> <ModalForm show={isShowHire} onClose={unshowModalFormHire} modalTitle={"Найм"} form={formHire}></ModalForm>
<ModalForm show={isShowDismiss} onClose={unshowModalFormDismiss} modalTitle={"Увольнение"} form={formDismiss}></ModalForm> <ModalForm show={isShowDismiss} onClose={unshowModalFormDismiss} modalTitle={"Увольнение"} form={formDismiss}></ModalForm>
<ModalForm show={isShowChooseStore} onClose={unshowModalFormChooseStore} modalTitle={"Управление должностями"} form={formCheckBoxesStore}></ModalForm> <ModalForm show={isShowChooseStore} onClose={unshowModalFormChooseStore} modalTitle={"Управление магазинами"} form={formCheckBoxesStore}></ModalForm>
</div> </div>
} }

View File

@ -1,6 +1,6 @@
.prokrutka { .prokrutka {
background: #fff; /* цвет фона, белый */ background: #9c9c9c; /* цвет фона, белый */
border: 1px solid #C1C1C1; /* размер и цвет границы блока */ border: 1px solid #000000; /* размер и цвет границы блока */
overflow: auto; overflow: auto;
width:200px; width:200px;
height:100px; height:100px;

View File

@ -11,7 +11,7 @@ export default function Stores(props) {
{name: 'name', label: "Название"}, {name: 'name', label: "Название"},
]; ];
const nameCatalog = "Должности"; const nameCatalog = "Магазин";
const url = '/store'; const url = '/store';
const requestParams = '?name=nameData'; const requestParams = '?name=nameData';
@ -88,7 +88,7 @@ export default function Stores(props) {
<Form.Label>Название</Form.Label> <Form.Label>Название</Form.Label>
<Form.Control name="name" value={data.name} type="input" placeholder="Enter text" onChange={handleFormChange} required/> <Form.Control name="name" value={data.name} type="input" placeholder="Enter text" onChange={handleFormChange} required/>
</Form.Group> </Form.Group>
<Button variant="primary" type="submit"> <Button variant="info" type="submit">
Отправить Отправить
</Button> </Button>
</Form> </Form>

View File

@ -5,7 +5,7 @@ import Navbar from 'react-bootstrap/Navbar';
export default function Header(props) { export default function Header(props) {
return ( return (
<Navbar collapseOnSelect expand="lg" bg="dark" variant="dark"> <Navbar collapseOnSelect expand="lg" bg="white" variant="white">
<Container className='lg justify-content-center'> <Container className='lg justify-content-center'>
<Navbar.Toggle aria-controls="responsive-navbar-nav" /> <Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav"> <Navbar.Collapse id="responsive-navbar-nav">

View File

@ -13,6 +13,6 @@ export default function ItemTable(props) {
} }
{props.isOnlyView || <td key={`controls_${props.item.id}`}> {props.isOnlyView || <td key={`controls_${props.item.id}`}>
<Button variant="info" onClick={edit}>Редактировать</Button> <Button variant="info" onClick={edit}>Редактировать</Button>
<Button variant="danger" onClick={remove}>Удалить</Button></td>} <Button variant="info" onClick={remove}>Удалить</Button></td>}
</tr> </tr>
} }

View File

@ -2,9 +2,9 @@ import Car from "./Car";
export default class Buyer { export default class Buyer {
constructor(data) { constructor(data) {
this.id = data?.id; this.id = data?.id;
this.name = data?.name || ''; this.name = data?.name || '';
this.cars = Array.isArray(data?.cars) ? data?.cars.map((e) => new Car(e)) || [] : []; this.cars = data?.cars.map((e) => new Car(e)) || '';
this.countCars = ''; this.countCars = '';
if (this.cars !== '') { if (this.cars !== '') {
this.countCars = this.cars.length; this.countCars = this.cars.length;

View File

@ -5,7 +5,7 @@ export default class Car {
this.id = data?.id; this.id = data?.id;
this.surname = data?.surname || ''; this.surname = data?.surname || '';
this.name = data?.name || ''; this.name = data?.name || '';
this.phoneNumber = data?.phoneNumber || ''; this.price = data?.price || '';
this.stores = data?.stores.map((p) => new Store(p)) || ''; this.stores = data?.stores.map((p) => new Store(p)) || '';
this.storesString = ''; this.storesString = '';
if (this.stores !== '') { if (this.stores !== '') {

View File

@ -1 +1 @@
rootProject.name = 'lab1' rootProject.name = 'springip'

View File

@ -1,12 +1,13 @@
package ru.ulstu.is.lab1; package com.example.springip;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication @SpringBootApplication
public class Lab1Application { public class SpringipApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(Lab1Application.class, args); SpringApplication.run(SpringipApplication.class, args);
} }
}
}

View File

@ -1,4 +1,4 @@
package ru.ulstu.is.lab1; package com.example.springip;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

View File

@ -1,10 +1,10 @@
package ru.ulstu.is.lab1.controller; package com.example.springip.lab3.controller;
import ru.ulstu.is.lab1.dto.BuyerDto; import com.example.springip.lab3.dto.BuyerDto;
import ru.ulstu.is.lab1.dto.CarDto; import com.example.springip.lab3.dto.CarDto;
import ru.ulstu.is.lab1.models.Car; import com.example.springip.lab3.models.Car;
import ru.ulstu.is.lab1.service.BuyerService; import com.example.springip.lab3.service.BuyerService;
import ru.ulstu.is.lab1.service.CarService; import com.example.springip.lab3.service.CarService;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@ -26,13 +26,13 @@ public class BuyerController {
} }
@GetMapping("/{id}/cars") @GetMapping("/{id}/cars")
public List<CarDto> getBuyerCars(@PathVariable long id) { public List<CarDto> getBuyerCaes(@PathVariable long id) {
return buyerService.findBuyer(id).getCars().stream().map(CarDto::new).toList(); return buyerService.findBuyer(id).getCars().stream().map(CarDto::new).toList();
} }
@GetMapping @GetMapping
public List<BuyerDto> getAllBuyers() { public List<BuyerDto> getAllCompanies() {
return buyerService.findAllBuyers().stream() return buyerService.findAllCompanies().stream()
.map(BuyerDto::new) .map(BuyerDto::new)
.toList(); .toList();
} }
@ -44,7 +44,7 @@ public class BuyerController {
@PutMapping("/{id}") @PutMapping("/{id}")
public BuyerDto update(@PathVariable Long id, public BuyerDto update(@PathVariable Long id,
@RequestParam("name") String name) { @RequestParam("name") String name) {
return new BuyerDto(buyerService.updateBuyer(id, name)); return new BuyerDto(buyerService.updateBuyer(id, name));
} }
@ -60,9 +60,9 @@ public class BuyerController {
} }
@PutMapping("/{id}/dismiss") @PutMapping("/{id}/dismiss")
public CarDto dismiss(@PathVariable Long id, @RequestParam Long carId) { public void dismiss(@PathVariable Long id, @RequestParam Long carId) {
Car e = carService.findCar(carId); Car e = carService.findCar(carId);
return new CarDto(buyerService.deleteCar(id, e)); buyerService.deleteCar(id, e);
} }
} }

View File

@ -1,9 +1,9 @@
package ru.ulstu.is.lab1.controller; package com.example.springip.lab3.controller;
import ru.ulstu.is.lab1.dto.CarDto; import com.example.springip.lab3.dto.CarDto;
import ru.ulstu.is.lab1.models.Store; import com.example.springip.lab3.models.Store;
import ru.ulstu.is.lab1.service.CarService; import com.example.springip.lab3.service.CarService;
import ru.ulstu.is.lab1.service.StoreService; import com.example.springip.lab3.service.StoreService;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@ -33,20 +33,20 @@ public class CarController {
@PostMapping @PostMapping
public CarDto createCar(@RequestParam("name") String name, public CarDto createCar(@RequestParam("name") String name,
@RequestParam("surname") String surname, @RequestParam("surname") String surname,
@RequestParam("phoneNumber") String phoneNumber) { @RequestParam("price") String price) {
return new CarDto(carService.addCar( return new CarDto(carService.addCar(
surname, surname,
name, name,
phoneNumber)); price));
} }
@PutMapping("/{id}") @PutMapping("/{id}")
public CarDto updateCar(@PathVariable Long id, public CarDto updateCar(@PathVariable Long id,
@RequestParam("name") String name, @RequestParam("name") String name,
@RequestParam("surname") String surname, @RequestParam("surname") String surname,
@RequestParam("phoneNumber") String phoneNumber) { @RequestParam("price") String price) {
return new CarDto(carService.updateCar(id, surname, name, phoneNumber)); return new CarDto(carService.updateCar(id, surname, name, price));
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
@ -56,7 +56,7 @@ public class CarController {
@PutMapping("/{id}/addPos") @PutMapping("/{id}/addPos")
public CarDto addStore(@PathVariable Long id, public CarDto addStore(@PathVariable Long id,
@RequestParam("store") Long store) { @RequestParam("store") Long store) {
Store p = storeService.findStore(store); Store p = storeService.findStore(store);
if (p == null) if (p == null)
return null; return null;
@ -64,7 +64,7 @@ public class CarController {
} }
@PutMapping("/{id}/delPos") @PutMapping("/{id}/delPos")
public CarDto delStore(@PathVariable Long id, public CarDto delStore(@PathVariable Long id,
@RequestParam("store") Long store) { @RequestParam("store") Long store) {
Store p = storeService.findStore(store); Store p = storeService.findStore(store);
if (p == null) if (p == null)
return null; return null;

View File

@ -1,7 +1,7 @@
package ru.ulstu.is.lab1.controller; package com.example.springip.lab3.controller;
import ru.ulstu.is.lab1.dto.StoreDto; import com.example.springip.lab3.dto.StoreDto;
import ru.ulstu.is.lab1.service.StoreService; import com.example.springip.lab3.service.StoreService;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@ -21,7 +21,7 @@ public class StoreController {
} }
@GetMapping @GetMapping
public List<StoreDto> getAllBuyers() { public List<StoreDto> getAllCompanies() {
return storeService.findAllStores().stream() return storeService.findAllStores().stream()
.map(StoreDto::new) .map(StoreDto::new)
.toList(); .toList();
@ -34,7 +34,7 @@ public class StoreController {
@PutMapping("/{id}") @PutMapping("/{id}")
public StoreDto update(@PathVariable Long id, public StoreDto update(@PathVariable Long id,
@RequestParam("name") String name) { @RequestParam("name") String name) {
return new StoreDto(storeService.updateStore(id, name)); return new StoreDto(storeService.updateStore(id, name));
} }

View File

@ -1,6 +1,6 @@
package ru.ulstu.is.lab1.dao; package com.example.springip.lab3.dao;
import ru.ulstu.is.lab1.models.Buyer; import com.example.springip.lab3.models.Buyer;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional; import java.util.Optional;

View File

@ -1,6 +1,6 @@
package ru.ulstu.is.lab1.dao; package com.example.springip.lab3.dao;
import ru.ulstu.is.lab1.models.Car; import com.example.springip.lab3.models.Car;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List; import java.util.List;

View File

@ -1,6 +1,6 @@
package ru.ulstu.is.lab1.dao; package com.example.springip.lab3.dao;
import ru.ulstu.is.lab1.models.Store; import com.example.springip.lab3.models.Store;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional; import java.util.Optional;

View File

@ -1,6 +1,6 @@
package ru.ulstu.is.lab1.dto; package com.example.springip.lab3.dto;
import ru.ulstu.is.lab1.models.Buyer; import com.example.springip.lab3.models.Buyer;
import java.util.List; import java.util.List;
@ -22,4 +22,8 @@ public class BuyerDto {
public String getName() { public String getName() {
return name; return name;
} }
public List<CarDto> getCars() {
return cars;
}
} }

View File

@ -1,12 +1,12 @@
package ru.ulstu.is.lab1.dto; package com.example.springip.lab3.dto;
import ru.ulstu.is.lab1.models.Buyer; import com.example.springip.lab3.models.Buyer;
public class BuyerWithoutCaDto { public class BuyerWithoutEmpDto {
private final Long Id; private final Long Id;
private final String name; private final String name;
public BuyerWithoutCaDto(Buyer buyer) { public BuyerWithoutEmpDto(Buyer buyer) {
this.Id = buyer.getId(); this.Id = buyer.getId();
this.name = buyer.getName(); this.name = buyer.getName();
} }

View File

@ -1,25 +1,25 @@
package ru.ulstu.is.lab1.dto; package com.example.springip.lab3.dto;
import ru.ulstu.is.lab1.models.Car; import com.example.springip.lab3.models.Car;
import java.util.List; import java.util.List;
public class CarDto { public class CarDto {
private final Long Id; private final Long Id;
private final String name; private final String name;
private final String phoneNumber; private final String price;
private final String surname; private final String surname;
private final List<StoreDto> stores; private final List<StoreDto> stores;
private final BuyerWithoutCaDto buyer; private final BuyerWithoutEmpDto buyer;
public CarDto(Car car) { public CarDto(Car car) {
Id = car.getId(); Id = car.getId();
this.name = car.getName(); this.name = car.getName();
this.phoneNumber = car.getPhoneNumber(); this.price = car.getPrice();
this.surname = car.getSurname(); this.surname = car.getSurname();
this.stores = car.getStores().stream().map(StoreDto::new).toList(); this.stores = car.getStores().stream().map(StoreDto::new).toList();
this.buyer = car.getBuyer() != null ? new BuyerWithoutCaDto(car.getBuyer()) : null; this.buyer = car.getBuyer() != null ? new BuyerWithoutEmpDto(car.getBuyer()) : null;
} }
public Long getId() { public Long getId() {
@ -30,8 +30,8 @@ public class CarDto {
return name; return name;
} }
public String getPhoneNumber() { public String getPrice() {
return phoneNumber; return price;
} }
public String getSurname() { public String getSurname() {
@ -42,7 +42,7 @@ public class CarDto {
return stores; return stores;
} }
public BuyerWithoutCaDto getBuyer() { public BuyerWithoutEmpDto getBuyer() {
return buyer; return buyer;
} }
} }

View File

@ -1,6 +1,6 @@
package ru.ulstu.is.lab1.dto; package com.example.springip.lab3.dto;
import ru.ulstu.is.lab1.models.Store; import com.example.springip.lab3.models.Store;
public class StoreDto { public class StoreDto {
private final Long Id; private final Long Id;

View File

@ -1,6 +1,6 @@
package ru.ulstu.is.lab1.models; package com.example.springip.lab3.models;
import javax.persistence.*; import jakarta.persistence.*;
import java.util.*; import java.util.*;
@ -11,7 +11,7 @@ public class Buyer {
private Long Id; private Long Id;
@Column(unique = true) @Column(unique = true)
private String name; private String name;
@OneToMany(mappedBy = "buyer", cascade = CascadeType.ALL, fetch = FetchType.EAGER) @OneToMany(mappedBy = "buyer", cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private Set<Car> cars = new HashSet<>(); private Set<Car> cars = new HashSet<>();
public Buyer(String name, Set<Car> cars) { public Buyer(String name, Set<Car> cars) {

View File

@ -1,6 +1,6 @@
package ru.ulstu.is.lab1.models; package com.example.springip.lab3.models;
import javax.persistence.*; import jakarta.persistence.*;
import java.util.*; import java.util.*;
@ -9,7 +9,7 @@ public class Car {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
private String phoneNumber; private String price;
private String name; private String name;
private String surname; private String surname;
@ -20,8 +20,8 @@ public class Car {
private Set<Store> stores = new HashSet<>(); private Set<Store> stores = new HashSet<>();
public Car(String surname, String name, String phoneNumber) { public Car(String surname, String name, String price) {
this.phoneNumber = phoneNumber; this.price = price;
this.name = name; this.name = name;
this.surname = surname; this.surname = surname;
} }
@ -33,12 +33,12 @@ public class Car {
return id; return id;
} }
public String getPhoneNumber() { public String getPrice() {
return phoneNumber; return price;
} }
public void setPhoneNumber(String phoneNumber) { public void setPrice(String price) {
this.phoneNumber = phoneNumber; this.price = price;
} }
public String getName() { public String getName() {

View File

@ -1,6 +1,6 @@
package ru.ulstu.is.lab1.models; package com.example.springip.lab3.models;
import javax.persistence.*; import jakarta.persistence.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -10,7 +10,7 @@ import java.util.Objects;
public class Store { public class Store {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long Id;
private String name; private String name;
@ -34,7 +34,7 @@ public class Store {
} }
public Long getId() { public Long getId() {
return id; return Id;
} }
public List<Car> getCars() { public List<Car> getCars() {
@ -63,11 +63,11 @@ public class Store {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
Store student = (Store) o; Store student = (Store) o;
return Objects.equals(id, student.id); return Objects.equals(Id, student.Id);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(id); return Objects.hash(Id);
} }
} }

View File

@ -1,12 +1,9 @@
package ru.ulstu.is.lab1.service; package com.example.springip.lab3.service;
import ru.ulstu.is.lab1.dao.BuyerRepository;
import ru.ulstu.is.lab1.dao.CarRepository;
import ru.ulstu.is.lab1.models.Buyer;
import ru.ulstu.is.lab1.models.Car;
import javax.persistence.EntityNotFoundException;
import com.example.springip.lab3.dao.BuyerRepository;
import com.example.springip.lab3.models.Car;
import com.example.springip.lab3.models.Buyer;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -16,10 +13,10 @@ import java.util.List;
@Service @Service
public class BuyerService { public class BuyerService {
private BuyerRepository buyerRepository; private BuyerRepository buyerRepository;
private CarRepository carRepository; private CarService carService;
public BuyerService(BuyerRepository buyerRepository, CarRepository carRepository) { public BuyerService(BuyerRepository buyerRepository, CarService carService) {
this.buyerRepository = buyerRepository; this.buyerRepository = buyerRepository;
this.carRepository = carRepository; this.carService = carService;
} }
@Transactional @Transactional
@ -42,7 +39,7 @@ public class BuyerService {
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<Buyer> findAllBuyers() { public List<Buyer> findAllCompanies() {
return buyerRepository.findAll(); return buyerRepository.findAll();
} }
@ -65,7 +62,7 @@ public class BuyerService {
} }
@Transactional @Transactional
public void deleteAllBuyers() { public void deleteAllCompanies() {
buyerRepository.deleteAll(); buyerRepository.deleteAll();
} }
@ -78,9 +75,8 @@ public class BuyerService {
} }
@Transactional @Transactional
public Car deleteCar(Long id, Car car) { public void deleteCar(Long id, Car car) {
Buyer currentBuyer = findBuyer(id); Buyer currentBuyer = findBuyer(id);
currentBuyer.deleteCar(car); currentBuyer.deleteCar(car);
return carRepository.save(car);
} }
} }

View File

@ -1,10 +1,10 @@
package ru.ulstu.is.lab1.service; package com.example.springip.lab3.service;
import ru.ulstu.is.lab1.dao.CarRepository; import com.example.springip.lab3.dao.CarRepository;
import ru.ulstu.is.lab1.models.Buyer; import com.example.springip.lab3.models.Car;
import ru.ulstu.is.lab1.models.Car; import com.example.springip.lab3.models.Buyer;
import ru.ulstu.is.lab1.models.Store; import com.example.springip.lab3.models.Store;
import javax.persistence.EntityNotFoundException; import jakarta.persistence.EntityNotFoundException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -19,11 +19,11 @@ public class CarService {
} }
@Transactional @Transactional
public Car addCar(String surname, String name, String phoneNumber) { public Car addCar(String surname, String name, String price) {
if (!StringUtils.hasText(name) ||!StringUtils.hasText(surname) || !StringUtils.hasText(phoneNumber)) { if (!StringUtils.hasText(name) ||!StringUtils.hasText(surname) || !StringUtils.hasText(price)) {
throw new IllegalArgumentException("Car's data is null or empty"); throw new IllegalArgumentException("Car's data is null or empty");
} }
final Car car = new Car(surname, name, phoneNumber); final Car car = new Car(surname, name, price);
carRepository.save(car); carRepository.save(car);
return car; return car;
} }
@ -47,14 +47,14 @@ public class CarService {
} }
@Transactional @Transactional
public Car updateCar(Long id, String surname, String name, String phoneNumber) { public Car updateCar(Long id, String surname, String name, String price) {
if (!StringUtils.hasText(name) ||!StringUtils.hasText(surname) || !StringUtils.hasText(phoneNumber)) { if (!StringUtils.hasText(name) ||!StringUtils.hasText(surname) || !StringUtils.hasText(price)) {
throw new IllegalArgumentException("Car's data is null or empty"); throw new IllegalArgumentException("Car's data is null or empty");
} }
final Car currentCar = findCar(id); final Car currentCar = findCar(id);
currentCar.setName(name); currentCar.setName(name);
currentCar.setSurname(surname); currentCar.setSurname(surname);
currentCar.setPhoneNumber(phoneNumber); currentCar.setPrice(price);
return carRepository.save(currentCar); return carRepository.save(currentCar);
} }
@ -102,6 +102,10 @@ public class CarService {
@Transactional @Transactional
public List<Car> getCarsByStore(Store p) { public List<Car> getCarsByStore(Store p) {
// List<Car> cars = em.createQuery("select e from Car e INNER JOIN e.stores p WHERE p.id=:posit",
// Car.class)
// .setParameter("posit", p.getId())
// .getResultList();
List<Car> cars = carRepository.findByStores_Id(p.getId()); List<Car> cars = carRepository.findByStores_Id(p.getId());
return cars; return cars;
} }

View File

@ -1,10 +1,8 @@
package ru.ulstu.is.lab1.service; package com.example.springip.lab3.service;
import ru.ulstu.is.lab1.dao.StoreRepository;
import ru.ulstu.is.lab1.models.Store;
import javax.persistence.EntityNotFoundException;
import com.example.springip.lab3.dao.StoreRepository;
import com.example.springip.lab3.models.Store;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;