Лабораторная 4-5 (Backend)

This commit is contained in:
Никита Белянин 2024-05-24 11:17:51 +04:00
parent c39d189584
commit f5d9e6c9f1
100 changed files with 3333 additions and 1588 deletions

View File

@ -1,18 +0,0 @@
Swagger UI: \
http://localhost:8080/swagger-ui/index.html
H2 Console: \
http://localhost:8080/h2-console
JDBC URL: jdbc:h2:file:./data \
User Name: sa \
Password: password
Почитать:
- Односторонние и двусторонние связи https://www.baeldung.com/jpa-hibernate-associations
- Getters и Setters для двусторонних связей https://en.wikibooks.org/wiki/Java_Persistence/OneToMany#Getters_and_Setters
- Многие-ко-многим с доп. атрибутами https://thorben-janssen.com/hibernate-tip-many-to-many-association-with-additional-attributes/
- Многие-ко-многим с доп. атрибутами https://www.baeldung.com/jpa-many-to-many
- Каскадное удаление сущностей со связями многие-ко-многим https://www.baeldung.com/jpa-remove-entity-many-to-many
- Выбор типа коллекции для отношений вида ко-многим в JPA https://thorben-janssen.com/association-mappings-bag-list-set/

View File

@ -1,80 +0,0 @@
package com.example.demo;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.houses.service.HouseService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
private final TypeService typeService;
private final HouseService houseService;
private final UserService userService;
public DemoApplication(TypeService typeService, HouseService houseService, UserService userService) {
this.typeService = typeService;
this.houseService = houseService;
this.userService = userService;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
if (args.length > 0 && Objects.equals("--populate", args[0])) {
log.info("Create default types values");
final var type1 = typeService.create(new TypeEntity("Апартаменты"));
final var type2 = typeService.create(new TypeEntity("Таунхауз"));
final var type3 = typeService.create(new TypeEntity("Пентхауз"));
final var type4 = typeService.create(new TypeEntity("Квартира"));
log.info("Create default users values");
final var user1 = userService.create(new UserEntity("Иван", "ivaqqn@mail.ru",
"+79048756587", "vanya1", "1fdfddf"));
final var user2 = userService.create(new UserEntity("Пётр", "pe1tr@mail.ru",
"+79048751187", "petry", "1232"));
log.info("Create houses values");
houseService.create(user1.getId(), new HouseEntity(type4, user1, "Квартира1",
"Удобная квартира в центре города", 49999.00));
houseService.create(user1.getId(), new HouseEntity(type1, user1, "Квартира2",
"Удобная квартира на севере", 129999.00));
houseService.create(user1.getId(), new HouseEntity(type4, user1, "Квартира3",
"Квартира с большой парковкой", 15450.50));
houseService.create(user2.getId(), new HouseEntity(type2, user2,
"Апартаменты",
"Апартаменты на 24 этаже", 69900.50));
houseService.create(user2.getId(), new HouseEntity(type2, user2, "Пентауз",
"Дорогой пентхауз", 150000.00));
houseService.create(user1.getId(), new HouseEntity(type3, user1, "Таунхауз",
"Большой бассейн", 75000.00));
houseService.create(user2.getId(), new HouseEntity(type3, user2, "Пентауз",
"Для каждого!", 67800.00));
log.info("Create users values");
userService.create(new UserEntity("Иван", "i1van@mail.ru",
"+79048743287", "vanya", "1"));
userService.create(new UserEntity("Пётр", "peqtr@mail.ru",
"+79044444187", "petry1", "1de232"));
userService.create(new UserEntity("Сергей", "serg79@mail.ru",
"95-85-72", "sergy1", "1234"));
userService.create(new UserEntity("Джеймс", "jaims21@mail.ru",
"89047853087", "jaims1", "jaen12"));
}
}
}

View File

