Skip to content

Commit

Permalink
Posts list page added. Posts controller developed. Minor fixes.
Browse files Browse the repository at this point in the history
  • Loading branch information
Niaktes committed Oct 24, 2023
1 parent e21f92c commit e365f39
Show file tree
Hide file tree
Showing 8 changed files with 365 additions and 23 deletions.
93 changes: 93 additions & 0 deletions src/main/java/ru/job4j/cars/controller/PostController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package ru.job4j.cars.controller;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ru.job4j.cars.dto.ImageDto;
import ru.job4j.cars.dto.PostSearchDto;
import ru.job4j.cars.model.Brand;
import ru.job4j.cars.model.CarModel;
import ru.job4j.cars.model.Post;
import ru.job4j.cars.service.*;

@Controller
@RequestMapping("/posts")
@AllArgsConstructor
public class PostController {

private final PostService postService;
private final BodyService bodyService;
private final BrandService brandService;
private final CarModelService carModelService;
private final CategoryService categoryService;
private final ColorService colorService;
private final EngineSizeService engineSizeService;
private final FuelTypeService fuelTypeService;
private final TransmissionService transmissionService;

@GetMapping("/all")
public String getAllPosts(Model model, @ModelAttribute PostSearchDto searchDto) {
addFormAttributesToModel(model);
boolean searchActive = searchDto.getCar() != null
|| searchDto.getHighestPrice() > 0
|| searchDto.getLowestPrice() > 0
|| searchDto.getPostCreatedBeforeDays() > 0
|| searchDto.isImageExists();
if (!searchActive) {
model.addAttribute("posts", postService.findAllNotSold());
} else {
model.addAttribute("posts", postService.findAllByCriteria(searchDto));
}
return "posts/list";
}

@GetMapping("/create")
public String getCreationPage(Model model) {
addFormAttributesToModel(model);
return "posts/create";
}

@GetMapping("/{id}")
public String getById(Model model, @PathVariable int id) {
Optional<Post> postOptional = postService.findById(id);
if (postOptional.isEmpty()) {
model.addAttribute("message", "Объявление с указанным id не найдено.");
return "errors/404";
}
model.addAttribute("post", postOptional.get());
return "posts/one";
}

@PostMapping("/create")
public String createPost(@ModelAttribute Post post, @RequestParam MultipartFile file, Model model) {
try {
postService.save(post, new ImageDto(file.getOriginalFilename(), file.getBytes()));
} catch (IOException e) {
model.addAttribute("message", "Ошибка при создании объявления!");
return "errors/404";
}
return "redirect:/posts/all";
}

private Model addFormAttributesToModel(Model model) {
Map<Brand, List<CarModel>> brandsModels = new LinkedHashMap<>();
brandService.findAll().forEach(brand -> brandsModels.put(
brand, carModelService.findAllByBrandId(brand.getId()).stream().toList()));
model.addAttribute("brandsModels", brandsModels);
model.addAttribute("bodies", bodyService.findAll());
model.addAttribute("transmissions", transmissionService.findAll());
model.addAttribute("fuelTypes", fuelTypeService.findAll());
model.addAttribute("engineSizes", engineSizeService.findAll());
model.addAttribute("colors", colorService.findAll());
model.addAttribute("categories", categoryService.findAll());
return model;
}

}
19 changes: 19 additions & 0 deletions src/main/java/ru/job4j/cars/dto/PostSearchDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package ru.job4j.cars.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import ru.job4j.cars.model.Car;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class PostSearchDto {

private Car car;
private long highestPrice;
private long lowestPrice;
private int postCreatedBeforeDays;
private boolean imageExists;

}
Original file line number Diff line number Diff line change
Expand Up @@ -96,28 +96,28 @@ public List<Post> findAllByCriteria(Car car, boolean imagesExist, int createdDay
CriteriaQuery<Post> criteriaQuery = criteriaBuilder.createQuery(Post.class);
Root<Post> post = criteriaQuery.from(Post.class);
post.fetch("car", JoinType.LEFT);
post.fetch("images", JoinType.LEFT);
post.fetch("image", JoinType.LEFT);
post.fetch("priceHistories", JoinType.LEFT);
List<Predicate> predicates = new ArrayList<>();
if (car.getCarModel() != null) {
if (car.getCarModel().getId() > 0) {
predicates.add(criteriaBuilder.equal(post.get("car").get("model"), car.getCarModel()));
}
if (car.getBody() != null) {
if (car.getBody().getId() > 0) {
predicates.add(criteriaBuilder.equal(post.get("car").get("body"), car.getBody()));
}
if (car.getEngine() != null) {
if (car.getEngine().getId() > 0) {
predicates.add(criteriaBuilder.equal(post.get("car").get("engine"), car.getEngine()));
}
if (car.getTransmission() != null) {
if (car.getTransmission().getId() > 0) {
predicates.add(criteriaBuilder.equal(
post.get("car").get("transmission"),
car.getTransmission())
);
}
if (car.getColor() != null) {
if (car.getColor().getId() > 0) {
predicates.add(criteriaBuilder.equal(post.get("car").get("color"), car.getColor()));
}
if (car.getCategory() != null) {
if (car.getCategory().getId() > 0) {
predicates.add(criteriaBuilder.equal(post.get("car").get("category"), car.getCategory()));
}
if (car.getYear() != 0) {
Expand All @@ -133,7 +133,7 @@ public List<Post> findAllByCriteria(Car car, boolean imagesExist, int createdDay
);
}
if (imagesExist) {
predicates.add(criteriaBuilder.isNotEmpty(post.get("photos")));
predicates.add(criteriaBuilder.isNotNull(post.get("image")));
}
if (createdDaysBefore > 0) {
predicates.add(criteriaBuilder.between(
Expand Down
5 changes: 2 additions & 3 deletions src/main/java/ru/job4j/cars/service/PostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import java.util.List;
import java.util.Optional;
import ru.job4j.cars.dto.ImageDto;
import ru.job4j.cars.model.Car;
import ru.job4j.cars.dto.PostSearchDto;
import ru.job4j.cars.model.Post;

public interface PostService {
Expand All @@ -20,7 +20,6 @@ public interface PostService {

void delete(Post post);

List<Post> findAllByCriteria(Car car, boolean imagesExist, int createdDaysBefore, long minPrice,
long maxPrice);
List<Post> findAllByCriteria(PostSearchDto searchDto);

}
48 changes: 39 additions & 9 deletions src/main/java/ru/job4j/cars/service/SimplePostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,31 @@
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import ru.job4j.cars.dto.ImageDto;
import ru.job4j.cars.model.Car;
import ru.job4j.cars.model.Image;
import ru.job4j.cars.model.Post;
import ru.job4j.cars.dto.PostSearchDto;
import ru.job4j.cars.model.*;
import ru.job4j.cars.repository.PostRepository;

@Service
@AllArgsConstructor
public class SimplePostService implements PostService {

private final PostRepository postRepository;
private final CarModelService carModelService;
private final BrandService brandService;
private final EngineService engineService;
private final ImageService imageService;

@Override
public Optional<Post> save(Post post, ImageDto imageDto) {
Image newImage = imageService.saveImage(imageDto);
post.setImage(newImage);
setBrand(post.getCar());
setEngine(post.getCar());
Image newImage = null;
if (imageDto.getContent().length != 0) {
newImage = imageService.saveImage(imageDto);
post.setImage(newImage);
}
Optional<Post> postOptional = postRepository.save(post);
if (postOptional.isEmpty()) {
if (postOptional.isEmpty() && newImage != null) {
imageService.deleteImage(newImage);
}
return postOptional;
Expand Down Expand Up @@ -71,9 +78,32 @@ public void delete(Post post) {
}

@Override
public List<Post> findAllByCriteria(Car car, boolean imageExist, int createdDaysBefore,
long minPrice, long maxPrice) {
return postRepository.findAllByCriteria(car, imageExist, createdDaysBefore, minPrice, maxPrice);
public List<Post> findAllByCriteria(PostSearchDto searchDto) {
return postRepository.findAllByCriteria(
searchDto.getCar(),
searchDto.isImageExists(),
searchDto.getPostCreatedBeforeDays(),
searchDto.getLowestPrice(),
searchDto.getHighestPrice());
}

private Car setBrand(Car car) {
CarModel carModel = carModelService.getById(car.getCarModel().getId());
Brand brand = brandService.getById(carModel.getBrandId());
car.setBrand(brand);
return car;
}

private Car setEngine(Car car) {
Optional<Engine> engineOptional = engineService.findByFuelTypeAndSize(
car.getEngine().getFuelType(), car.getEngine().getEngineSize());
if (engineOptional.isEmpty()) {
Engine engine = engineService.save(car.getEngine());
car.setEngine(engine);
} else {
car.setEngine(engineOptional.get());
}
return car;
}

}
2 changes: 1 addition & 1 deletion src/main/resources/templates/blocks/header.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

<div th:fragment="header_main">
<nav class="navbar navbar-expand-lg navbar-dark bg-grey">
<div class="container col-9">
<div class="container col-12">
<a class="navbar-brand" href="/">
<img src="https://img.freepik.com/premium-vector/purchase-buy-sharing-or-rental-car-logo-with-flat-icons-car-dealer-gives-keys-to-buyer-isolated-vector-illustration_108855-3539.jpg" alt="Автомаг" height="80">
</a>
Expand Down
4 changes: 2 additions & 2 deletions src/main/resources/templates/posts/create.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="model">Модель автомобиля</label>
<select class="form-control" id="model" name="car.model.id">
<label for="carModel">Модель автомобиля</label>
<select class="form-control" id="carModel" name="car.carModel.id">
<optgroup th:each="brand : ${brandsModels.keySet()}" th:label="${brand.name}">
<option th:each="model : ${brandsModels.get(brand)}" th:text="${model.name}" th:value="${model.id}"></option>
</optgroup>
Expand Down
Loading

0 comments on commit e365f39

Please sign in to comment.