@ -1,97 +0,0 @@
package com.example.demo.core.api;
import java.util.ArrayList;
import java.util.List;
public class PageDto<D> {
private List<D> items = new ArrayList<>();
private int itemsCount;
private int currentPage;
private int currentSize;
private int totalPages;
private long totalItems;
private boolean isFirst;
private boolean isLast;
private boolean hasNext;
private boolean hasPrevious;
public List<D> getItems() {
return items;
}
public void setItems(List<D> items) {
this.items = items;
}
public int getItemsCount() {
return itemsCount;
}
public void setItemsCount(int itemsCount) {
this.itemsCount = itemsCount;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getCurrentSize() {
return currentSize;
}
public void setCurrentSize(int currentSize) {
this.currentSize = currentSize;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public long getTotalItems() {
return totalItems;
}
public void setTotalItems(long totalItems) {
this.totalItems = totalItems;
}
public boolean isFirst() {
return isFirst;
}
public void setFirst(boolean isFirst) {
this.isFirst = isFirst;
}
public boolean isLast() {
return isLast;
}
public void setLast(boolean isLast) {
this.isLast = isLast;
}
public boolean isHasNext() {
return hasNext;
}
public void setHasNext(boolean hasNext) {
this.hasNext = hasNext;
}
public boolean isHasPrevious() {
return hasPrevious;
}
public void setHasPrevious(boolean hasPrevious) {
this.hasPrevious = hasPrevious;
}
}

View File

@ -1,25 +0,0 @@
package com.example.demo.core.api;
import java.util.function.Function;
import org.springframework.data.domain.Page;
public class PageDtoMapper {
private PageDtoMapper() {
}
public static <D, E> PageDto<D> toDto(Page<E> page, Function<E, D> mapper) {
final PageDto<D> dto = new PageDto<>();
dto.setItems(page.getContent().stream().map(mapper::apply).toList());
dto.setItemsCount(page.getNumberOfElements());
dto.setCurrentPage(page.getNumber());
dto.setCurrentSize(page.getSize());
dto.setTotalPages(page.getTotalPages());
dto.setTotalItems(page.getTotalElements());
dto.setFirst(page.isFirst());
dto.setLast(page.isLast());
dto.setHasNext(page.hasNext());
dto.setHasPrevious(page.hasPrevious());
return dto;
}
}

View File

@ -1,12 +0,0 @@
package com.example.demo.core.configuration;
public class Constants {
public static final String SEQUENCE_NAME = "hibernate_sequence";
public static final String API_URL = "/api/1.0";
public static final String DEFAULT_PAGE_SIZE = "5";
private Constants() {
}
}

View File

@ -1,13 +0,0 @@
package com.example.demo.core.configuration;
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MapperConfiguration {
@Bean
ModelMapper modelMapper() {
return new ModelMapper();
}
}

View File

@ -1,54 +0,0 @@
package com.example.demo.core.error;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class AdviceController {
private final Logger log = LoggerFactory.getLogger(AdviceController.class);
public static ErrorCauseDto getRootCause(Throwable throwable) {
Throwable rootCause = throwable;
while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
rootCause = rootCause.getCause();
}
final StackTraceElement firstError = rootCause.getStackTrace()[0];
return new ErrorCauseDto(
rootCause.getClass().getName(),
firstError.getMethodName(),
firstError.getFileName(),
firstError.getLineNumber());
}
private ResponseEntity<ErrorDto> handleException(Throwable throwable, HttpStatusCode httpCode) {
log.error("{}", throwable.getMessage());
throwable.printStackTrace();
final ErrorDto errorDto = new ErrorDto(throwable.getMessage(), AdviceController.getRootCause(throwable));
return new ResponseEntity<>(errorDto, httpCode);
}
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseEntity<ErrorDto> handleNotFoundException(Throwable throwable) {
return handleException(throwable, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<ErrorDto> handleDataIntegrityViolationException(Throwable throwable) {
return handleException(throwable, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<ErrorDto> handleAnyException(Throwable throwable) {
return handleException(throwable, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@ -1,31 +0,0 @@
package com.example.demo.core.error;
class ErrorCauseDto {
private String exception;
private String methodName;
private String fineName;
private int lineNumber;
ErrorCauseDto(String exception, String methodName, String fineName, int lineNumber) {
this.exception = exception;
this.methodName = methodName;
this.fineName = fineName;
this.lineNumber = lineNumber;
}
public String getException() {
return exception;
}
public String getMethodName() {
return methodName;
}
public String getFineName() {
return fineName;
}
public int getLineNumber() {
return lineNumber;
}
}

View File

@ -1,20 +0,0 @@
package com.example.demo.core.error;
public class ErrorDto {
private String error;
private ErrorCauseDto rootCause;
public ErrorDto(String error, ErrorCauseDto rootCause) {
this.error = error;
this.rootCause = rootCause;
}
public String getError() {
return error;
}
public ErrorCauseDto getRootCause() {
return rootCause;
}
}

View File

@ -1,79 +0,0 @@
package com.example.demo.houses.api;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.configuration.Constants;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.houses.service.HouseService;
import com.example.demo.types.service.TypeService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/user/{userId}/house")
public class HouseController {
private final HouseService houseService;
private final TypeService typeService;
private final ModelMapper modelMapper;
public HouseController(HouseService houseService, TypeService typeService,
ModelMapper modelMapper) {
this.houseService = houseService;
this.modelMapper = modelMapper;
this.typeService = typeService;
}
private HouseDto toDto(HouseEntity entity) {
return modelMapper.map(entity, HouseDto.class);
}
private HouseEntity toEntity(HouseDto dto) {
final HouseEntity entity = modelMapper.map(dto, HouseEntity.class);
entity.setType(typeService.get(dto.getTypeId()));
return entity;
}
public List<HouseDto> getAllHouses() {
return houseService.getAllHouses().stream().map(this::toDto).toList();
}
@GetMapping
public List<HouseDto> getAll(@RequestParam(name = "typeId", defaultValue = "0") Long typeId,
@PathVariable(name = "userId") Long userId) {
return houseService.getAll(typeId, userId).stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public HouseDto get(@PathVariable(name = "id") Long id,
@PathVariable(name = "userId") Long userId) {
return toDto(houseService.get(id, userId));
}
@PostMapping
public HouseDto create(@PathVariable(name = "userId") Long userId,
@RequestBody @Valid HouseDto dto) {
return toDto(houseService.create(userId, toEntity(dto)));
}
@PutMapping("/{id}")
public HouseDto update(@PathVariable(name = "id") Long id,
@PathVariable(name = "userId") Long userId, @RequestBody HouseDto dto) {
return toDto(houseService.update(id, userId, toEntity(dto)));
}
@DeleteMapping("/{id}")
public HouseDto delete(@PathVariable(name = "id") Long id, @PathVariable(name = "userId") Long userId) {
return toDto(houseService.delete(id, userId));
}
}

View File

@ -1,79 +0,0 @@
package com.example.demo.orders.api;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.api.PageDto;
import com.example.demo.core.api.PageDtoMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.houses.service.HouseService;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/user/{user}/order")
public class OrderController {
private final OrderService orderService;
private final HouseService houseService;
private final ModelMapper modelMapper;
public OrderController(OrderService orderService, HouseService houseService,
ModelMapper modelMapper) {
this.orderService = orderService;
this.houseService = houseService;
this.modelMapper = modelMapper;
}
private OrderDto toDto(OrderEntity entity) {
return modelMapper.map(entity, OrderDto.class);
}
private OrderEntity toEntity(OrderDto dto) {
final OrderEntity entity = modelMapper.map(dto, OrderEntity.class);
entity.setHouse(houseService.getForOrder(dto.getHouseId()));
return entity;
}
@GetMapping
public PageDto<OrderDto> getAll(
@PathVariable(name = "user") Long userId,
@RequestParam(name = "houseId", defaultValue = "0") Long houseId,
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
return PageDtoMapper.toDto(orderService.getAll(userId, houseId, page, size), this::toDto);
}
@GetMapping("/{id}")
public OrderDto get(@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id) {
return toDto(orderService.get(userId, id));
}
@PostMapping
public OrderDto create(@PathVariable(name = "user") Long userId,
@RequestBody @Valid OrderDto dto) {
return toDto(orderService.create(userId, toEntity(dto)));
}
@PutMapping("/{id}")
public OrderDto update(@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id, @RequestBody @Valid OrderDto dto) {
return toDto(orderService.update(userId, id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public OrderDto delete(@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id) {
return toDto(orderService.delete(userId, id));
}
}

View File

@ -1,93 +0,0 @@
package com.example.demo.orders.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class OrderDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotNull
@Min(1)
private Long houseId;
@NotNull
@Min(1)
private Long userId;
@NotNull
@Min(1)
private Double price;
@NotNull
@Min(1)
private Integer countPeople;
@NotBlank
private String rentalDateStart;
@NotBlank
private String rentalDateEnd;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getHouseId() {
return houseId;
}
public void setHouseId(Long houseId) {
this.houseId = houseId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getCountPeople() {
return countPeople;
}
public void setCountPeople(Integer countPeople) {
this.countPeople = countPeople;
}
public String getRentalDateStart() {
return rentalDateStart;
}
public void setRentalDateStart(String rentalDateStart) {
this.rentalDateStart = rentalDateStart;
}
public String getRentalDateEnd() {
return rentalDateEnd;
}
public void setRentalDateEnd(String rentalDateEnd) {
this.rentalDateEnd = rentalDateEnd;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Double getSum() {
return price * countPeople;
}
}

View File

@ -1,122 +0,0 @@
package com.example.demo.orders.model;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.users.model.UserEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "orders")
public class OrderEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "houseId", nullable = false)
private HouseEntity house;
@ManyToOne
@JoinColumn(name = "userId", nullable = false)
private UserEntity user;
@Column(nullable = false)
private Double price;
@Column(nullable = false)
private Integer countPeople;
@Column(nullable = false)
private String rentalDateStart;
@Column(nullable = false)
private String rentalDateEnd;
public OrderEntity() {
}
public OrderEntity(HouseEntity house, UserEntity user, Double price, Integer countPeople, String rentalDateStart,
String rentalDateEnd) {
this.house = house;
this.user = user;
this.price = price;
this.countPeople = countPeople;
this.rentalDateStart = rentalDateStart;
this.rentalDateEnd = rentalDateEnd;
}
public HouseEntity getHouse() {
return house;
}
public void setHouse(HouseEntity house) {
this.house = house;
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
if (!user.getOrders().contains(this)) {
user.getOrders().add(this);
}
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getCountPeople() {
return countPeople;
}
public void setCountPeople(Integer countPeople) {
this.countPeople = countPeople;
}
public String getRentalDateStart() {
return rentalDateStart;
}
public void setRentalDateStart(String rentalDateStart) {
this.rentalDateStart = rentalDateStart;
}
public String getRentalDateEnd() {
return rentalDateEnd;
}
public void setRentalDateEnd(String rentalDateEnd) {
this.rentalDateEnd = rentalDateEnd;
}
@Override
public int hashCode() {
return Objects.hash(id, house.getId(), user.getId(), price, countPeople, rentalDateStart, rentalDateEnd);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final OrderEntity other = (OrderEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getHouse().getId(), house.getId())
&& Objects.equals(other.getUser().getId(), user.getId())
&& Objects.equals(other.getPrice(), price)
&& Objects.equals(other.getCountPeople(), countPeople)
&& Objects.equals(other.getRentalDateStart(), rentalDateStart)
&& Objects.equals(other.getRentalDateEnd(), rentalDateEnd);
}
}

View File

@ -1,67 +0,0 @@
package com.example.demo.types.api;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.configuration.Constants;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/type")
public class TypeController {
private final TypeService typeService;
private final ModelMapper modelMapper;
public TypeController(TypeService typeService, ModelMapper modelMapper) {
this.typeService = typeService;
this.modelMapper = modelMapper;
}
private TypeDto toDto(TypeEntity entity) {
return modelMapper.map(entity, TypeDto.class);
}
private TypeEntity toEntity(TypeDto dto) {
return modelMapper.map(dto, TypeEntity.class);
}
@GetMapping
public List<TypeDto> getAll() {
return typeService.getAll().stream()
.map(this::toDto)
.toList();
}
@GetMapping("/{id}")
public TypeDto get(@PathVariable(name = "id") Long id) {
return toDto(typeService.get(id));
}
@PostMapping
public TypeDto create(@RequestBody @Valid TypeDto dto) {
return toDto(typeService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public TypeDto update(@PathVariable(name = "id") Long id,
@RequestBody @Valid TypeDto dto) {
return toDto(typeService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public TypeDto delete(@PathVariable(name = "id") Long id) {
return toDto(typeService.delete(id));
}
}

View File

@ -1,69 +0,0 @@
package com.example.demo.users.api;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.api.PageDto;
import com.example.demo.core.api.PageDtoMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/user")
public class UserController {
private final UserService userService;
private final ModelMapper modelMapper;
public UserController(UserService userService, ModelMapper modelMapper) {
this.userService = userService;
this.modelMapper = modelMapper;
}
private UserDto toDto(UserEntity entity) {
return modelMapper.map(entity, UserDto.class);
}
private UserEntity toEntity(UserDto dto) {
return modelMapper.map(dto, UserEntity.class);
}
@GetMapping
public PageDto<UserDto> getAll(
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
return PageDtoMapper.toDto(userService.getAll(page, size), this::toDto);
}
@GetMapping("/{id}")
public UserDto get(@PathVariable(name = "id") Long id) {
return toDto(userService.get(id));
}
@PostMapping
public UserDto create(@RequestBody @Valid UserDto dto) {
return toDto(userService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public UserDto update(
@PathVariable(name = "id") Long id,
@RequestBody @Valid UserDto dto) {
return toDto(userService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public UserDto delete(@PathVariable(name = "id") Long id) {
return toDto(userService.delete(id));
}
}

View File

@ -1,80 +0,0 @@
package com.example.demo.users.service;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.repository.UserRepository;
@Service
public class UserService {
private final UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
private void checkLogin(String login) {
if (repository.findByLoginIgnoreCase(login).isPresent()) {
throw new IllegalArgumentException(
String.format("User with login %s is already exists", login));
}
}
private void checkPassword(String password) {
if (repository.findByPasswordIgnoreCase(password).isPresent()) {
throw new IllegalArgumentException(
String.format("User with password %s is already exists", password));
}
}
@Transactional(readOnly = true)
public List<UserEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<UserEntity> getAll(int page, int size) {
return repository.findAll(PageRequest.of(page, size));
}
@Transactional(readOnly = true)
public UserEntity get(long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(UserEntity.class, id));
}
@Transactional
public UserEntity create(UserEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
checkLogin(entity.getLogin());
checkPassword(entity.getPassword());
repository.save(entity);
return repository.save(entity);
}
@Transactional
public UserEntity update(long id, UserEntity entity) {
final UserEntity existsEntity = get(id);
checkLogin(entity.getLogin());
existsEntity.setLogin(entity.getLogin());
repository.save(existsEntity);
return existsEntity;
}
@Transactional
public UserEntity delete(long id) {
final UserEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -1,133 +0,0 @@
package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.houses.service.HouseService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.transaction.Transactional;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class HouseServiceTests {
@Autowired
private HouseService houseService;
@Autowired
private TypeService typeService;
@Autowired
private UserService userService;
private TypeEntity type1;
private TypeEntity type2;
private UserEntity user1;
private UserEntity user2;
private HouseEntity house1;
private HouseEntity house2;
private HouseEntity house;
@BeforeEach
void createData() {
removeData();
type1 = typeService.create(new TypeEntity("Студия"));
type2 = typeService.create(new TypeEntity("Квартирка"));
user1 = userService.create(new UserEntity("dom", "serj2003@mail.ru",
"42-42-42", "user123", "serj1"));
user2 = userService
.create(new UserEntity("serega", "sej2003@mail.ru", "101564501",
"qwegfhfrty123", "sehfghrj1"));
house = houseService.create(user1.getId(),
new HouseEntity(type1, user1, "Apartament", "Близко к центру города",
50000.00));
house1 = houseService.create(user2.getId(), new HouseEntity(type2, user2,
"Studia", "Удобная парковка", 10000.00));
house2 = houseService.create(user1.getId(), new HouseEntity(type1, user1,
"Flat", "Very excelent", 4000.00));
}
@AfterEach
void removeData() {
typeService.getAll().forEach(type -> {
userService.getAll().forEach(user -> {
houseService.getAll(type.getId(), user.getId())
.forEach(house -> houseService.delete(house.getId(), user.getId()));
});
});
typeService.getAll().forEach(type -> typeService.delete(type.getId()));
userService.getAll().forEach(user -> userService.delete(user.getId()));
}
@Test
@Transactional
void createTest() {
Assertions.assertEquals(3, houseService.getAllHouses().size());
Assertions.assertEquals(type1, typeService.get(type1.getId()));
Assertions.assertEquals(user1, userService.get(user1.getId()));
Assertions.assertEquals(house1, house1);
Assertions.assertEquals(house2, house2);
Assertions.assertEquals(0, houseService.getAll(type2.getId(), user2.getId()).size());
}
@Test
@Transactional
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L));
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
Assertions.assertThrows(NotFoundException.class, () -> houseService.get(house.getId(), user1.getId()));
}
@Test
@Transactional
void createNotUniqueTest() {
final TypeEntity nonUniqueType = new TypeEntity("Студия");
Assertions.assertThrows(IllegalArgumentException.class,
() -> typeService.create(nonUniqueType));
}
@Test
@Transactional
void updateTest() {
final String test = "dom";
final String testnumber = "42-42-42";
final UserEntity newEntity = userService.update(user1.getId(), new UserEntity("", "", "dom", "very well", ""));
Assertions.assertEquals(2, userService.getAll().size());
Assertions.assertEquals(newEntity, userService.get(user1.getId()));
Assertions.assertEquals(test, newEntity.getFio());
Assertions.assertEquals(testnumber, newEntity.getNumberphone());
}
@Test
@Transactional
void deleteTest() {
Assertions.assertEquals(0, houseService.getAll(type1.getId(),
user1.getId()).size());
final HouseEntity newEntity = houseService.create(user1.getId(), new HouseEntity(type1, user1, "Flat",
"Dom excelent", 7000.00));
Assertions.assertEquals(0, houseService.getAll(type1.getId(),
user1.getId()).size());
Assertions.assertNotEquals(house1.getId(), newEntity.getId());
}
}

View File

@ -1,164 +0,0 @@
package com.example.demo;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.houses.service.HouseService;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.transaction.Transactional;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class OrderServiceTests {
@Autowired
private HouseService houseService;
@Autowired
private TypeService typeService;
@Autowired
private OrderService orderService;
@Autowired
private UserService userService;
private TypeEntity type1;
private TypeEntity type2;
private HouseEntity house1;
private HouseEntity house2;
private UserEntity user1;
private UserEntity user2;
private List<OrderEntity> orders;
private OrderEntity order;
@BeforeEach
void createData() {
removeData();
type1 = typeService.create(new TypeEntity("Квартира"));
type2 = typeService.create(new TypeEntity("Студия"));
user1 = userService.create(new UserEntity("user1", "dvsd", "dvds", "dfdsf",
"dvdv"));
user2 = userService.create(new UserEntity("user2", "dvsd23", "dvds123",
"12xcz", "12313"));
house1 = houseService.create(user1.getId(),
new HouseEntity(type1, user1, "Квартира1", "Удобная квартира в центре города", 49999.00));
house2 = houseService.create(user2.getId(),
new HouseEntity(type2, user1, "Студия", "Студия на несколько человек",
15000.0));
order = orderService.create(user1.getId(),
new OrderEntity(house1, user1, 100.00, 2, "11-11-2023", "18-11-2023"));
orders = List.of(
new OrderEntity(house1, user1, 19999.00, 2, "", ""),
new OrderEntity(house2, user1, 19999.00, 2, "", ""));
orders.forEach(order -> orderService.create(user1.getId(), order));
}
@AfterEach
void removeData() {
typeService.getAll().forEach(type -> {
userService.getAll().forEach(user -> {
houseService.getAll(type.getId(), user.getId())
.forEach(house -> houseService.delete(house.getId(), user.getId()));
});
});
typeService.getAll().forEach(type -> typeService.delete(type.getId()));
userService.getAll().forEach(user -> userService.delete(user.getId()));
}
@Test
@Order(1)
@Transactional
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L));
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
Assertions.assertThrows(NotFoundException.class, () -> houseService.get(house1.getId(), user1.getId()));
Assertions.assertThrows(NotFoundException.class,
() -> orderService.get(0L, 0L));
}
@Test
@Order(2)
@Transactional
void createTest() {
Assertions.assertEquals(2, orderService.getAll(user1.getId(), house1.getId()).size());
Assertions.assertEquals(0, orderService.getAll(user2.getId(), house2.getId()).size());
Assertions.assertEquals(type1, typeService.get(type1.getId()));
Assertions.assertEquals(user1, userService.get(user1.getId()));
Assertions.assertEquals(2, houseService.getAllHouses().size());
}
@Test
@Order(3)
@Transactional
void createNotEntitiesTest() {
final OrderEntity nonEntitiesOrder = new OrderEntity(null, null, 100.00, 2, "18-01-2023", "12-11-2011");
Assertions.assertThrows(NullPointerException.class,
() -> orderService.create(user1.getId(), nonEntitiesOrder));
}
@Test
@Order(4)
@Transactional
void createNullableTest() {
final OrderEntity nullableOrder = new OrderEntity(null, null, null, null, null,
null);
Assertions.assertThrows(NullPointerException.class,
() -> orderService.create(user1.getId(), nullableOrder));
}
@Test
@Order(5)
@Transactional
void updateTest() {
final String test = "18-11-2023";
final Double testprice = 2012.00;
final Integer testcount = 3;
final OrderEntity newEntity = orderService.update(user1.getId(), order.getId(),
new OrderEntity(house1, user1, 2012.00, 3, "19-21-22", "21-22"));
Assertions.assertEquals(2, orderService.getAll(user1.getId(), house1.getId()).size());
Assertions.assertEquals(test, newEntity.getRentalDateEnd());
Assertions.assertEquals(testprice, newEntity.getPrice());
Assertions.assertEquals(testcount, newEntity.getCountPeople());
}
@Test
@Order(6)
@Transactional
void deleteTest() {
order = orderService.delete(user1.getId(), order.getId());
Assertions.assertEquals(2, orderService.getAll(user1.getId(), house1.getId()).size());
final OrderEntity newEntity = orderService.create(user1.getId(), new OrderEntity(house1, user1, 19999.00, 2, "",
""));
Assertions.assertEquals(3, orderService.getAll(user1.getId(),
house1.getId()).size());
Assertions.assertNotEquals(house1.getId(), newEntity.getId());
}
}

View File

@ -1,165 +0,0 @@
package com.example.demo;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.houses.service.HouseService;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.transaction.Transactional;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class UserOrderServiceTest {
@Autowired
private HouseService houseService;
@Autowired
private TypeService typeService;
@Autowired
private OrderService orderService;
@Autowired
private UserService userService;
private TypeEntity type1;
private TypeEntity type2;
private HouseEntity house1;
private HouseEntity house2;
private UserEntity user1;
private UserEntity user2;
private List<OrderEntity> orders;
private OrderEntity order;
@BeforeEach
void createData() {
removeData();
type1 = typeService.create(new TypeEntity("Квартира"));
type2 = typeService.create(new TypeEntity("Студия"));
user1 = userService.create(new UserEntity("user1", "dvsd", "dvds", "dfdsf",
"dvdv"));
user2 = userService.create(new UserEntity("user2", "dvsd23", "dvds123",
"12xcz",
"12313"));
house1 = houseService.create(user1.getId(),
new HouseEntity(type1, user1, "Квартира1", "Удобная квартира в центре города", 49999.00));
house2 = houseService.create(user2.getId(),
new HouseEntity(type2, user1, "Студия", "Студия на несколько человек",
15000.0));
order = orderService.create(user1.getId(), new OrderEntity(house1, user1, 100.00, 2, "fe", "ef"));
orders = List.of(
new OrderEntity(house1, user1, 19999.00, 2, "", ""),
new OrderEntity(house2, user1, 19999.00, 2, "", ""));
orders.forEach(order -> orderService.create(user1.getId(), order));
}
@AfterEach
void removeData() {
typeService.getAll().forEach(type -> {
userService.getAll().forEach(user -> {
houseService.getAll(type.getId(), user.getId())
.forEach(house -> houseService.delete(house.getId(), user.getId()));
});
});
typeService.getAll().forEach(type -> typeService.delete(type.getId()));
userService.getAll().forEach(user -> userService.delete(user.getId()));
}
@Test
@Transactional
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L));
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
Assertions.assertThrows(NotFoundException.class, () -> houseService.get(house1.getId(), user1.getId()));
Assertions.assertThrows(NotFoundException.class,
() -> orderService.get(0L, 0L));
}
@Test
@Transactional
void createTest() {
Assertions.assertEquals(2, orderService.getAll(user1.getId(), house1.getId()).size());
Assertions.assertEquals(0, orderService.getAll(user2.getId(), house2.getId()).size());
}
@Test
@Transactional
void orderFilterTest() {
Assertions.assertEquals(0, orderService.getAll(user1.getId(),
type1.getId()).size());
Assertions.assertEquals(0, orderService.getAll(user1.getId(),
type2.getId()).size());
Assertions.assertEquals(0, orderService.getAll(user1.getId(),
type2.getId()).size());
}
@Test
@Transactional
void createNotEntitiesTest() {
final OrderEntity nonEntitiesOrder = new OrderEntity(null, null, 100.00, 2, "18-01-2023", "12-11-2011");
Assertions.assertThrows(NullPointerException.class,
() -> orderService.create(user1.getId(), nonEntitiesOrder));
}
@Test
@Transactional
void createNullableTest() {
final OrderEntity nullableOrder = new OrderEntity(null, null, null, null, null,
null);
Assertions.assertThrows(NullPointerException.class,
() -> orderService.create(user1.getId(), nullableOrder));
}
@Test
@Transactional
void updateTest() {
final String test = "ef";
final Double testprice = 2012.00;
final Integer testcount = 3;
final OrderEntity newEntity = orderService.update(user1.getId(), order.getId(),
new OrderEntity(house1, user1, 2012.00, 3, "19-21-22", "21-22"));
Assertions.assertEquals(2, orderService.getAll(user1.getId(), house1.getId()).size());
Assertions.assertEquals(test, newEntity.getRentalDateEnd());
Assertions.assertEquals(testprice, newEntity.getPrice());
Assertions.assertEquals(testcount, newEntity.getCountPeople());
}
@Transactional
@Test
void deleteTest() {
order = orderService.delete(user1.getId(), order.getId());
Assertions.assertEquals(2, orderService.getAll(user1.getId(), house1.getId()).size());
final OrderEntity newEntity = orderService.create(user1.getId(), new OrderEntity(house1, user1, 19999.00, 2, "",
""));
Assertions.assertEquals(3, orderService.getAll(user1.getId(),
house1.getId()).size());
Assertions.assertNotEquals(house1.getId(), newEntity.getId());
}
}

View File

@ -13,7 +13,7 @@
"request": "launch",
"cwd": "${workspaceFolder}",
"mainClass": "com.example.demo.DemoApplication",
"projectName": "lec3",
"projectName": "lec6",
"args": "--populate",
"envFile": "${workspaceFolder}/.env"
}

View File

@ -18,4 +18,7 @@
"java.format.settings.url": ".vscode/eclipse-formatter.xml",
"java.project.explorer.showNonJavaResources": true,
"java.codeGeneration.hashCodeEquals.useJava7Objects": true,
"cSpell.words": [
"classappend"
],
}

View File

@ -3,7 +3,7 @@ plugins {
id 'org.springframework.boot' version '3.2.5'
id 'io.spring.dependency-management' version '1.1.4'
}
apply plugin: 'org.springframework.boot'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
@ -29,12 +29,20 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
implementation 'org.modelmapper:modelmapper:3.2.0'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.2.224'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:3.3.0'
runtimeOnly 'org.webjars.npm:bootstrap:5.3.3'
runtimeOnly 'org.webjars.npm:bootstrap-icons:1.11.3'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

View File

15
Lab2_4_5/readme.md Normal file
View File

@ -0,0 +1,15 @@
H2 Console: \
http://localhost:8080/h2-console
JDBC URL: jdbc:h2:file:./data \
User Name: sa \
Password: password
Почитать:
- Spring Boot CRUD Application with Thymeleaf https://www.baeldung.com/spring-boot-crud-thymeleaf
- Thymeleaf Layout Dialect https://ultraq.github.io/thymeleaf-layout-dialect/
- Tutorial: Using Thymeleaf https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html#introducing-thymeleaf
- Working with Cookies in Spring MVC using @CookieValue Annotation https://www.geeksforgeeks.org/working-with-cookies-in-spring-mvc-using-cookievalue-annotation/
- Session Attributes in Spring MVC https://www.baeldung.com/spring-mvc-session-attributes
- LazyInitializationException What it is and the best way to fix it https://thorben-janssen.com/lazyinitializationexception/

View File

@ -0,0 +1,110 @@
package com.example.demo;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Objects;
import java.util.stream.IntStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.houses.service.HouseService;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.model.UserRole;
import com.example.demo.users.service.UserService;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
private final TypeService typeService;
private final HouseService houseService;
private final UserService userService;
private final OrderService orderService;
public DemoApplication(TypeService typeService, HouseService houseService, UserService userService,
OrderService orderService) {
this.typeService = typeService;
this.houseService = houseService;
this.userService = userService;
this.orderService = orderService;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
if (args.length > 0 && Objects.equals("--populate", args[0])) {
log.info("Create default types values");
final var type1 = typeService.create(new TypeEntity("Апартаменты"));
final var type2 = typeService.create(new TypeEntity("Дом"));
final var type3 = typeService.create(new TypeEntity("Квартира"));
final var type4 = typeService.create(new TypeEntity("Студия"));
final var type5 = typeService.create(new TypeEntity("Пентхауз"));
final var type6 = typeService.create(new TypeEntity("Таунхауз"));
log.info("Create default users values");
final var admin = new UserEntity("admin", "admin", "admin", "+78005553535");
admin.setRole(UserRole.ADMIN);
userService.create(admin);
final var user1 = userService.create(new UserEntity("user", "user",
"Иван", "+79048756587"));
final var user2 = userService.create(new UserEntity("dmitry1", "1fd323fddf",
"Дмитрий", "+79049654487"));
final var user3 = userService.create(new UserEntity("vanya1", "1fdfddf",
"Иван2", "+79049656587"));
log.info("Create houses values");
houseService.create(admin.getId(), new HouseEntity(type4, admin, "Квартира1",
"Удобная квартира в центре города", "Севастопольская 2", 49999.00));
houseService.create(admin.getId(), new HouseEntity(type1, admin, "Квартира2",
"Удобный апартаменты на севере с парковкой", "Ленина 123", 129999.00));
houseService.create(admin.getId(), new HouseEntity(type4, admin, "Квартира3",
"Квартира с большой парковкой на юге города", "Полбина 21", 15450.50));
houseService.create(user2.getId(), new HouseEntity(type2, user2,
"Апартаменты", "Апартаменты на 24 этаже с красивым видом на город", "Гончарова 5", 69900.50));
houseService.create(user2.getId(), new HouseEntity(type2, user2, "Пентауз",
"Дорогой пентхауз", "Хрустальная 7", 150000.00));
houseService.create(user1.getId(), new HouseEntity(type3, user1, "Таунхауз",
"Большой бассейн", "Варейкиса 8", 75000.00));
houseService.create(user2.getId(), new HouseEntity(type3, user2, "Пентауз",
"Для каждого!", "Северный Венец 16", 67800.00));
final var house1 = houseService.create(user2.getId(), new HouseEntity(type4, user2, "Дом у моря",
"Для каждого!", "Ленина 72", 67800.00));
log.info("Create users values");
userService.create(new UserEntity("vanya", "22331", "Иван", "+79048743287"));
userService.create(new UserEntity("peqtr@mail.ru", "1de232", "Пётр", "+79044444187"));
userService.create(new UserEntity("sergy1", "1234", "Сергей", "+79993232211"));
userService.create(new UserEntity("jaen12", "jaims1", "Джеймс",
"89047853087"));
Calendar calendar = Calendar.getInstance();
calendar.set(2023, Calendar.MAY, 23, 14, 30);
// Получаем объект Date из Calendar
LocalDateTime dateTime1 = LocalDateTime.of(2023, 5, 14, 17, 30);
LocalDateTime dateTime2 = LocalDateTime.of(2023, 8, 14, 17, 30);
// final String dateTime = "18-02-2023";
orderService.create(user1.getId(), new OrderEntity(house1, user1, dateTime1, dateTime2));
// IntStream.range(2, 5)
// .forEach(value -> userService.create(
// new UserEntity("user".concat(String.valueOf(value)),
// Constants.DEFAULT_PASSWORD, "", "")));
}
}
}

View File

@ -0,0 +1,28 @@
package com.example.demo.core.api;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
// import com.example.demo.core.session.SessionCart;
import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpSession;
@ControllerAdvice
public class GlobalController {
// private final SessionCart cart;
// public GlobalController(SessionCart cart) {
// this.cart = cart;
// }
@ModelAttribute("servletPath")
String getRequestServletPath(HttpServletRequest request) {
return request.getServletPath();
}
// @ModelAttribute("totalCart")
// double getTotalCart(HttpSession session) {
// return cart.getSum();
// }
}

View File

@ -0,0 +1,18 @@
package com.example.demo.core.api;
import java.util.Map;
import java.util.function.Function;
import org.springframework.data.domain.Page;
public class PageAttributesMapper {
private PageAttributesMapper() {
}
public static <E, D> Map<String, Object> toAttributes(Page<E> page, Function<E, D> mapper) {
return Map.of(
"items", page.getContent().stream().map(mapper::apply).toList(),
"currentPage", page.getNumber(),
"totalPages", page.getTotalPages());
}
}

View File

@ -0,0 +1,19 @@
package com.example.demo.core.configuration;
public class Constants {
public static final String SEQUENCE_NAME = "hibernate_sequence";
public static final int DEFUALT_PAGE_SIZE = 5;
public static final String REDIRECT_VIEW = "redirect:";
public static final String ADMIN_PREFIX = "/admin";
public static final String LOGIN_URL = "/login";
public static final String LOGOUT_URL = "/logout";
public static final String DEFAULT_PASSWORD = "123456";
private Constants() {
}
}

View File

@ -0,0 +1,23 @@
package com.example.demo.core.configuration;
import org.modelmapper.ModelMapper;
import org.modelmapper.PropertyMap;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.example.demo.core.model.BaseEntity;
@Configuration
public class MapperConfiguration {
@Bean
ModelMapper modelMapper() {
final ModelMapper mapper = new ModelMapper();
mapper.addMappings(new PropertyMap<Object, BaseEntity>() {
@Override
protected void configure() {
skip(destination.getId());
}
});
return mapper;
}
}

View File

@ -1,15 +1,13 @@
package com.example.demo.core.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(@NonNull CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE");
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
}

View File

@ -0,0 +1,53 @@
package com.example.demo.core.error;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import jakarta.servlet.http.HttpServletRequest;
@ControllerAdvice
public class AdviceController {
private final Logger log = LoggerFactory.getLogger(AdviceController.class);
private static Throwable getRootCause(Throwable throwable) {
Throwable rootCause = throwable;
while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
rootCause = rootCause.getCause();
}
return rootCause;
}
private static Map<String, Object> getAttributes(HttpServletRequest request, Throwable throwable) {
final Throwable rootCause = getRootCause(throwable);
final StackTraceElement firstError = rootCause.getStackTrace()[0];
return Map.of(
"message", rootCause.getMessage(),
"url", request.getRequestURL(),
"exception", rootCause.getClass().getName(),
"file", firstError.getFileName(),
"method", firstError.getMethodName(),
"line", firstError.getLineNumber());
}
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest request, Throwable throwable) throws Throwable {
if (AnnotationUtils.findAnnotation(throwable.getClass(),
ResponseStatus.class) != null) {
throw throwable;
}
log.error("{}", throwable.getMessage());
throwable.printStackTrace();
final ModelAndView model = new ModelAndView();
model.addAllObjects(getAttributes(request, throwable));
model.setViewName("error");
return model;
}
}

View File

@ -0,0 +1,65 @@
package com.example.demo.core.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer.FrameOptionsConfig;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import com.example.demo.core.configuration.Constants;
import com.example.demo.users.api.UserSignupController;
import com.example.demo.users.model.UserRole;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.headers(headers -> headers.frameOptions(FrameOptionsConfig::sameOrigin));
httpSecurity.csrf(AbstractHttpConfigurer::disable);
httpSecurity.cors(Customizer.withDefaults());
httpSecurity.authorizeHttpRequests(requests -> requests
.requestMatchers("/css/**", "/webjars/**", "/*.svg", "/*.png", "/*.jpg", "/*.jpeg")
.permitAll());
httpSecurity.authorizeHttpRequests(requests -> requests
.requestMatchers(Constants.ADMIN_PREFIX + "/**").hasRole(UserRole.ADMIN.name())
.requestMatchers("/h2-console/**").hasRole(UserRole.ADMIN.name())
.requestMatchers("/swagger-ui/index.html/**").hasRole(UserRole.ADMIN.name())
.requestMatchers("/catalog").permitAll()
.requestMatchers(UserSignupController.URL).anonymous()
.requestMatchers(Constants.LOGIN_URL).anonymous()
.anyRequest().authenticated());
httpSecurity.formLogin(formLogin -> formLogin
.loginPage(Constants.LOGIN_URL));
httpSecurity.rememberMe(rememberMe -> rememberMe.key("uniqueAndSecret"));
httpSecurity.logout(logout -> logout
.deleteCookies("JSESSIONID"));
return httpSecurity.build();
}
@Bean
DaoAuthenticationProvider authenticationProvider(UserDetailsService userDetailsService) {
final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,64 @@
package com.example.demo.core.security;
import java.util.Collection;
import java.util.Set;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.example.demo.users.model.UserEntity;
public class UserPrincipal implements UserDetails {
private final long id;
private final String username;
private final String password;
private final Set<? extends GrantedAuthority> roles;
private final boolean active;
public UserPrincipal(UserEntity user) {
this.id = user.getId();
this.username = user.getLogin();
this.password = user.getPassword();
this.roles = Set.of(user.getRole());
this.active = true;
}
public Long getId() {
return id;
}
@Override
public String getUsername() {
return username;
}
@Override
public String getPassword() {
return password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles;
}
@Override
public boolean isEnabled() {
return active;
}
@Override
public boolean isAccountNonExpired() {
return isEnabled();
}
@Override
public boolean isAccountNonLocked() {
return isEnabled();
}
@Override
public boolean isCredentialsNonExpired() {
return isEnabled();
}
}

View File

@ -0,0 +1,14 @@
// package com.example.demo.core.session;
// import java.util.HashMap;
// import com.example.demo.users.api.UserCartDto;
// public class SessionCart extends HashMap<Integer, UserCartDto> {
// public double getSum() {
// return this.values().stream()
// .map(item -> item.getCount() * item.getPrice())
// .mapToDouble(Double::doubleValue)
// .sum();
// }
// }

View File

@ -0,0 +1,17 @@
// package com.example.demo.core.session;
// import org.springframework.context.annotation.Bean;
// import org.springframework.context.annotation.Configuration;
// import org.springframework.context.annotation.Scope;
// import org.springframework.context.annotation.ScopedProxyMode;
// import org.springframework.web.context.WebApplicationContext;
// @Configuration
// public class SessionHelper {
// @Bean
// @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode =
// ScopedProxyMode.TARGET_CLASS)
// SessionCart todos() {
// return new SessionCart();
// }
// }

View File

@ -0,0 +1,97 @@
package com.example.demo.houses.api;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.demo.core.api.PageAttributesMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.houses.service.HouseService;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.types.api.TypeDto;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.users.api.UserDto;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@Controller
@RequestMapping(CatalogController.URL)
public class CatalogController {
private static final String CATALOG_VIEW = "catalog";
private static final String URL = "/catalog";
private static final String HOUSE_ATTRIBUTE = "house";
private static final String HOUSE_ONE = "house-one";
private static final String TYPEID_ATTRIBUTE = "typeId";
private static final String USERID_ATTRIBUTE = "userId";
private static final String PAGE_ATTRIBUTE = "page";
private final HouseService houseService;
private final TypeService typeService;
private final UserService userService;
private final ModelMapper modelMapper;
public CatalogController(HouseService houseService, TypeService typeService,
UserService userService, ModelMapper modelMapper) {
this.houseService = houseService;
this.modelMapper = modelMapper;
this.typeService = typeService;
this.userService = userService;
}
private HouseDto toDto(HouseEntity entity) {
return modelMapper.map(entity, HouseDto.class);
}
private TypeDto toTypeDto(TypeEntity entity) {
return modelMapper.map(entity, TypeDto.class);
}
private UserDto toUserDto(UserEntity entity) {
return modelMapper.map(entity, UserDto.class);
}
@GetMapping
public String getCatalog(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@RequestParam(name = TYPEID_ATTRIBUTE, defaultValue = "0") long typeId,
@RequestParam(name = USERID_ATTRIBUTE, defaultValue = "0") long userId,
Model model) {
model.addAttribute(PAGE_ATTRIBUTE, page);
model.addAllAttributes(PageAttributesMapper.toAttributes(
houseService.getAll(typeId, userId, page, Constants.DEFUALT_PAGE_SIZE), this::toDto));
model.addAttribute(
"users",
userService.getAll().stream().map(this::toUserDto).toList());
model.addAttribute(
"types",
typeService.getAll().stream().map(this::toTypeDto).toList());
model.addAttribute("typeId", typeId);
model.addAttribute("userId", userId);
return CATALOG_VIEW;
}
@GetMapping("/house-one/{id}")
public String getOne(@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
model.addAttribute(HOUSE_ATTRIBUTE, toDto(houseService.getAdmin(id)));
model.addAttribute("houses", houseService.getAllHouses().stream().map(this::toDto).toList());
model.addAttribute("users", userService.getAll().stream().map(this::toUserDto).toList());
model.addAttribute("types", typeService.getAll().stream().map(this::toTypeDto).toList());
model.addAttribute(PAGE_ATTRIBUTE, page);
return HOUSE_ONE;
}
}

View File

@ -0,0 +1,188 @@
package com.example.demo.houses.api;
import java.util.Map;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.core.api.PageAttributesMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.houses.service.HouseService;
import com.example.demo.types.api.TypeDto;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.users.api.UserDto;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@Controller
@RequestMapping(HouseController.URL)
public class HouseController {
public static final String URL = Constants.ADMIN_PREFIX + "/house";
private static final String HOUSE_VIEW = "house";
private static final String HOUSE_EDIT_VIEW = "house-edit";
private static final String HOUSE_ATTRIBUTE = "house";
private static final String PAGE_ATTRIBUTE = "page";
private final HouseService houseService;
private final TypeService typeService;
private final UserService userService;
private final ModelMapper modelMapper;
public HouseController(HouseService houseService, TypeService typeService,
UserService userService, ModelMapper modelMapper) {
this.houseService = houseService;
this.modelMapper = modelMapper;
this.typeService = typeService;
this.userService = userService;
}
private HouseDto toDto(HouseEntity entity) {
return modelMapper.map(entity, HouseDto.class);
}
private HouseEntity toEntity(HouseDto dto) {
final HouseEntity entity = modelMapper.map(dto, HouseEntity.class);
entity.setType(typeService.get(dto.getTypeId()));
return entity;
}
private TypeDto toTypeDto(TypeEntity entity) {
return modelMapper.map(entity, TypeDto.class);
}
private UserDto toUserDto(UserEntity entity) {
return modelMapper.map(entity, UserDto.class);
}
public String getAllHouses(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
houseService.getAllHouses(page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attributes);
model.addAttribute(PAGE_ATTRIBUTE, page);
return HOUSE_VIEW;
}
@GetMapping
public String getAll(@RequestParam(name = "typeId", defaultValue = "0") Long typeId,
@RequestParam(name = "userId", defaultValue = "0") Long userId,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
houseService.getAllHouses(page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
// house.setTypeName(typeService.get(house.getTypeId()));
model.addAllAttributes(attributes);
model.addAttribute(PAGE_ATTRIBUTE, page);
model.addAttribute(
"types",
typeService.getAll().stream().map(this::toTypeDto).toList());
model.addAttribute(
"houses",
houseService.getAllHouses(page, Constants.DEFUALT_PAGE_SIZE).stream().map(this::toDto).toList());
return HOUSE_VIEW;
}
@GetMapping("/edit/")
public String create(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page, Model model) {
model.addAttribute(HOUSE_ATTRIBUTE, new HouseDto());
model.addAttribute("users", userService.getAll().stream().map(this::toUserDto).toList());
model.addAttribute("types", typeService.getAll().stream().map(this::toTypeDto).toList());
model.addAttribute(PAGE_ATTRIBUTE, page);
return HOUSE_EDIT_VIEW;
}
@PostMapping("/edit/")
public String create(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@RequestParam(name = "userId", defaultValue = "0") Long userId,
@ModelAttribute(name = HOUSE_ATTRIBUTE) @Valid HouseDto house,
BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return HOUSE_EDIT_VIEW;
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
houseService.create(userId, toEntity(house));
return Constants.REDIRECT_VIEW + URL;
}
@GetMapping("/edit/{id}")
public String update(@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
model.addAttribute(HOUSE_ATTRIBUTE, toDto(houseService.getAdmin(id)));
model.addAttribute("houses", houseService.getAllHouses().stream().map(this::toDto).toList());
model.addAttribute("users", userService.getAll().stream().map(this::toUserDto).toList());
model.addAttribute("types", typeService.getAll().stream().map(this::toTypeDto).toList());
model.addAttribute(PAGE_ATTRIBUTE, page);
return HOUSE_EDIT_VIEW;
}
@PostMapping("/edit/{id}")
public String update(@PathVariable(name = "id") Long id,
@RequestParam(name = "userId") Long userId,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = HOUSE_ATTRIBUTE) @Valid HouseDto house,
BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return HOUSE_EDIT_VIEW;
}
if (id <= 0) {
throw new IllegalArgumentException();
}
model.addAttribute(
"types",
typeService.getAll().stream().map(this::toTypeDto).toList());
model.addAttribute(
"userId",
userService.getAll().stream().map(this::toUserDto).toList());
model.addAttribute("users", toUserDto(userService.get(userId)));
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
houseService.update(id, userId, toEntity(house));
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/delete/{id}")
public String delete(@PathVariable(name = "id") Long id,
@RequestParam(name = "userId") Long userId,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
RedirectAttributes redirectAttributes) {
final UserEntity user = userService.get(userId);
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
houseService.delete(id, user.getId());
// toDto(houseService.delete(id, userId));
return Constants.REDIRECT_VIEW + URL;
}
}

View File

@ -1,14 +1,11 @@
package com.example.demo.houses.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class HouseDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotNull
@ -26,11 +23,13 @@ public class HouseDto {
@NotBlank
private String description;
@NotBlank
private String address;
@NotNull
@Min(1)
private Double price;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}
@ -47,7 +46,6 @@ public class HouseDto {
this.typeId = typeId;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getUserId() {
return userId;
}
@ -72,6 +70,14 @@ public class HouseDto {
this.description = description;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Double getPrice() {
return price;
}

View File

@ -6,6 +6,7 @@ import com.example.demo.core.model.BaseEntity;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.users.model.UserEntity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
@ -15,11 +16,11 @@ import jakarta.persistence.Table;
@Entity
@Table(name = "houses")
public class HouseEntity extends BaseEntity {
@ManyToOne
@ManyToOne(cascade = CascadeType.REMOVE)
@JoinColumn(name = "typeId", nullable = false)
private TypeEntity type;
@ManyToOne
@ManyToOne(cascade = CascadeType.REMOVE)
@JoinColumn(name = "userId", nullable = false)
private UserEntity user;
@ -29,6 +30,9 @@ public class HouseEntity extends BaseEntity {
@Column(nullable = false)
private String description;
@Column(nullable = false)
private String address;
@Column(nullable = false)
private Double price;
@ -36,11 +40,13 @@ public class HouseEntity extends BaseEntity {
super();
}
public HouseEntity(TypeEntity type, UserEntity user, String title, String description, Double price) {
public HouseEntity(TypeEntity type, UserEntity user, String title, String description, String address,
Double price) {
this.type = type;
this.user = user;
this.title = title;
this.description = description;
this.address = address;
this.price = price;
}
@ -76,6 +82,14 @@ public class HouseEntity extends BaseEntity {
this.description = description;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Double getPrice() {
return price;
}
@ -86,7 +100,7 @@ public class HouseEntity extends BaseEntity {
@Override
public int hashCode() {
return Objects.hash(id, type, user, title, description, price);
return Objects.hash(id, type, user, title, description, address, price);
}
@Override
@ -101,6 +115,7 @@ public class HouseEntity extends BaseEntity {
&& Objects.equals(other.getUser(), user)
&& Objects.equals(other.getTitle(), title)
&& Objects.equals(other.getDescription(), description)
&& Objects.equals(other.getAddress(), address)
&& Objects.equals(other.getPrice(), price);
}
}

View File

@ -4,7 +4,6 @@ import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
@ -21,6 +20,10 @@ public interface HouseRepository
Page<HouseEntity> findByUserId(long userId, Pageable pageable);
List<HouseEntity> findByTypeId(long typeId);
Page<HouseEntity> findByTypeId(long typeId, Pageable pageable);
List<HouseEntity> findByUserIdAndTypeId(long userId, long typeId);
Page<HouseEntity> findByUserIdAndTypeId(long userId, long typeId, Pageable pageable);

View File

@ -1,5 +1,6 @@
package com.example.demo.houses.service;
import java.util.Collection;
import java.util.List;
import java.util.stream.StreamSupport;
@ -9,6 +10,7 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.houses.repository.HouseRepository;
@ -30,24 +32,47 @@ public class HouseService {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<HouseEntity> getAllHouses(int page, int size) {
return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
}
@Transactional(readOnly = true)
public List<HouseEntity> getAll(Long typeId, Long userId) {
userService.get(userId);
if (typeId > 0) {
return repository.findByUserIdAndTypeId(typeId, userId);
return repository.findByTypeId(typeId);
}
return repository.findByUserId(userId);
if (userId >= 0) {
return repository.findByUserId(userId);
}
if (typeId > 0 && userId > 0) {
return repository.findByUserIdAndTypeId(userId, typeId);
}
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<HouseEntity> getAll(Long typeId, Long userId, int page, int size) {
final Pageable pageRequest = PageRequest.of(page, size);
if (typeId > 0) {
return repository.findByUserIdAndTypeId(typeId, userId, pageRequest);
return repository.findByTypeId(typeId, pageRequest);
}
return repository.findByUserId(userId, pageRequest);
if (userId > 0) {
return repository.findByUserId(userId, pageRequest);
}
if (typeId > 0 && userId > 0) {
return repository.findByUserIdAndTypeId(userId, typeId, pageRequest);
}
return repository.findAll(pageRequest);
}
@Transactional
@ -58,6 +83,24 @@ public class HouseService {
return house;
}
@Transactional
public HouseEntity getAdmin(Long id) {
final HouseEntity house = repository.findById(id)
.orElseThrow(() -> new NotFoundException(HouseEntity.class, id));
return house;
}
@Transactional(readOnly = true)
public List<HouseEntity> getByIds(Collection<Long> ids) {
final List<HouseEntity> houses = StreamSupport.stream(repository.findAllById(ids).spliterator(), false)
.toList();
if (houses.size() < ids.size()) {
throw new IllegalArgumentException("Invalid type");
}
return houses;
}
@Transactional
public HouseEntity getForOrder(Long id) {
final HouseEntity house = repository.findById(id)
@ -78,12 +121,13 @@ public class HouseService {
@Transactional
public HouseEntity update(Long id, Long userId, HouseEntity entity) {
userService.get(userId);
final HouseEntity existEntity = get(id, userId);
existEntity.setTitle(entity.getTitle());
existEntity.setDescription(entity.getDescription());
existEntity.setPrice(entity.getPrice());
existEntity.setType(entity.getType());
existEntity.setAddress(entity.getAddress());
existEntity.setUser(entity.getUser());
return repository.save(existEntity);
}

View File

@ -0,0 +1,157 @@
package com.example.demo.orders.api;
import java.util.Map;
import org.modelmapper.ModelMapper;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.core.api.PageAttributesMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.core.security.UserPrincipal;
import com.example.demo.houses.api.HouseDto;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.houses.service.HouseService;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService;
import com.example.demo.users.api.UserDto;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@Controller
@RequestMapping(OrderController.URL)
public class OrderController {
public static final String URL = "/order";
private static final String ORDER_VIEW = "order";
private static final String ORDER_EDIT_VIEW = "order-edit";
private static final String ORDER_ATTRIBUTE = "order";
private static final String ORDER_DETAILS_VIEW = "order-details";
private static final String PAGE_ATTRIBUTE = "page";
private final OrderService orderService;
private final HouseService houseService;
private final UserService userService;
private final ModelMapper modelMapper;
public OrderController(OrderService orderService, HouseService houseService, UserService userService,
ModelMapper modelMapper) {
this.orderService = orderService;
this.houseService = houseService;
this.userService = userService;
this.modelMapper = modelMapper;
}
private OrderDto toDto(OrderEntity entity) {
return modelMapper.map(entity, OrderDto.class);
}
private UserDto toUserDto(UserEntity entity) {
return modelMapper.map(entity, UserDto.class);
}
private HouseDto toHouseDto(HouseEntity entity) {
return modelMapper.map(entity, HouseDto.class);
}
private OrderEntity toEntity(OrderDto dto) {
final OrderEntity entity = modelMapper.map(dto, OrderEntity.class);
// entity.setUser(userService.get());
entity.setHouse(houseService.getForOrder(dto.getHouseId()));
return entity;
}
@GetMapping
public String getAll(
@RequestParam(name = "houseId", defaultValue = "0") Long houseId,
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int size,
@AuthenticationPrincipal UserPrincipal principal,
Model model) {
final long userId = principal.getId();
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
orderService.getAll(userId, houseId, page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attributes);
model.addAttribute(PAGE_ATTRIBUTE, page);
model.addAttribute(
"orders",
orderService.getAll(userId, houseId).stream().map(this::toDto).toList());
model.addAttribute(
"users",
userService.getAll().stream().map(this::toUserDto).toList());
model.addAttribute(
"houses",
houseService.getAllHouses().stream().map(this::toHouseDto).toList());
return ORDER_VIEW;
}
@GetMapping("details/{id}")
public String getOrderDetails(@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model,
@AuthenticationPrincipal UserPrincipal principal) {
final long userId = principal.getId();
model.addAttribute(ORDER_ATTRIBUTE, orderService.get(userId, id));
model.addAttribute(ORDER_ATTRIBUTE, toDto(orderService.get(userId, id)));
model.addAttribute(PAGE_ATTRIBUTE, page);
model.addAttribute("houses", houseService.getAllHouses().stream().map(this::toHouseDto).toList());
model.addAttribute("users", userService.getAll().stream().map(this::toUserDto).toList());
return ORDER_DETAILS_VIEW;
}
@GetMapping("/edit/")
public String create(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page, Model model) {
model.addAttribute(ORDER_ATTRIBUTE, new OrderDto());
model.addAttribute("houses", houseService.getAllHouses().stream().map(this::toHouseDto).toList());
model.addAttribute(PAGE_ATTRIBUTE, page);
return ORDER_EDIT_VIEW;
}
@PostMapping("/edit/")
public String create(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = ORDER_ATTRIBUTE) @Valid OrderDto order,
@AuthenticationPrincipal UserPrincipal principal,
BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return ORDER_EDIT_VIEW;
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
orderService.create(principal.getId(), toEntity(order));
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/delete/{id}")
public String delete(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
RedirectAttributes redirectAttributes,
@AuthenticationPrincipal UserPrincipal principal) {
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
orderService.delete(principal.getId(), id);
return Constants.REDIRECT_VIEW + URL;
}
}

View File

@ -0,0 +1,52 @@
package com.example.demo.orders.api;
import java.time.LocalDateTime;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public class OrderDto {
private Long id;
@NotNull
@Min(1)
private Long houseId;
@NotNull
private LocalDateTime datestart;
@NotNull
private LocalDateTime dateend;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getHouseId() {
return houseId;
}
public void setHouseId(Long houseId) {
this.houseId = houseId;
}
public LocalDateTime getDatestart() {
return datestart;
}
public void setDatestart(LocalDateTime datestart) {
this.datestart = datestart;
}
public LocalDateTime getDateend() {
return dateend;
}
public void setDateend(LocalDateTime dateend) {
this.dateend = dateend;
}
}

View File

@ -0,0 +1,97 @@
package com.example.demo.orders.model;
import java.time.LocalDateTime;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.users.model.UserEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import jakarta.persistence.CascadeType;
@Entity
@Table(name = "orders")
public class OrderEntity extends BaseEntity {
@ManyToOne(cascade = CascadeType.REMOVE)
@JoinColumn(name = "houseId", nullable = false)
private HouseEntity house;
@ManyToOne(cascade = CascadeType.REMOVE)
@JoinColumn(name = "userId", nullable = false)
private UserEntity user;
@Column(nullable = false)
private LocalDateTime datestart;
@Column(nullable = false)
private LocalDateTime dateend;
public OrderEntity() {
}
public OrderEntity(HouseEntity house, UserEntity user, LocalDateTime datestart, LocalDateTime dateend) {
this.house = house;
this.user = user;
this.datestart = datestart;
this.dateend = dateend;
}
public HouseEntity getHouse() {
return house;
}
public void setHouse(HouseEntity house) {
this.house = house;
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
// if (!user.getOrders().contains(this)) {
// user.getOrders().add(this);
// }
}
public LocalDateTime getDatestart() {
return datestart;
}
public void setDatestart(LocalDateTime datestart) {
this.datestart = datestart;
}
public LocalDateTime getDateend() {
return dateend;
}
public void setDateend(LocalDateTime dateend) {
this.dateend = dateend;
}
@Override
public int hashCode() {
return Objects.hash(id, house.getId(), user.getId(), datestart, dateend);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final OrderEntity other = (OrderEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getHouse().getId(), house.getId())
&& Objects.equals(other.getUser().getId(), user.getId())
&& Objects.equals(other.getDatestart(), datestart)
&& Objects.equals(other.getDateend(), dateend);
}
}

View File

@ -12,12 +12,9 @@ import com.example.demo.orders.model.OrderEntity;
public interface OrderRepository
extends CrudRepository<OrderEntity, Long>, PagingAndSortingRepository<OrderEntity, Long> {
Optional<OrderEntity> findOneByUserIdAndId(long userId, long id);
List<OrderEntity> findByHouseId(long houseId);
Page<OrderEntity> findByHouseId(long userId, Pageable pageable);
List<OrderEntity> findByUserId(long userId);
Page<OrderEntity> findByUserId(long userId, Pageable pageable);
@ -25,4 +22,5 @@ public interface OrderRepository
List<OrderEntity> findByUserIdAndHouseId(long userId, long houseId);
Page<OrderEntity> findByUserIdAndHouseId(long userId, long houseId, Pageable pageable);
}

View File

@ -66,9 +66,10 @@ public class OrderService {
public OrderEntity update(long userId, long id, OrderEntity entity) {
userService.get(userId);
final OrderEntity existsEntity = get(userId, id);
existsEntity.setUser(entity.getUser());
existsEntity.setHouse(entity.getHouse());
existsEntity.setPrice(entity.getPrice());
existsEntity.setCountPeople(entity.getCountPeople());
existsEntity.setDatestart(entity.getDatestart());
existsEntity.setDateend(entity.getDateend());
return repository.save(existsEntity);
}

View File

@ -0,0 +1,111 @@
package com.example.demo.types.api;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.core.configuration.Constants;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import jakarta.validation.Valid;
@Controller
@RequestMapping(TypeController.URL)
public class TypeController {
public static final String URL = Constants.ADMIN_PREFIX + "/type";
private static final String TYPE_VIEW = "type";
private static final String TYPE_EDIT_VIEW = "type-edit";
private static final String TYPE_ATTRIBUTE = "type";
private final TypeService typeService;
private final ModelMapper modelMapper;
public TypeController(TypeService typeService, ModelMapper modelMapper) {
this.typeService = typeService;
this.modelMapper = modelMapper;
}
private TypeDto toDto(TypeEntity entity) {
return modelMapper.map(entity, TypeDto.class);
}
private TypeEntity toEntity(TypeDto dto) {
return modelMapper.map(dto, TypeEntity.class);
}
@GetMapping
public String getAll(Model model) {
model.addAttribute(
"items",
typeService.getAll().stream()
.map(this::toDto)
.toList());
return TYPE_VIEW;
}
@GetMapping("/edit/")
public String create(Model model) {
model.addAttribute(TYPE_ATTRIBUTE, new TypeDto());
return TYPE_EDIT_VIEW;
}
@PostMapping("/edit/")
public String create(
@ModelAttribute(name = TYPE_ATTRIBUTE) @Valid TypeDto type,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
return TYPE_EDIT_VIEW;
}
typeService.create(toEntity(type));
return Constants.REDIRECT_VIEW + URL;
}
@GetMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
Model model) {
if (id <= 0) {
throw new IllegalArgumentException();
}
model.addAttribute(TYPE_ATTRIBUTE, toDto(typeService.get(id)));
return TYPE_EDIT_VIEW;
}
@PostMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@ModelAttribute(name = TYPE_ATTRIBUTE) @Valid TypeDto type,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
return TYPE_EDIT_VIEW;
}
if (id <= 0) {
throw new IllegalArgumentException();
}
typeService.update(id, toEntity(type));
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/delete/{id}")
public String delete(
@PathVariable(name = "id") Long id) {
typeService.delete(id);
return Constants.REDIRECT_VIEW + URL;
}
}

View File

@ -1,12 +1,9 @@
package com.example.demo.types.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class TypeDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank

View File

@ -45,5 +45,4 @@ public class TypeEntity extends BaseEntity {
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getName(), name);
}
}

View File

@ -8,4 +8,6 @@ import com.example.demo.types.model.TypeEntity;
public interface TypeRepository extends CrudRepository<TypeEntity, Long> {
Optional<TypeEntity> findByNameIgnoreCase(String name);
Optional<TypeEntity> findById(long id);
}

View File

@ -1,6 +1,8 @@
package com.example.demo.types.service;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
import org.springframework.stereotype.Service;
@ -18,8 +20,9 @@ public class TypeService {
this.repository = repository;
}
private void checkName(String name) {
if (repository.findByNameIgnoreCase(name).isPresent()) {
private void checkName(Long id, String name) {
final Optional<TypeEntity> existsType = repository.findByNameIgnoreCase(name);
if (existsType.isPresent() && !existsType.get().getId().equals(id)) {
throw new IllegalArgumentException(
String.format("Type with name %s is already exists", name));
}
@ -30,6 +33,15 @@ public class TypeService {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public List<TypeEntity> getByIds(Collection<Long> ids) {
final List<TypeEntity> types = StreamSupport.stream(repository.findAllById(ids).spliterator(), false).toList();
if (types.size() < ids.size()) {
throw new IllegalArgumentException("Invalid type");
}
return types;
}
@Transactional(readOnly = true)
public TypeEntity get(long id) {
return repository.findById(id)
@ -41,14 +53,14 @@ public class TypeService {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
checkName(entity.getName());
checkName(null, entity.getName());
return repository.save(entity);
}
@Transactional
public TypeEntity update(Long id, TypeEntity entity) {
final TypeEntity existsEntity = get(id);
checkName(entity.getName());
checkName(id, entity.getName());
existsEntity.setName(entity.getName());
return repository.save(existsEntity);
}

View File

@ -0,0 +1,137 @@
package com.example.demo.users.api;
import java.util.Map;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.core.api.PageAttributesMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@Controller
@RequestMapping(UserController.URL)
public class UserController {
public static final String URL = Constants.ADMIN_PREFIX + "/user";
private static final String USER_VIEW = "user";
private static final String USER_EDIT_VIEW = "user-edit";
private static final String PAGE_ATTRIBUTE = "page";
private static final String USER_ATTRIBUTE = "user";
private final UserService userService;
private final ModelMapper modelMapper;
public UserController(UserService userService, ModelMapper modelMapper) {
this.userService = userService;
this.modelMapper = modelMapper;
}
private UserDto toDto(UserEntity entity) {
return modelMapper.map(entity, UserDto.class);
}
private UserEntity toEntity(UserDto dto) {
return modelMapper.map(dto, UserEntity.class);
}
@GetMapping
public String getAll(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
userService.getAll(page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attributes);
model.addAttribute(PAGE_ATTRIBUTE, page);
return USER_VIEW;
}
@GetMapping("/edit/")
public String create(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
model.addAttribute(USER_ATTRIBUTE, new UserDto());
model.addAttribute(PAGE_ATTRIBUTE, page);
return USER_EDIT_VIEW;
}
@PostMapping("/edit/")
public String create(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserDto user,
BindingResult bindingResult,
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return USER_EDIT_VIEW;
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
userService.create(toEntity(user));
return Constants.REDIRECT_VIEW + URL;
}
@GetMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
if (id <= 0) {
throw new IllegalArgumentException();
}
model.addAttribute(USER_ATTRIBUTE, toDto(userService.get(id)));
model.addAttribute(PAGE_ATTRIBUTE, page);
return USER_EDIT_VIEW;
}
@PostMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserDto user,
BindingResult bindingResult,
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return USER_EDIT_VIEW;
}
if (id <= 0) {
throw new IllegalArgumentException();
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
userService.update(id, toEntity(user));
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/delete/{id}")
public String delete(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
userService.delete(id);
return Constants.REDIRECT_VIEW + URL;
}
}

View File

@ -0,0 +1,61 @@
package com.example.demo.users.api;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserDto {
private Long id;
@NotBlank
@Size(min = 3, max = 20)
private String login;
@NotBlank
private String fio;
@NotBlank
@Size(min = 12, max = 12)
private String numberphone;
private String role;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getFio() {
return fio;
}
public void setFio(String fio) {
this.fio = fio;
}
public String getNumberphone() {
return numberphone;
}
public void setNumberphone(String numberphone) {
this.numberphone = numberphone;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}

View File

@ -0,0 +1,121 @@
package com.example.demo.users.api;
import org.modelmapper.ModelMapper;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.core.api.PageAttributesMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.core.security.UserPrincipal;
import com.example.demo.houses.api.HouseDto;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.houses.service.HouseService;
import com.example.demo.orders.api.OrderDto;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService;
import com.example.demo.types.api.TypeDto;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@Controller
public class UserProfileController {
private static final String PROFILE_VIEW = "profile";
private static final String PAGE_ATTRIBUTE = "page";
private static final String HOUSEID_ATTRIBUTE = "houseId";
private static final String TYPEID_ATTRIBUTE = "typeId";
private static final String PROFILE_ATTRIBUTE = "profile";
private final OrderService orderService;
private final HouseService houseService;
private final UserService userService;
private final ModelMapper modelMapper;
public UserProfileController(OrderService orderService, HouseService houseService,
UserService userService, ModelMapper modelMapper) {
this.orderService = orderService;
this.houseService = houseService;
this.userService = userService;
this.modelMapper = modelMapper;
}
private OrderDto toDto(OrderEntity entity) {
return modelMapper.map(entity, OrderDto.class);
}
private HouseDto toHouseDto(HouseEntity entity) {
return modelMapper.map(entity, HouseDto.class);
}
private UserDto toUserDto(UserEntity entity) {
return modelMapper.map(entity, UserDto.class);
}
@GetMapping
public String getProfile(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@RequestParam(name = HOUSEID_ATTRIBUTE, defaultValue = "0") int houseId,
@RequestParam(name = TYPEID_ATTRIBUTE, defaultValue = "0") int typeId,
Model model,
@AuthenticationPrincipal UserPrincipal principal) {
final long userId = principal.getId();
model.addAttribute(PAGE_ATTRIBUTE, page);
model.addAttribute(HOUSEID_ATTRIBUTE, houseId);
model.addAttribute(
"orders",
orderService.getAll(userId, houseId).stream().map(this::toDto).toList());
model.addAttribute(
"users",
userService.getAll().stream().map(this::toUserDto).toList());
model.addAttribute(
"houses",
houseService.getAllHouses().stream().map(this::toHouseDto).toList());
model.addAllAttributes(PageAttributesMapper.toAttributes(
orderService.getAll(userId, houseId, page, Constants.DEFUALT_PAGE_SIZE),
this::toDto));
return PROFILE_VIEW;
}
@PostMapping
public String saveProfile(
@ModelAttribute(name = PROFILE_ATTRIBUTE) @Valid UserProfileDto profile,
BindingResult bindResult,
Model model,
@AuthenticationPrincipal UserPrincipal principal) {
if (bindResult.hasErrors()) {
return PROFILE_VIEW;
}
return Constants.REDIRECT_VIEW + "/";
}
@PostMapping("/delete/{id}")
public String deleteOrder(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@RequestParam(name = HOUSEID_ATTRIBUTE, defaultValue = "0") int houseId,
RedirectAttributes redirectAttributes,
@AuthenticationPrincipal UserPrincipal principal) {
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
redirectAttributes.addAttribute(HOUSEID_ATTRIBUTE, houseId);
orderService.delete(principal.getId(), id);
return Constants.REDIRECT_VIEW + "/";
}
}

View File

@ -0,0 +1,6 @@
package com.example.demo.users.api;
public class UserProfileDto {
public UserProfileDto() {
}
}

View File

@ -0,0 +1,65 @@
package com.example.demo.users.api;
import java.util.Objects;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.core.configuration.Constants;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@Controller
@RequestMapping(UserSignupController.URL)
public class UserSignupController {
public static final String URL = "/signup";
private static final String SIGNUP_VIEW = "signup";
private static final String USER_ATTRIBUTE = "user";
private final UserService userService;
private final ModelMapper modelMapper;
public UserSignupController(
UserService userService,
ModelMapper modelMapper) {
this.userService = userService;
this.modelMapper = modelMapper;
}
private UserEntity toEntity(UserSignupDto dto) {
return modelMapper.map(dto, UserEntity.class);
}
@GetMapping
public String getSignup(Model model) {
model.addAttribute(USER_ATTRIBUTE, new UserSignupDto());
return SIGNUP_VIEW;
}
@PostMapping
public String signup(
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserSignupDto user,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
return SIGNUP_VIEW;
}
if (!Objects.equals(user.getPassword(), user.getPasswordConfirm())) {
bindingResult.rejectValue("password", "signup:passwords", "Пароли не совпадают.");
model.addAttribute(USER_ATTRIBUTE, user);
return SIGNUP_VIEW;
}
userService.create(toEntity(user));
return Constants.REDIRECT_VIEW + Constants.LOGIN_URL + "?signup";
}
}

View File

@ -1,63 +1,27 @@
package com.example.demo.users.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
private String fio;
@NotBlank
private String email;
@NotBlank
@Size(min = 12, max = 12)
private String numberphone;
public class UserSignupDto {
@NotBlank
@Size(min = 3, max = 20)
private String login;
@NotBlank
@Size(min = 6, max = 32)
@Size(min = 3, max = 20)
private String password;
public Long getId() {
return id;
}
@NotBlank
@Size(min = 3, max = 20)
private String passwordConfirm;
public void setId(Long id) {
this.id = id;
}
@NotBlank
private String fio;
public String getFio() {
return fio;
}
public void setFio(String fio) {
this.fio = fio;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNumberphone() {
return numberphone;
}
public void setNumberphone(String numberphone) {
this.numberphone = numberphone;
}
@NotBlank
@Size(min = 12, max = 12)
private String numberphone;
public String getLogin() {
return login;
@ -74,4 +38,28 @@ public class UserDto {
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
public String getFio() {
return fio;
}
public void setFio(String fio) {
this.fio = fio;
}
public String getNumberphone() {
return numberphone;
}
public void setNumberphone(String numberphone) {
this.numberphone = numberphone;
}
}

View File

@ -1,74 +1,43 @@
package com.example.demo.users.model;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.orders.model.OrderEntity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
@Entity
@Table(name = "users")
public class UserEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 20)
private String login;
@Column(nullable = false, unique = false, length = 60)
private String password;
@Column(nullable = false, unique = false, length = 100)
private String fio;
@Column(nullable = false, unique = true, length = 30)
private String email;
@Column(nullable = false, unique = true, length = 12)
private String numberphone;
@Column(nullable = false, unique = true, length = 20)
private String login;
private UserRole role;
@Column(nullable = false, unique = false, length = 32)
private String password;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
@OrderBy("id ASC")
private Set<OrderEntity> orders = new HashSet<>();
// @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
// @OrderBy("id ASC")
// private Set<OrderEntity> orders = new HashSet<>();
public UserEntity() {
}
public UserEntity(String fio, String email, String numberphone, String login, String password) {
this.fio = fio;
this.email = email;
this.numberphone = numberphone;
public UserEntity(String login, String password, String fio, String numberphone) {
this.login = login;
this.password = password;
}
public String getFio() {
return fio;
}
public void setFio(String fio) {
this.fio = fio;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNumberphone() {
return numberphone;
}
public void setNumberphone(String numberphone) {
this.numberphone = numberphone;
this.role = UserRole.USER;
}
public String getLogin() {
@ -87,20 +56,44 @@ public class UserEntity extends BaseEntity {
this.password = password;
}
public Set<OrderEntity> getOrders() {
return orders;
public String getFio() {
return fio;
}
public void addOrder(OrderEntity order) {
if (order.getUser() != this) {
order.setUser(this);
}
orders.add(order);
public void setFio(String fio) {
this.fio = fio;
}
public String getNumberphone() {
return numberphone;
}
public void setNumberphone(String numberphone) {
this.numberphone = numberphone;
}
public UserRole getRole() {
return role;
}
public void setRole(UserRole role) {
this.role = role;
}
// public Set<OrderEntity> getOrders() {
// return orders;
// }
// public void addOrder(OrderEntity order) {
// if (order.getUser() != this) {
// order.setUser(this);
// }
// orders.add(order);
// }
@Override
public int hashCode() {
return Objects.hash(id, fio, email, numberphone, login, password, orders);
return Objects.hash(id, login, password, fio, numberphone, role/* orders */);
}
@Override
@ -111,11 +104,11 @@ public class UserEntity extends BaseEntity {
return false;
UserEntity other = (UserEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getFio(), fio)
&& Objects.equals(other.getEmail(), email)
&& Objects.equals(other.getNumberphone(), numberphone)
&& Objects.equals(other.getLogin(), login)
&& Objects.equals(other.getPassword(), password)
&& Objects.equals(other.getOrders(), orders);
&& Objects.equals(other.getFio(), fio)
&& Objects.equals(other.getNumberphone(), numberphone)
&& Objects.equals(other.getRole(), role);
// && Objects.equals(other.getOrders(), orders);
}
}

View File

@ -0,0 +1,16 @@
package com.example.demo.users.model;
import org.springframework.security.core.GrantedAuthority;
public enum UserRole implements GrantedAuthority {
ADMIN,
OWNER,
USER;
private static final String PREFIX = "ROLE_";
@Override
public String getAuthority() {
return PREFIX + this.name();
}
}

View File

@ -0,0 +1,115 @@
package com.example.demo.users.service;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.example.demo.core.configuration.Constants;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.core.security.UserPrincipal;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.model.UserRole;
import com.example.demo.users.repository.UserRepository;
@Service
public class UserService implements UserDetailsService {
private final UserRepository repository;
private final PasswordEncoder passwordEncoder;
public UserService(UserRepository repository, PasswordEncoder passwordEncoder) {
this.repository = repository;
this.passwordEncoder = passwordEncoder;
}
private void checkLogin(Long id, String login) {
final Optional<UserEntity> existsUser = repository.findByLoginIgnoreCase(login);
if (existsUser.isPresent() && !existsUser.get().getId().equals(id)) {
throw new IllegalArgumentException(
String.format("User with login %s is already exists", login));
}
}
private void checkPassword(Long id, String password) {
final Optional<UserEntity> existsUser = repository.findByPasswordIgnoreCase(password);
if (existsUser.isPresent() && !existsUser.get().getId().equals(id)) {
throw new IllegalArgumentException(
String.format("User with password %s is already exists", password));
}
}
@Transactional(readOnly = true)
public UserEntity getByLogin(String login) {
return repository.findByLoginIgnoreCase(login)
.orElseThrow(() -> new IllegalArgumentException("Invalid login"));
}
@Transactional(readOnly = true)
public List<UserEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<UserEntity> getAll(int page, int size) {
return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
}
@Transactional(readOnly = true)
public UserEntity get(long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(UserEntity.class, id));
}
@Transactional
public UserEntity create(UserEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
checkLogin(null, entity.getLogin());
checkPassword(null, entity.getPassword());
final String password = Optional.ofNullable(entity.getPassword()).orElse("");
entity.setPassword(
passwordEncoder.encode(
StringUtils.hasText(password.strip()) ? password : Constants.DEFAULT_PASSWORD));
entity.setRole(Optional.ofNullable(entity.getRole()).orElse(UserRole.USER));
repository.save(entity);
return repository.save(entity);
}
@Transactional
public UserEntity update(long id, UserEntity entity) {
final UserEntity existsEntity = get(id);
checkLogin(id, entity.getLogin());
existsEntity.setLogin(entity.getLogin());
existsEntity.setFio(entity.getFio());
existsEntity.setNumberphone(entity.getNumberphone());
repository.save(existsEntity);
return existsEntity;
}
@Transactional
public UserEntity delete(long id) {
final UserEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final UserEntity existsUser = getByLogin(username);
return new UserPrincipal(existsUser);
}
}

View File

@ -13,7 +13,7 @@ spring.datasource.password=password
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create
spring.jpa.open-in-view=false
# spring.jpa.show-sql=true
spring.jpa.show-sql=true
# spring.jpa.properties.hibernate.format_sql=true
# H2 console

Binary file not shown.

After

Width:  |  Height:  |  Size: 452 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 179 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

View File

@ -0,0 +1,96 @@
html,
body {
height: 100%;
background-color: aqua;
}
h1 {
font-size: 1.5em;
}
h2 {
font-size: 1.25em;
}
h3 {
font-size: 1.1em;
}
td form {
margin: 0;
padding: 0;
margin-top: -.25em;
}
.button-fixed-width {
width: 150px;
}
.button-link {
padding: 0;
}
.invalid-feedback {
display: block;
}
.w-10 {
width: 10% !important;
}
.my-navbar {
background-color: #3c3c3c !important;
}
.my-navbar .link a:hover {
text-decoration: underline;
}
.my-navbar .logo {
width: 26px;
height: 26px;
}
.my-footer {
background-color: #2c2c2c;
height: 52px;
color: rgba(255, 255, 255, 0.5);
}
.cart-image {
width: 3.1rem;
padding: 0.25rem;
border-radius: 0.5rem;
}
.title-text {
color: black;
}
.card-text {
color: black;
width: 250px;
overflow: auto;
}
.card-text-full {
color: black;
width: 450px;
overflow: auto;
}
.cart-item {
height: auto;
}
.card {
background-color: white;
width: 18rem;
text-overflow: clip;
overflow: auto;
}
.card-text {
width: 250px;
overflow: auto;
}

View File

@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-cart2" viewBox="0 0 16 16">
<path d="M0 2.5A.5.5 0 0 1 .5 2H2a.5.5 0 0 1 .485.379L2.89 4H14.5a.5.5 0 0 1 .485.621l-1.5 6A.5.5 0 0 1 13 11H4a.5.5 0 0 1-.485-.379L1.61 3H.5a.5.5 0 0 1-.5-.5zM3.14 5l1.25 5h8.22l1.25-5H3.14zM5 13a1 1 0 1 0 0 2 1 1 0 0 0 0-2zm-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0zm9-1a1 1 0 1 0 0 2 1 1 0 0 0 0-2zm-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0z"/>
</svg>

After

Width:  |  Height:  |  Size: 463 B

View File

@ -0,0 +1,24 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
width="512.000000pt" height="512.000000pt" viewBox="0 0 512.000000 512.000000"
preserveAspectRatio="xMidYMid meet">
<metadata>
Created by potrace 1.16, written by Peter Selinger 2001-2019
</metadata>
<g transform="translate(0.000000,512.000000) scale(0.100000,-0.100000)"
fill="#000000" stroke="none">
<path d="M2433 4582 c-28 -10 -69 -30 -90 -44 -71 -47 -2330 -1935 -2336
-1952 -13 -32 -7 -91 10 -116 9 -14 62 -78 116 -143 111 -131 125 -139 203
-122 12 3 516 417 1120 920 604 503 1101 915 1104 915 3 0 502 -414 1109 -919
839 -699 1110 -920 1134 -924 18 -2 44 0 59 5 23 8 189 193 241 268 23 33 22
101 -2 131 -11 13 -175 152 -365 309 l-345 285 -1 668 0 669 -29 29 -29 29
-347 0 c-381 0 -383 0 -404 -62 -7 -20 -11 -145 -11 -339 l0 -309 -396 331
c-273 228 -414 339 -453 357 -75 35 -211 42 -288 14z"/>
<path d="M1643 3027 l-913 -752 0 -800 0 -801 23 -44 c13 -26 40 -57 65 -75
l44 -30 649 -3 649 -2 0 610 0 610 400 0 400 0 0 -610 0 -610 649 2 649 3 44
30 c23 17 53 49 65 70 l23 40 0 805 0 805 -910 750 c-501 413 -914 751 -918
752 -4 2 -418 -336 -919 -750z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
<svg fill="#000000" width="800px" height="800px" class="bi house" viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">
<title>house</title>
<path d="M0 16h4l12-13.696 12 13.696h4l-13.984-16h-4zM4 32h8v-9.984q0-0.832 0.576-1.408t1.44-0.608h4q0.8 0 1.408 0.608t0.576 1.408v9.984h8v-13.408l-12-13.248-12 13.248v13.408zM26.016 6.112l4 4.576v-8.672h-4v4.096z"></path>
</svg>

After

Width:  |  Height:  |  Size: 506 B

View File

@ -0,0 +1,86 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Корзина</title>
</head>
<body>
<main layout:fragment="content">
<div class="d-flex flex-column align-items-center">
<div class="mb-2 col-12 col-md-8 col-lg-6 d-flex align-items-center">
<strong class="flex-fill">Корзина</strong>
<form action="#" th:action="@{/cart/clear}" method="post">
<button type="submit" class="btn btn-danger button-fixed-width"
onclick="return confirm('Вы уверены?')">
<i class="bi bi-x-lg"></i> Очистить
</button>
</form>
</div>
<div class="card col-12 col-md-8 col-lg-6 align-items-center" th:each="cartItem : ${cart}">
<div class="card-body col-12 p-2 d-flex flex-row align-items-center justify-content-center">
<div class="col-9">
[[${cartItem.typeName}]] [[${#numbers.formatDecimal(cartItem.price, 1, 2)}]] *
[[${cartItem.count}]]
=
[[${#numbers.formatDecimal(cartItem.price * cartItem.count, 1, 2)}]]
</div>
<div class="col-3 d-flex justify-content-end">
<form action="#"
th:action="@{/cart/increase?type={type}&price={price}(type=${cartItem.type},price=${cartItem.price})}"
method="post">
<button type="submit" class="btn btn-primary">
<i class="bi bi-plus-lg"></i>
</button>
</form>
<form action="#"
th:action="@{/cart/decrease?type={type}&price={price}(type=${cartItem.type},price=${cartItem.price})}"
method="post">
<button class="btn btn-danger">
<i class="bi bi-dash-lg"></i>
</button>
</form>
</div>
</div>
</div>
<div class=" mb-2 col-12 col-md-8 col-lg-6 d-flex justify-content-end">
<strong>Итого: [[${#numbers.formatDecimal(totalCart, 1, 2)}]] &#8381;</strong>
</div>
<div class="mb-2 col-12 col-md-8 col-lg-6 d-flex justify-content-center"
th:if="${not #lists.isEmpty(cart)}">
<form action="#" th:action="@{/cart/save}" method="post">
<button type="submit" class="btn btn-primary" onclick="return confirm('Вы уверены?')">
Оформить заказ
</button>
</form>
</div>
</div>
<div class="mb-2">
<form action=" #" th:action="@{/cart}" th:object="${order}" method="post">
<div class="mb-2">
<label for="type" class="form-label">Товары</label>
<select th:field="*{type}" id="type" class="form-select">
<option selected value="">Укажите тип товара</option>
<option th:each="type : ${types}" th:value="${type.id}">[[${type.name}]]</option>
</select>
<div th:if="${#fields.hasErrors('type')}" th:errors="*{type}" class="invalid-feedback"></div>
</div>
<div class="mb-2">
<label for="price" class="form-label">Цена</label>
<input type="number" th:field="*{price}" id="price" class="form-control" step="0.50">
<div th:if="${#fields.hasErrors('price')}" th:errors="*{price}" class="invalid-feedback"></div>
</div>
<div class="mb-2">
<label for="count" class="form-label">Количество</label>
<input type="number" th:field="*{count}" id="count" class="form-control" value="0" step="1">
<div th:if="${#fields.hasErrors('count')}" th:errors="*{count}" class="invalid-feedback"></div>
</div>
<button type="submit" class="btn btn-primary">Добавить в корзину</button>
</form>
</div>
</main>
</body>
</html>
</html>

View File

@ -0,0 +1,82 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Каталог</title>
</head>
<body>
<main layout:fragment="content" class="w-100 mx-auto main">
<div class="tab-content mt-2">
<h2 class="text-center title-text"> Каталог недвижимости </h2>
<div class="tab-pane container active table-responsive" id="orders">
<form th:action="@{/catalog}" method="get" class="row mt-2 w-50 mx-auto pb-3">
<div class="pb-3">
<input type="hidden" th:name="page" th:value="${page}">
<select th:name="typeId" id="typeId" class="form-select">
<option selected value="">Фильтр по типу</option>
<option th:each="type : ${types}" th:value="${type.id}" th:selected="${type.id==typeId}">
[[${type.name}]]
</option>
</select>
</select>
<input type="hidden" th:name="page" th:value="${page}">
<select th:name="userId" id="userId" class="form-select">
<option selected value="">Фильтр по владельцу </option>
<option th:each="user : ${users}" th:value="${user.id}" th:selected="${user.id==userId}">
[[${user.login}]]
</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Показать</button>
</form>
<div class="container mt-2 mb-5">
<div class="row">
<div class="col" th:each="house : ${items}">
<div class="col pb-4">
<div class="card mx-auto card-text text-center" style="width: 18rem;">
<img src="/Image10.jpg" class="card-img-top" width="100%" height="200px" alt="dom">
<div class="card-body">
<h2 th:text="${house.title}"></h2>
<div class="mt-1"> Тип:
<th:block th:each="type : ${types}">
<th:block th:if="${type.Id} eq ${house.typeId}">
<th scope="row" th:text="${type.name}"></th>
</th:block>
</th:block>
</div>
<div class="mt-1">
<th:block th:each="user : ${users}">
<th:block th:if="${user.Id} eq ${house.userId}">
<th scope="row" th:text="${user.fio}"></th>
</th:block>
</th:block>
</div>
<p th:text="${house.description}"></p>
<form th:action="@{/catalog/house-one/{id}(id=${house.id})}" method="get"
class="align-items-center mx-auto text-center">
<input type="hidden" th:name="page" th:value="${page}">
<button type="submit" class="btn btn-primary">
<p class="mt-2" th:text="${house.price} + ₽"></p>
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<th:block th:replace="~{ pagination :: pagination (
url='catalog',
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</div>
</div>
</main>
</body>
</html>

View File

@ -0,0 +1,73 @@
<!DOCTYPE html>
<html lang="ru" data-bs-theme="dark" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity6">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/house-com.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title layout:title-pattern="$LAYOUT_TITLE - $CONTENT_TITLE">UlRent.ru</title>
<script type="text/javascript" src="/webjars/bootstrap/5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="/webjars/bootstrap/5.3.3/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="/webjars/bootstrap-icons/1.11.3/font/bootstrap-icons.min.css" />
<link rel="stylesheet" href="/css/style.css" />
</head>
<body class="h-100 d-flex flex-column">
<nav class="navbar navbar-expand-md my-navbar" data-bs-theme="dark">
<div class="container-fluid">
<a class="navbar-brand" href="/">
<i class="d-inline-block align-top me-1 logo"></i>
UlRent.ru
</a>
<a class="navbar-brand" href="/catalog">
<i class="d-inline-block align-top me-1 logo"></i>
Каталог
</a>
<th:block sec:authorize="isAuthenticated()" th:with="userName=${#authentication.name}">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#main-navbar"
aria-controls="main-navbar" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="main-navbar">
<ul class="navbar-nav me-auto link" th:with="activeLink=${#objects.nullSafe(servletPath, '')}">
<a class="nav-link" href="/order"
th:classappend="${activeLink.startsWith('/order') ? 'active' : ''}">
Заказы
</a>
<th:block sec:authorize="hasRole('ADMIN')">
<a class="nav-link" href="/admin/user"
th:classappend="${activeLink.startsWith('/admin/user') ? 'active' : ''}">
Пользователи
</a>
<a class="nav-link" href="/admin/type"
th:classappend="${activeLink.startsWith('/admin/type') ? 'active' : ''}">
Типы недвижимости
</a>
<a class="nav-link" href="/admin/house"
th:classappend="${activeLink.startsWith('/admin/house') ? 'active' : ''}">
Списки домов
</a>
<a class="nav-link" href="/admin/h2-console/" target="_blank">Консоль H2</a>
</th:block>
</ul>
<ul class="navbar-nav" th:if="${not #strings.isEmpty(userName)}">
<form th:action="@{/logout}" method="post">
<button type="submit" class="navbar-brand nav-link" onclick="return confirm('Вы уверены?')">
Выход ([[${userName}]])
</button>
</form>
</ul>
</div>
</th:block>
</div>
</nav>
<main class="container-fluid p-2" layout:fragment="content">
</main>
<footer class="my-footer mt-auto d-flex flex-shrink-0 justify-content-center align-items-center">
Автор, [[${#dates.year(#dates.createNow())}]]
</footer>
</body>
</html>

View File

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Ошибка</title>
</head>
<body>
<main layout:fragment="content">
<ul class="list-group mb-2">
<th:block th:if="${#strings.isEmpty(message)}">
<li class="list-group-item">
Неизвестная ошибка
</li>
</th:block>
<th:block th:if="${not #strings.isEmpty(message)}">
<li class="list-group-item">
<strong>Ошибка:</strong> [[${message}]]
</li>
</th:block>
<th:block th:if="${not #strings.isEmpty(url)}">
<li class="list-group-item">
<strong>Адрес:</strong> [[${url}]]
</li>
<li class="list-group-item">
<strong>Класс исключения:</strong> [[${exception}]]
</li>
<li class="list-group-item">
[[${method}]] ([[${file}]]:[[${line}]])
</li>
</th:block>
</ul>
<a class="btn btn-primary button-fixed-width" href="/">На главную</a>
</main>
</body>
</html>

View File

@ -0,0 +1,62 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Редакторовать недвижимость</title>
</head>
<body>
<main layout:fragment="content">
<form action="#" th:action="@{/admin/house/edit/{id}(id=${house.id})}" th:object="${house}" method="post">
<h2 class="text-center title-text mt-4"> Недвижимость </h2>
<div class="mb-3">
<label for="id" class="form-label title-text">ID</label>
<input type="text" th:value="*{id}" id="id" class="form-control" readonly disabled>
</div>
<div class="mb-3">
<label for="title" class="form-label title-text">Название недвижимости</label>
<input type="text" th:field="*{title}" id="title" class="form-control">
<div th:if="${#fields.hasErrors('title')}" th:errors="*{title}" class="invalid-feedback"></div>
</div>
<div class="mb-3">
<label for="type" class="form-label title-text"> Тип недвижимости </label>
<select th:field="*{typeId}" id="typeId" class="form-select">
<option selected value=""> Укажите тип </option>
<option th:each="type : ${types}" th:value="${type.id}"> [[${type.name}]] </option>
</select>
</div>
<div class="mb-3">
<label for="user" class="form-label title-text"> Собственник </label>
<select th:field="*{userId}" id="userId" class="form-select">
<option selected value=""> Укажите собственника </option>
<option th:each="user : ${users}" th:value="${user.id}"> [[${user.login}]] </option>
</select>
</div>
<div class="mb-3">
<label for="description" class="form-label title-text">Описание недвижимости</label>
<input type="text" th:field="*{description}" id="description" class="form-control">
<div th:if="${#fields.hasErrors('description')}" th:errors="*{description}" class="invalid-feedback">
</div>
</div>
<div class="mb-3">
<label for="address" class="form-label title-text">Адрес</label>
<input type="text" th:field="*{address}" id="address" class="form-control">
<div th:if="${#fields.hasErrors('address')}" th:errors="*{address}" class="invalid-feedback">
</div>
</div>
<div class="mb-3">
<label for="price" class="form-label title-text">Цена</label>
<input type="text" th:field="*{price}" id="price" class="form-control">
<div th:if="${#fields.hasErrors('price')}" th:errors="*{price}" class="invalid-feedback">
</div>
</div>
<div class="mb-3 d-flex flex-row">
<button class="btn btn-primary me-2 button-fixed-width" type="submit">Сохранить</button>
<a class="btn btn-secondary button-fixed-width" href="/admin/house">Отмена</a>
</div>
</form>
</main>
</body>
</html>

View File

@ -0,0 +1,63 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Редакторовать недвижимость</title>
</head>
<body>
<main layout:fragment="content">
<form action="#" th:action="@{/catalog/house-one/{id}(id=${house.id})}" th:object="${house}" method="post">
<div class="container mt-2 mb-5">
<div class="card mx-auto card-text text-center" style="width: 42rem;">
<img src="/Image10.jpg" class="card-img-top2" width="100%" height="400px" alt="dom" />
<div class="card-body">
<h5 class="card-title">Информация о недвижимости</h5>
<p class="card-text-full d-flex flex-row justify-content-start ms-5"><strong>Название
недвижимости: </strong> <span th:text="${house.title}"></span>
</p>
<h3 class="d-flex flex-row justify-content-start title-text ms-5"> Тип недвижимости:
<th:block th:each="type : ${types}">
<th:block th:if="${type.Id} eq ${house.typeId}">
<th th:text="${type.name}"></th>
</th:block>
</th:block>
</h3>
<h3 class="d-flex flex-row justify-content-start title-text ms-5"> Владелец:
<th:block th:each="user : ${users}">
<th:block th:if="${user.Id} eq ${house.userId}">
<th scope="row" th:text="${user.fio}"></th>
</th:block>
</th:block>
</h3>
<p class="card-text-full d-flex flex-row justify-content-start ms-5"><strong>Адрес
недвижимости: </strong> <span th:text="${house.address}"></span>
</p>
<h3 class="title-text ms-5 d-flex flex-row justify-content-start"> Мобильный телефон:
<th:block th:each="user : ${users}">
<th:block th:if="${user.Id} eq ${house.userId}">
<th scope="row" th:text="${user.numberphone}"></th>
</th:block>
</th:block>
</h3>
<p class="title-text ms-5 d-flex flex-row justify-content-start"><strong> Описание: </strong>
<span th:text="${house.description}"></span></p>
<p class="card-text d-flex flex-row justify-content-start ms-5"><strong>Цена:</strong> <span
th:text="${house.price}"></span>
</p>
<div class="d-flex flex-row justify-content-center mt-3">
<a class="btn btn-primary me-2 button-fixed-width" href="/order"
th:href="@{/order/edit/(page=${page})}">Создать заказ</a>
<a class="btn btn-secondary button-fixed-width" href="/catalog">Назад</a>
</div>
</div>
</div>
</div>
</form>
</main>
</body>
</html>

View File

@ -0,0 +1,63 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Недвижимость</title>
</head>
<body>
<main layout:fragment="content">
<th:block th:switch="${houses.size()}">
<h2 th:case="0">Данные отсутствуют</h2>
<th:block th:case="*">
<h2 class="title-text text-center mt-3">Недвижимость</h2>
<div>
<a th:href="@{/admin/house/edit/(page=${page})}" class="btn btn-primary mb-3">Добавить
недвижимость</a>
</div>
<table class="table">
<caption></caption>
<thead>
<tr>
<th scope="col" class="w-10">ID</th>
<th scope="col" class="w-auto">Название недвижимости</th>
<th scope="col" class="w-auto">Тип недвижимости</th>
<th scope="col" class="w-auto"> Описание</th>
<th scope="col" class="w-auto"> Цена</th>
<th scope="col" class="w-auto"> Редактировать</th>
<th scope="col" class="w-auto"> Удаление</th>
</tr>
</thead>
<tbody>
<tr th:each="house : ${houses}">
<th scope="row" th:text="${house.id}"></th>
<td th:text="${house.title}"></td>
<td th:text="${house.typeId}"></td>
<td th:text="${house.description}"></td>
<td th:text="${house.price}"></td>
<td>
<form th:action="@{/admin/house/edit/{id}(id=${house.id})}" method="get">
<input type="hidden" th:name="page" th:value="${page}">
<button type="submit" class="btn btn-link button-link">Редактировать</button>
</form>
</td>
<td>
<form th:action="@{/admin/house/delete/{id}(id=${house.id})}" method="post">
<input type="hidden" th:name="page" th:value="${page}">
<button type="submit" class="btn btn-link button-link"
onclick="return confirm('Вы уверены?')">Удалить</button>
</form>
</td>
</tr>
</tbody>
</table>
</th:block>
<th:block th:replace="~{ pagination :: pagination (
url=${'admin/house'},
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</th:block>
</main>
</body>
</html>

View File

@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Вход</title>
</head>
<body>
<main layout:fragment="content">
<form action="#" th:action="@{/login}" method="post" class="mx-auto w-25 mt-3">
<div th:if="${param.error}" class="alert alert-danger">
Неверный логин или пароль
</div>
<div th:if="${param.logout}" class="alert alert-success">
Выход успешно произведен
</div>
<div th:if="${param.signup}" class="alert alert-success">
Пользователь успешно создан
</div>
<div class="mb-3">
<label for="username" class="form-label title-text">Имя пользователя</label>
<input type="text" id="username" name="username" class="form-control" required minlength="3"
maxlength="20">
</div>
<div class="mb-3">
<label for="password" class="form-label title-text">Пароль</label>
<input type="password" id="password" name="password" class="form-control" required minlength="3"
maxlength="20">
</div>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" id="remember-me" name="remember-me" checked>
<label class="form-check-label title-text" for="remember-me">Запомнить меня</label>
</div>
<div class="mb-3 d-flex flex-row">
<button class="btn btn-primary me-2 button-fixed-width" type="submit">Войти</button>
<a class="btn btn-secondary button-fixed-width" href="/signup">Регистрация</a>
</div>
</form>
</main>
</body>
</html>
</html>

View File

@ -0,0 +1,78 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Детали заказа</title>
</head>
<body>
<main layout:fragment="content">
<h1 class="title-text text-center">Заказ №[[${order.id}]], [[${#temporals.format(order.datestart, 'HH:mm
dd-MM-yyyy')}]]
</h1>
<button class="btn btn-primary mt-2 ms-3" onclick="history.back()">Назад</button>
<table class="table mt-2">
<caption></caption>
<thead>
<tr>
<th scope="col" class="w-10">Номер</th>
<th scope="col" class="w-auto">Начало брони</th>
<th scope="col" class="w-auto">Конец брони</th>
<th scope="col" class="w-auto">Недвижимость</th>
<th scope="col" class="w-auto">Цена</th>
<th scope="col" class="w-auto">Адрес</th>
</tr>
</thead>
<tbody>
<td th:text="${order.id}"></td>
<td th:text="${#temporals.format(order.datestart, 'yyyy-MM-dd HH:mm')}"></td>
<td th:text="${#temporals.format(order.dateend, 'yyyy-MM-dd HH:mm')}"></td>
<div class="mt-1">
<th:block th:each="house : ${houses}">
<th:block th:if="${house.Id} eq ${order.houseId}">
<th scope="row" th:text="${house.title}"></th>
</th:block>
</th:block>
</div>
<div class="mt-1">
<th:block th:each="house : ${houses}">
<th:block th:if="${house.Id} eq ${order.houseId}">
<th scope="row" th:text="${house.price}"></th>
</th:block>
</th:block>
</div>
<div class="mt-1">
<th:block th:each="house : ${houses}">
<th:block th:if="${house.Id} eq ${order.houseId}">
<th scope="row" th:text="${house.address}"></th>
</th:block>
</th:block>
</div>
<!-- <div class="mt-1">
<th:block th:each="user : ${users}">
<th:block th:if="${user.Id} eq ${order.userId}">
<th scope="row" th:text="${user.fio}"></th>
</th:block>
</th:block>
</div>
<div class="mt-1">
<th:block th:each="user : ${users}">
<th:block th:if="${user.Id} eq ${order.userId}">
<th scope="row" th:text="${user.numberphone}"></th>
</th:block>
</th:block>
</div> -->
</tbody>
</table>
<th:block th:replace="~{ pagination :: pagination (
url='',
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</main>
</body>
</html>

View File

@ -0,0 +1,47 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Оформление заказа</title>
</head>
<body>
<main layout:fragment="content">
<form action="#" th:action="@{/order/edit/{id}(id=${order.id})}" th:object="${order}" method="post"
class="w-50 mx-auto">
<h2 class="title-text text-center"> Заявка на бронь </h2>
<div class="mb-3">
<label for="id" class="form-label title-text">ID</label>
<input type="text" th:value="*{id}" id="id" class="form-control" readonly disabled>
</div>
<div class="mb-3">
<label for="house" class="form-label title-text"> Недвижимости </label>
<select th:field="*{houseId}" id="houseId" class="form-select">
<option selected value=""> Укажите недвижимость </option>
<option th:each="house : ${houses}" th:value="${house.id}"> [[${house.title}]] </option>
</select>
</div>
<div class="mb-3">
<label for="datestart" class="form-label title-text">Дата начала </label>
<input type="datetime-local" th:field="*{datestart}" id="datestart" class="form-control">
<div th:if="${#fields.hasErrors('datestart')}" th:errors="*{datestart}" class="invalid-feedback">
</div>
</div>
<div class="mb-3">
<label for="dateend" class="form-label title-text">Дата окончания</label>
<input type="datetime-local" th:field="*{dateend}" id="dateend" class="form-control">
<div th:if="${#fields.hasErrors('dateend')}" th:errors="*{dateend}" class="invalid-feedback">
</div>
</div>
<div class="mb-3 d-flex flex-row">
<button class="btn btn-primary me-2 button-fixed-width" type="submit">Сохранить</button>
<a class="btn btn-secondary button-fixed-width" href="/">Отмена</a>
</div>
</form>
</main>
</body>
</html>

View File

@ -0,0 +1,53 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<body>
<main layout:fragment="content" class="w-75 mx-auto">
<th:block th:switch="${items.size()}">
<h2 th:case="0" class="text-center title-text">Данные отсутствуют</h2>
<th:block th:case="*">
<h2 class="title-text text-center mt-3">Заявка на бронь (Заказы)</h2>
<div>
<a th:href="@{/order/edit/(page=${page})}" class="btn btn-primary mb-3"> Создать заказ</a>
</div>
<table class="table mt-2">
<caption></caption>
<thead>
<tr>
<th scope="col" class="w-10">ID</th>
<th scope="col" class="w-auto">Дата бронирования</th>
<th scope="col" class="w-auto">Выселение</th>
<th scope="col" class="w-auto"> Подробно </th>
</tr>
</thead>
<tbody>
<tr th:each="order : ${orders}">
<th scope="row" th:text="${order.id}"></th>
<td th:text="${#temporals.format(order.datestart, 'dd-MM-yyyy')}"></td>
<td th:text="${#temporals.format(order.dateend, 'dd-MM-yyyy')}"></td>
<td>
<form th:action="@{/order/details/{id}(id=${order.id})}" method="get">
<input type="hidden" th:name="page" th:value="${page}">
<button type="submit" class="btn btn-link button-link"
onclick="return confirm('Вы уверены?')">Детали</button>
</form>
</td>
</tr>
</tbody>
</table>
</th:block>
<th:block th:replace="~{ pagination :: pagination (
url='/',
totalPages=${totalPages},
currentPage=${currentPage}) }" />
<div class="mt-2 d-flex justify-content-center">
<a class="btn btn-primary" th:href="@{/order/edit/(page=${page})}">Создать заказ</a>
</div>
</th:block>
</main>
</body>
</html>

View File

@ -0,0 +1,51 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<th:block th:fragment="pagination (url, totalPages, currentPage)">
<nav th:if="${totalPages > 1}" th:with="
maxPage=2,
currentPage=${currentPage + 1}">
<ul class="pagination justify-content-center"
th:with="
seqFrom=${currentPage - maxPage < 1 ? 1 : currentPage - maxPage},
seqTo=${currentPage + maxPage > totalPages ? totalPages : currentPage + maxPage}">
<th:block th:if="${currentPage > maxPage + 1}">
<li class="page-item">
<a class="page-link" aria-label="Previous" th:href="@{/{url}?page=0(url=${url})}">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
<li class="page-item disabled">
<span class="page-link" aria-label="Previous">
<span aria-hidden="true">&hellip;</span>
</span>
</li>
</th:block>
<li class="page-item" th:each="page : ${#numbers.sequence(seqFrom, seqTo)}"
th:classappend="${page == currentPage} ? 'active' : ''">
<a class=" page-link" th:href="@{/{url}?page={page}(url=${url},page=${page - 1})}">
<span th:text="${page}" />
</a>
</li>
<th:block th:if="${currentPage < totalPages - maxPage}">
<li class="page-item disabled">
<span class="page-link" aria-label="Previous">
<span aria-hidden="true">&hellip;</span>
</span>
</li>
<li class="page-item">
<a class="page-link" aria-label="Next"
th:href="@{/{url}?page={page}(url=${url},page=${totalPages - 1})}">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
</th:block>
</ul>
</nav>
</th:block>
</body>
</html>

View File

@ -0,0 +1,98 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Личный кабинет</title>
</head>
<body>
<main layout:fragment="content" class="mx-auto">
<div>
<h2 class="title-text text-center mt-3"> Главная страница сайта </h2>
<p class="title-text text-center"> Обзорный сайт недвижимости в вашем городе</p>
</div>
<ul class="nav nav-pills justify-content-center mt-2" role="tablist">
<li class="btn btn-danger nav-item me-3">
<a class="nav-link" href="/order">Заказы</a>
</li>
<li class="btn btn-danger nav-item">
<a class="nav-link" href="/catalog"> Каталог</a>
</li>
</ul>
<div class="mt-2 mx-auto align-items-center">
<img src="/Image6.jpg" width="750px" alt="dom" />
</div>
<th:block th:switch="${items.size()}">
<h2 th:case="0" class="text-center title-text">Данные отсутствуют</h2>
<th:block th:case="*">
<h2 class="title-text text-center mt-3">Недвижимость</h2>
<div class="mt-2 d-flex justify-content-center">
<a class="btn btn-primary" th:href="@{/order/edit/(page=${page})}">Создать заказ</a>
</div>
<table class="table mt-2">
<caption></caption>
<thead>
<tr>
<th scope="col" class="w-10">ID</th>
<th scope="col" class="w-auto">Недвижимость</th>
<th scope="col" class="w-auto">Цена</th>
<th scope="col" class="w-auto">Дата бронирования</th>
</tr>
</thead>
<tbody>
<tr th:each="order : ${orders}">
<th scope="row" th:text="${order.id}"></th>
<div class="mt-1">
<th:block th:each="house : ${houses}">
<th:block th:if="${house.Id} eq ${order.houseId}">
<th scope="row" th:text="${house.title}"></th>
</th:block>
</th:block>
</div>
<div class="mt-1">
<th:block th:each="house : ${houses}">
<th:block th:if="${house.Id} eq ${order.houseId}">
<th scope="row" th:text="${house.price}"></th>
</th:block>
</th:block>
</div>
<td th:text="${#temporals.format(order.datestart, 'dd-MM-yyyy')}"></td>
<!-- <div class="mt-1">
<th:block th:each="user : ${users}">
<th:block th:if="${user.Id} eq ${order.userId}">
<th scope="row" th:text="${user.fio}"></th>
</th:block>
</th:block>
</div>
<div class="mt-1">
<th:block th:each="user : ${users}">
<th:block th:if="${user.Id} eq ${order.userId}">
<th scope="row" th:text="${user.numberphone}"></th>
</th:block>
</th:block>
</div> -->
<!-- <td>
<form th:action="@{/delete/{id}(id=${order.id})}" method="post">
<input type="hidden" th:name="page" th:value="${page}">
<input type="hidden" th:name="orderId" th:value="${orderId}">
<button type="submit" class="btn btn-link button-link"
onclick="return confirm('Вы уверены?')">Удалить</button>
</form>
</td> -->
</tr>
</tbody>
</table>
</th:block>
<th:block th:replace="~{ pagination :: pagination (
url='/',
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</th:block>
</main>
</body>
</html>

View File

@ -0,0 +1,51 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Вход</title>
</head>
<body>
<main layout:fragment="content">
<form action="#" th:action="@{/signup}" th:object="${user}" method="post">
<div class="mb-3">
<label for="login" class="form-label title-text">Имя пользователя</label>
<input type="text" th:field="*{login}" id="login" class="form-control">
<div th:if="${#fields.hasErrors('login')}" th:errors="*{login}" class="invalid-feedback"></div>
</div>
<div class="mb-3">
<label for="password" class="form-label title-text">Пароль</label>
<input type="password" th:field="*{password}" id="password" class="form-control">
<div th:if="${#fields.hasErrors('password')}" th:errors="*{password}" class="invalid-feedback"></div>
</div>
<div class="mb-3">
<label for="passwordConfirm" class="form-label title-text">Пароль (подтверждение)</label>
<input type="password" th:field="*{passwordConfirm}" id="passwordConfirm" class="form-control">
<div th:if="${#fields.hasErrors('passwordConfirm')}" th:errors="*{passwordConfirm}"
class="invalid-feedback"></div>
</div>
<div class="mb-3">
<label for="fio" class="form-label title-text"> ФИО </label>
<input type="text" th:field="*{fio}" id="fio" class="form-control">
<div th:if="${#fields.hasErrors('fio')}" th:errors="*{fio}" class="invalid-feedback"></div>
</div>
<div class="mb-3">
<label for="numberphone" class="form-label title-text"> Телефон </label>
<input type="text" th:field="*{numberphone}" id="numberphone" class="form-control">
<div th:if="${#fields.hasErrors('numberphone')}" th:errors="*{numberphone}" class="invalid-feedback">
</div>
</div>
<div class="mb-3 d-flex flex-row">
<button class="btn btn-primary me-2 button-fixed-width" type="submit">Регистрация</button>
<a class="btn btn-secondary button-fixed-width" href="/">Отмена</a>
</div>
</form>
</main>
</body>
</html>
</html>

View File

@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Редакторовать тип заказа</title>
</head>
<body>
<main layout:fragment="content" class="w-50 mx-auto">
<form action="#" th:action="@{/admin/type/edit/{id}(id=${type.id})}" th:object="${type}" method="post">
<h2 class="text-center title-text mt-5"> Работа с типами </h2>
<div class="mb-3 mt-3">
<label for="id" class="form-label title-text">ID</label>
<input type="text" th:value="*{id}" id="id" class="form-control" readonly disabled>
</div>
<div class="mb-3">
<label for="name" class="form-label title-text">Тип заказа</label>
<input type="text" th:field="*{name}" id="name" class="form-control">
<div th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="invalid-feedback"></div>
</div>
<div class="mb-3 d-flex flex-row">
<button class="btn btn-primary me-2 button-fixed-width" type="submit">Сохранить</button>
<a class="btn btn-secondary button-fixed-width" href="/admin/type">Отмена</a>
</div>
</form>
</main>
</body>
</html>

View File

@ -0,0 +1,50 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Типы недвижимости</title>
</head>
<body>
<main layout:fragment="content">
<th:block th:switch="${items.size()}">
<h2 th:case="0">Данные отсутствуют</h2>
<th:block th:case="*">
<h2 class="title-text text-center mt-3">Типы недвижимости</h2>
<div>
<a href="/admin/type/edit/" class="btn btn-primary mb-3">Добавить тип недвижимости</a>
</div>
<table class="table">
<caption></caption>
<thead>
<tr>
<th scope="col" class="w-10">ID</th>
<th scope="col" class="w-auto">Тип недвижимости</th>
<th scope="col" class="w-10"></th>
<th scope="col" class="w-10"></th>
</tr>
</thead>
<tbody>
<tr th:each="type : ${items}">
<th scope="row" th:text="${type.id}"></th>
<td th:text="${type.name}"></td>
<td>
<form th:action="@{/admin/type/edit/{id}(id=${type.id})}" method="get">
<button type="submit" class="btn btn-link button-link">Редактировать</button>
</form>
</td>
<td>
<form th:action="@{/admin/type/delete/{id}(id=${type.id})}" method="post">
<button type="submit" class="btn btn-link button-link"
onclick="return confirm('Вы уверены?')">Удалить</button>
</form>
</td>
</tr>
</tbody>
</table>
</th:block>
</th:block>
</main>
</body>
</html>

View File

@ -0,0 +1,41 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Редакторовать пользователя</title>
</head>
<body>
<main layout:fragment="content" class="w-75 mx-auto">
<form action="#" th:action="@{/admin/user/edit/{id}(id=${user.id},page=${page})}" th:object="${user}"
method="post">
<div class="mb-3">
<h2 class="text-center title-text mt-5"> Создание пользователей </h2>
<label for="id" class="form-label title-text">ID</label>
<input type="text" th:value="*{id}" id="id" class="form-control" readonly disabled>
</div>
<div class="mb-3">
<label for="login" class="form-label title-text">Имя пользователя</label>
<input type="text" th:field="*{login}" id="login" class="form-control">
<div th:if="${#fields.hasErrors('login')}" th:errors="*{login}" class="invalid-feedback"></div>
</div>
<div class="mb-3">
<label for="fio" class="form-label title-text">ФИО</label>
<input type="text" th:field="*{fio}" id="fio" class="form-control">
<div th:if="${#fields.hasErrors('fio')}" th:errors="*{fio}" class="invalid-feedback"></div>
</div>
<div class="mb-3">
<label for="numberphone" class="form-label title-text">Мобильный телефон</label>
<input type="text" th:field="*{numberphone}" id="numberphone" class="form-control">
<div th:if="${#fields.hasErrors('numberphone')}" th:errors="*{numberphone}" class="invalid-feedback">
</div>
</div>
<div class="mb-3 d-flex flex-row">
<button class="btn btn-primary me-2 button-fixed-width" type="submit">Сохранить</button>
<a class="btn btn-secondary button-fixed-width" th:href="@{/admin/user(page=${page})}">Отмена</a>
</div>
</form>
</main>
</body>
</html>

View File

@ -0,0 +1,61 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Пользователи</title>
</head>
<body>
<main layout:fragment="content">
<th:block th:switch="${items.size()}">
<h2 th:case="0">Данные отсутствуют</h2>
<th:block th:case="*">
<h2 class="title-text mt-3 text-center">Пользователи</h2>
<div>
<a th:href="@{/admin/user/edit/(page=${page})}" class="btn btn-primary mb-3">Добавить
пользователя</a>
</div>
<table class="table">
<caption></caption>
<thead>
<tr>
<th scope="col" class="w-10">ID</th>
<th scope="col" class="w-auto">Логин пользователя</th>
<th scope="col" class="w-auto"> ФИО пользователя</th>
<th scope="col" class="w-auto"> Мобильный телефон</th>
<th scope="col" class="w-auto"> Редактирование</th>
<th scope="col" class="w-auto"> Удаление</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${items}">
<th scope="row" th:text="${user.id}"></th>
<td th:text="${user.login}"></td>
<td th:text="${user.fio}"></td>
<td th:text="${user.numberphone}"></td>
<td>
<form th:action="@{/admin/user/edit/{id}(id=${user.id})}" method="get">
<input type="hidden" th:name="page" th:value="${page}">
<button type="submit" class="btn btn-link button-link">Редактировать</button>
</form>
</td>
<td>
<form th:action="@{/admin/user/delete/{id}(id=${user.id})}" method="post">
<input type="hidden" th:name="page" th:value="${page}">
<button type="submit" class="btn btn-link button-link"
onclick="return confirm('Вы уверены?')">Удалить</button>
</form>
</td>
</tr>
</tbody>
</table>
</th:block>
<th:block th:replace="~{ pagination :: pagination (
url=${'admin/user'},
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</th:block>
</main>
</body>
</html>

View File

@ -0,0 +1,150 @@
package com.example.demo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.houses.service.HouseService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class HouseServiceTests {
@Autowired
private HouseService houseService;
@Autowired
private TypeService typeService;
@Autowired
private UserService userService;
private TypeEntity type1;
private TypeEntity type2;
private UserEntity user1;
private UserEntity user2;
private HouseEntity house1;
private HouseEntity house2;
private HouseEntity house3;
@Test
@Order(1)
void createTest() {
type1 = typeService.create(new TypeEntity("Студия"));
type2 = typeService.create(new TypeEntity("Квартирка"));
user1 = userService.create(new UserEntity("dom", "42-42-42", "user123", "+79053332211"));
user2 = userService
.create(new UserEntity("serega", "101564501", "qwegfhfrty123", "+79992221147"));
house1 = houseService.create(user1.getId(),
new HouseEntity(type1, user1, "Apartament", "Близко к центру города", "",
50000.00));
house2 = houseService.create(user2.getId(), new HouseEntity(type2, user2,
"Studia",
"Удобная парковка", "", 10000.00));
house3 = houseService.create(user1.getId(), new HouseEntity(type1, user1, "Flat",
"Very excelent", "", 4000.00));
Assertions.assertEquals(house1, houseService.getAdmin(house1.getId()));
Assertions.assertEquals(house2, houseService.getAdmin(house2.getId()));
Assertions.assertEquals(house3, houseService.getAdmin(house3.getId()));
Assertions.assertEquals(2, houseService.getAll(type1.getId(), user1.getId()).size());
}
@Test
@Order(2)
void createNullableTest() {
final TypeEntity nonUniqueType = new TypeEntity("Студия");
Assertions.assertThrows(IllegalArgumentException.class, () -> typeService.create(nonUniqueType));
final HouseEntity nullableHouse = new HouseEntity(null, null, null, null, null, null);
Assertions.assertThrows(NullPointerException.class, () -> houseService.create(null, nullableHouse));
}
@Test
@Order(3)
void createNotUniqueTest() {
final TypeEntity nonUniqueType = new TypeEntity("Студия");
Assertions.assertThrows(IllegalArgumentException.class,
() -> typeService.create(nonUniqueType));
}
@Test
@Order(3)
void createNotEntitiesTest() {
final HouseEntity nullableHouse = new HouseEntity(null, null, null, null, null, null);
Assertions.assertThrows(NotFoundException.class, () -> houseService.create(0L, nullableHouse));
final HouseEntity nonEntitiesProduct = new HouseEntity(null, null, "nullable", null, null, null);
Assertions.assertThrows(NullPointerException.class,
() -> houseService.create(null, nonEntitiesProduct));
}
@Test
@Order(4)
void getTest() {
type1 = typeService.create(new TypeEntity("Пентхауз"));
user1 = userService.create(new UserEntity("login", "42-42-42", "user123", "+79000332211"));
house1 = houseService.create(user1.getId(),
new HouseEntity(type1, user1, "Apartament", "Близко к центру города", "",
50000.00));
Assertions.assertThrows(NotFoundException.class, () -> houseService.get(0L, 0L));
Assertions.assertEquals(1, houseService.getAll(type1.getId(), user1.getId()).size());
Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L));
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
Assertions.assertThrows(NotFoundException.class, () -> houseService.get(house1.getId(), user1.getId()));
}
@Test
@Order(5)
void updateTest() {
user1 = userService.create(new UserEntity("login12", "42-42-42", "user123", "+79000332200"));
var type1 = typeService.create(new TypeEntity("Таунхауз"));
var house1 = houseService.create(user1.getId(), new HouseEntity(type1, user1, "", "", "", 234.00));
final String test = "usernew";
final String testnumber = "+79073730072";
final UserEntity newEntity = userService.update(user1.getId(),
new UserEntity("user11", "", "usernew", "+79073730072"));
Assertions.assertEquals(4, userService.getAll().size());
Assertions.assertEquals(newEntity, userService.get(user1.getId()));
Assertions.assertEquals(test, newEntity.getFio());
Assertions.assertEquals(testnumber, newEntity.getNumberphone());
}
@Test
@Order(6)
void deleteTest() {
user1 = userService.create(new UserEntity("useeeer", "42-42-42", "user123", "+79113332211"));
var type1 = typeService.create(new TypeEntity("Дом на колёса"));
var type2 = typeService.create(new TypeEntity("Квартира"));
Assertions.assertEquals(0, houseService.getAll(type1.getId(), user1.getId()).size());
var house1 = houseService.create(user1.getId(),
new HouseEntity(type1, user1, "Квартира1", "Квартира на высоком этаже", "", 33300.00));
Assertions.assertEquals(1, houseService.getAll(type1.getId(), user1.getId()).size());
typeService.delete(type2.getId());
Assertions.assertFalse(
typeService.getAll().stream()
.anyMatch(p -> p.getId().equals(type2.getId())));
Assertions.assertEquals(1, houseService.getAll(type1.getId(), user1.getId()).size());
final HouseEntity newEntity = houseService.create(user1.getId(), new HouseEntity(type1, user1, "Flat", "",
"Dom excelent", 7000.00));
Assertions.assertEquals(2, houseService.getAll(type1.getId(),
user1.getId()).size());
Assertions.assertNotEquals(house1.getId(), newEntity.getId());
}
}

View File

@ -0,0 +1,110 @@
package com.example.demo;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.core.configuration.Constants;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.houses.service.HouseService;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.transaction.Transactional;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class OrderServiceTests {
@Autowired
private TypeService typeService;
@Autowired
private OrderService orderService;
@Autowired
private UserService userService;
@Autowired
private HouseService houseService;
private TypeEntity type1;
private TypeEntity type2;
private TypeEntity type3;
private UserEntity user1;
private UserEntity user2;
private HouseEntity house1;
private HouseEntity house2;
private OrderEntity order1;
private OrderEntity order2;
@Test
@Order(1)
void createTest() {
type1 = typeService.create(new TypeEntity("Климат"));
type2 = typeService.create(new TypeEntity("Кухни"));
type3 = typeService.create(new TypeEntity("Декор"));
user1 = userService.create(new UserEntity("user4", Constants.DEFAULT_PASSWORD, "Фросин Е.С.", "+79044441278"));
user2 = userService.create(new UserEntity("user3", Constants.DEFAULT_PASSWORD, "Еразин А.Е.", "+78882546699"));
final var house1 = houseService.create(user1.getId(),
new HouseEntity(type1, user1, "Комната1", "Хорошее охлаждение комнат", "", 399.00));
final var house2 = houseService.create(user1.getId(),
new HouseEntity(type1, user1, "Надёжный, удобный", "Квартира с большой парковкой на юге города", "",
499.00));
LocalDateTime date1 = LocalDateTime.of(2023, 04, 02, 10, 20);
LocalDateTime date2 = LocalDateTime.of(2023, 05, 02, 10, 20);
orderService.create(user1.getId(), new OrderEntity(house1, user1, date1, date2));
Assertions.assertEquals(1, orderService.getAll(user1.getId(), house1.getId()).size());
orderService.create(user1.getId(), new OrderEntity(house1, user1, date1, date2));
orderService.create(user1.getId(), new OrderEntity(house1, user1, date1, date2));
Assertions.assertEquals(3, orderService.getAll(user1.getId(), house1.getId()).size());
}
@Test
@Order(2)
void orderFilterTest() {
type1 = typeService.create(new TypeEntity("Контроль1"));
user1 = userService.create(new UserEntity("user15", Constants.DEFAULT_PASSWORD, "Фросин Е.С.", "+79041122278"));
user2 = userService.create(new UserEntity("user16", Constants.DEFAULT_PASSWORD, "Еразин А.Е.", "+70042546699"));
final var house1 = houseService.create(user1.getId(),
new HouseEntity(type1, user1, "Комната2", "Квартира с большой парковкой на юге города", "упк", 399.00));
final var house2 = houseService.create(user1.getId(),
new HouseEntity(type1, user1, "Дом3", "Квартира с большой парковкой", "пкуп", 499.00));
LocalDateTime date1 = LocalDateTime.of(2023, 04, 02, 10, 20);
LocalDateTime date2 = LocalDateTime.of(2023, 05, 02, 10, 20);
orderService.create(user1.getId(), new OrderEntity(house1, user1, date1, date2));
Assertions.assertEquals(1, orderService.getAll(user1.getId(), house1.getId()).size());
orderService.create(user1.getId(), new OrderEntity(house1, user1, date1, date2));
orderService.create(user1.getId(), new OrderEntity(house1, user1, date1, date2));
Assertions.assertEquals(3, orderService.getAll(user1.getId(), house1.getId()).size());
Assertions.assertEquals(0, orderService.getAll(user2.getId(), house1.getId()).size());
}
}

View File

@ -9,11 +9,8 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.houses.service.HouseService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@SpringBootTest
class TypeServiceTests {
@ -22,43 +19,26 @@ class TypeServiceTests {
private TypeEntity type;
@Autowired
private UserService userService;
private UserEntity user1;
@Autowired
private HouseService houseService;
@BeforeEach
void createData() {
removeData();
type = typeService.create(new TypeEntity("Студия"));
typeService.create(new TypeEntity("Квартира"));
typeService.create(new TypeEntity("Пентхауз"));
}
@AfterEach
void removeData() {
typeService.getAll().forEach(type -> {
userService.getAll().forEach(user -> {
houseService.getAll(type.getId(), user.getId())
.forEach(house -> houseService.delete(house.getId(), user.getId()));
});
});
typeService.getAll().forEach(type -> typeService.delete(type.getId()));
userService.getAll().forEach(user -> userService.delete(user.getId()));
}
@Test
void getTest() {
type = typeService.create(new TypeEntity("Студия-дом"));
Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L));
}
@Test
void createTest() {
Assertions.assertEquals(3, typeService.getAll().size());
type = typeService.create(new TypeEntity("Дом"));
Assertions.assertEquals(9, typeService.getAll().size());
Assertions.assertEquals(type, typeService.get(type.getId()));
}
@ -70,16 +50,18 @@ class TypeServiceTests {
@Test
void createNullableTest() {
type = typeService.create(new TypeEntity("Квартира"));
final TypeEntity nullableType = new TypeEntity(null);
Assertions.assertThrows(DataIntegrityViolationException.class, () -> typeService.create(nullableType));
}
@Test
void updateTest() {
type = typeService.create(new TypeEntity("Дом на колёсах"));
final String test = "TEST";
final String oldName = type.getName();
final TypeEntity newEntity = typeService.update(type.getId(), new TypeEntity(test));
Assertions.assertEquals(3, typeService.getAll().size());
Assertions.assertEquals(7, typeService.getAll().size());
Assertions.assertEquals(newEntity, typeService.get(type.getId()));
Assertions.assertEquals(test, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName());
@ -87,11 +69,12 @@ class TypeServiceTests {
@Test
void deleteTest() {
type = typeService.create(new TypeEntity("2х ярусная квартира"));
typeService.delete(type.getId());
Assertions.assertEquals(2, typeService.getAll().size());
Assertions.assertEquals(9, typeService.getAll().size());
final TypeEntity newEntity = typeService.create(new TypeEntity(type.getName()));
Assertions.assertEquals(3, typeService.getAll().size());
Assertions.assertEquals(10, typeService.getAll().size());
Assertions.assertNotEquals(type.getId(), newEntity.getId());
}
}

View File

@ -8,12 +8,10 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DataIntegrityViolationException;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.houses.model.HouseEntity;
import com.example.demo.houses.service.HouseService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@ -31,24 +29,17 @@ class UserServiceTests {
@Autowired
private TypeService typeService;
private TypeEntity type;
@Autowired
private HouseService houseService;
private HouseEntity house;
@BeforeEach
void createData() {
removeData();
user = userService.create(new UserEntity("serega", "serj2003@mail.ru",
"10101", "qwerty123", "serj1"));
user = userService.create(new UserEntity("qwerty123", "serj1", "serega", "+79044556787"));
userService.create(new UserEntity("Фёдор Лопатин", "test1@test.ru", "+79875433210",
"qwerty21221", "12312"));
userService.create(new UserEntity("Семён Кукушкин", "test2@test.ru", "+74567433210",
"qwersfdsdfy451", "23423"));
userService.create(new UserEntity("qwerty21221", "12345", "Фёдор Лопатин", "+79875433210"));
userService.create(new UserEntity("qwersfdsdfy451", "235124", "Семён Кукушкин", "+74567433210"));
}
@AfterEach
@ -77,18 +68,16 @@ class UserServiceTests {
@Test
void createNotUniqueTest() {
final UserEntity nonUniqueUser = new UserEntity("Михаил Медведев", "test@test.ru", "+79876543210", "qwerty123",
"febr21");
final UserEntity nonUniqueUser = new UserEntity("qwerty123", "serj1", "serega", "+79044556787");
Assertions.assertThrows(IllegalArgumentException.class, () -> userService.create(nonUniqueUser));
}
@Test
void createNullableTest() {
final UserEntity nullableUser = new UserEntity("Павел Крылов", "test@test.ru",
"+79876543210", "qwerty123", "342ffdv");
Assertions.assertThrows(IllegalArgumentException.class, () -> userService.create(nullableUser));
// Assertions.assertThrows(DataIntegrityViolationException.class, () ->
final UserEntity nullableUser = new UserEntity(null, null, null, null);
// Assertions.assertThrows(NotFoundException.class, () ->
// userService.create(nullableUser));
Assertions.assertThrows(DataIntegrityViolationException.class, () -> userService.create(nullableUser));
}
@Transactional
@ -97,7 +86,7 @@ class UserServiceTests {
final String test = "TEST";
final String oldLogin = user.getLogin();
final UserEntity newEntity = userService.update(user.getId(),
new UserEntity("Евгений Крышкин", "test@test.ru", "+79876543210", "qwerty18623", "fet213w"));
new UserEntity("qwerty18623", "fet213w", "Евгений Крышкин", "+79876543210"));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(newEntity, userService.get(user.getId()));
Assertions.assertNotEquals(test, newEntity.getLogin());
@ -109,8 +98,8 @@ class UserServiceTests {
userService.delete(user.getId());
Assertions.assertEquals(2, userService.getAll().size());
final UserEntity newEntity = userService.create(new UserEntity("Евпат Еремеев", "test@test.ru", "+79876543210",
"qwerty123", "fddffc21"));
final UserEntity newEntity = userService
.create(new UserEntity("test@test.ru", "fddffc21", "Евпат Еремеев", "+79033457762"));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertNotEquals(user.getId(), newEntity.getId());
}