почти вся логика работает, осталось заказы и игры

This commit is contained in:
Максим Яковлев 2024-05-12 01:51:51 +04:00
parent 86435c3fbe
commit 884b2aaad6
55 changed files with 1963 additions and 502 deletions

View File

@ -36,6 +36,14 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.2.224' implementation 'com.h2database:h2:2.2.224'
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' testImplementation 'org.springframework.boot:spring-boot-starter-test'
} }

Binary file not shown.

View File

@ -10,6 +10,7 @@ import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.demo.core.configuration.Constants;
import com.example.demo.games.model.GameEntity; import com.example.demo.games.model.GameEntity;
import com.example.demo.games.service.GameService; import com.example.demo.games.service.GameService;
import com.example.demo.genres.model.GenreEntity; import com.example.demo.genres.model.GenreEntity;
@ -19,57 +20,61 @@ import com.example.demo.orders.service.OrderService;
import com.example.demo.types.model.TypeEntity; import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService; import com.example.demo.types.service.TypeService;
import com.example.demo.users.model.UserEntity; import com.example.demo.users.model.UserEntity;
import com.example.demo.users.model.UserRole;
import com.example.demo.users.service.UserService; import com.example.demo.users.service.UserService;
@SpringBootApplication @SpringBootApplication
public class DemoApplication implements CommandLineRunner { public class DemoApplication implements CommandLineRunner {
private final Logger log = LoggerFactory.getLogger(DemoApplication.class); private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
private final TypeService typeService; private final TypeService typeService;
private final GenreService genreService; private final GenreService genreService;
private final GameService gameService; private final GameService gameService;
private final OrderService orderService; private final OrderService orderService;
private final UserService userService; private final UserService userService;
public DemoApplication(TypeService typeService, GenreService genreService, GameService gameService, OrderService orderService, UserService userService){ public DemoApplication(TypeService typeService, GenreService genreService, GameService gameService,
this.typeService = typeService; OrderService orderService, UserService userService) {
this.gameService = gameService; this.typeService = typeService;
this.genreService = genreService; this.gameService = gameService;
this.orderService = orderService; this.genreService = genreService;
this.userService = userService; this.orderService = orderService;
} this.userService = userService;
}
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args); SpringApplication.run(DemoApplication.class, args);
} }
@Override @Override
public void run(String... args) throws Exception{ public void run(String... args) throws Exception {
log.info("start"); log.info("start");
// final var type1 = typeService.create(new TypeEntity("ААА"));
// final var type2 = typeService.create(new TypeEntity("АА"));
// final var genre1 = genreService.create(new GenreEntity("Приключения")); log.info("Create default user values");
// final var genre2 = genreService.create(new GenreEntity("Симулятор")); final var admin = new UserEntity("admin", "admin@mail.com", "admin");
admin.setRole(UserRole.ADMIN);
userService.create(admin);
final var user1 = userService.create(new UserEntity("user", "user@gmail.com", Constants.DEFAULT_PASSWORD));
// final List<GenreEntity> genres1 = new ArrayList<GenreEntity>(); final var type1 = typeService.create(new TypeEntity("ААА"));
// genres1.add(genre1); final var type2 = typeService.create(new TypeEntity("АА"));
// genres1.add(genre2);
// final List<GenreEntity> genres2 = new ArrayList<GenreEntity>(); final var genre1 = genreService.create(new GenreEntity("Приключения"));
// genres2.add(genre2); final var genre2 = genreService.create(new GenreEntity("Симулятор"));
// final var game1 = gameService.create(new GameEntity(type1,"Game1",2100.0,"good game", genres1)); final List<GenreEntity> genres1 = new ArrayList<GenreEntity>();
// final var game2 = gameService.create(new GameEntity( type2, "Game2", 1200.0,"bad game", genres2)); genres1.add(genre1);
// final List<GameEntity> games = new ArrayList<GameEntity>(); genres1.add(genre2);
// games.add(game1);
// games.add(game2);
// var user1 = userService.create(new UserEntity( "login1", "email@mail.com", "qwerty123")); final List<GenreEntity> genres2 = new ArrayList<GenreEntity>();
// var user2 = userService.create(new UserEntity( "login2", "email@gmail.com", "qwerty1234")); genres2.add(genre2);
// orderService.create(7, new OrderEntity(user1,games)); final var game1 = gameService.create(new GameEntity(type1, "Game1", 2100.0, "good game", genres1));
// orderService.create(8, new OrderEntity(user2,games)); final var game2 = gameService.create(new GameEntity(type2, "Game2", 1200.0, "bad game", genres2));
} final List<GameEntity> games = new ArrayList<GameEntity>();
games.add(game1);
games.add(game2);
orderService.create(user1.getId(), new OrderEntity(games));
}
} }

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

@ -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

@ -2,8 +2,17 @@ package com.example.demo.core.configuration;
public class Constants { public class Constants {
public static final String SEQUENCE_NAME = "hibernate_sequence"; 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"; public static final int DEFAULT_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() { private Constants() {
} }

View File

@ -1,13 +1,23 @@
package com.example.demo.core.configuration; package com.example.demo.core.configuration;
import org.modelmapper.ModelMapper; import org.modelmapper.ModelMapper;
import org.modelmapper.PropertyMap;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import com.example.demo.core.model.BaseEntity;
@Configuration @Configuration
public class MapperConfiguration { public class MapperConfiguration {
@Bean @Bean
ModelMapper modelMapper() { ModelMapper modelMapper() {
return new 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; package com.example.demo.core.configuration;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration @Configuration
public class WebConfiguration implements WebMvcConfigurer { public class WebConfiguration implements WebMvcConfigurer {
@Override @Override
public void addCorsMappings(@NonNull CorsRegistry registry) { public void addViewControllers(ViewControllerRegistry registry) {
registry.addMapping("/**") registry.addViewController("/login").setViewName("login");
.allowedMethods("GET", "POST", "PUT", "DELETE");
} }
} }

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,63 @@
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")
.permitAll());
httpSecurity.authorizeHttpRequests(requests -> requests
.requestMatchers(Constants.ADMIN_PREFIX + "/**").hasRole(UserRole.ADMIN.name())
.requestMatchers("/h2-console/**").hasRole(UserRole.ADMIN.name())
.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.getPrice())
.mapToDouble(Double::doubleValue)
.sum();
}
}

View File

@ -0,0 +1,16 @@
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

@ -1,8 +1,11 @@
package com.example.demo.games.api; package com.example.demo.games.api;
import java.util.List; import java.util.List;
import java.util.Map;
import org.modelmapper.ModelMapper; import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
@ -11,10 +14,8 @@ import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; 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.PageAttributesMapper;
import com.example.demo.core.api.PageDtoMapper;
import com.example.demo.core.configuration.Constants; import com.example.demo.core.configuration.Constants;
import com.example.demo.games.model.GameEntity; import com.example.demo.games.model.GameEntity;
import com.example.demo.games.service.GameService; import com.example.demo.games.service.GameService;
@ -24,23 +25,31 @@ import com.example.demo.types.service.TypeService;
import jakarta.validation.Valid; import jakarta.validation.Valid;
@RestController @Controller
@RequestMapping(Constants.API_URL + "/game") @RequestMapping(GameController.URL)
public class GameController { public class GameController {
public static final String URL = Constants.ADMIN_PREFIX + "/game";
private static final String GAME_VIEW = "game";
private static final String GAME_EDIT_VIEW = "game-edit";
private static final String PAGE_ATTRIBUTE = "page";
private static final String GAME_ATTRIBUTE = "game";
private final GameService gameService; private final GameService gameService;
private final TypeService typeService; private final TypeService typeService;
private final GenreService genreService; private final GenreService genreService;
private final ModelMapper modelMapper; private final ModelMapper modelMapper;
public GameController(GameService gameService, TypeService typeService, GenreService genreService, ModelMapper modelMapper){ public GameController(GameService gameService, TypeService typeService, GenreService genreService,
ModelMapper modelMapper) {
this.gameService = gameService; this.gameService = gameService;
this.genreService = genreService; this.genreService = genreService;
this.modelMapper = modelMapper; this.modelMapper = modelMapper;
this.typeService = typeService; this.typeService = typeService;
} }
private GameDto toDto(GameEntity entity){ private GameDto toDto(GameEntity entity) {
//return modelMapper.map(entity, GameDto.class); // return modelMapper.map(entity, GameDto.class);
var dto = new GameDto(); var dto = new GameDto();
dto.setId(entity.getId()); dto.setId(entity.getId());
dto.setGenres(entity.getGenres().stream().map(GenreEntity::getId).toList()); dto.setGenres(entity.getGenres().stream().map(GenreEntity::getId).toList());
@ -51,44 +60,46 @@ public class GameController {
return dto; return dto;
} }
private GameEntity toEntity(GameDto dto){ private GameEntity toEntity(GameDto dto) {
// return modelMapper.map(dto, GameEntity.class);
final GameEntity entity = modelMapper.map(dto, GameEntity.class); final GameEntity entity = modelMapper.map(dto, GameEntity.class);
entity.setType(typeService.get(dto.getTypeId())); entity.setType(typeService.get(dto.getTypeId()));
var genres = dto.getGenres(); var genres = dto.getGenres();
List<GenreEntity> genresList = genreService.getAllById(genres); List<GenreEntity> genresList = genreService.getAllById(genres);
for(var genre : genresList){ for (var genre : genresList) {
entity.setGenres(genre); entity.setGenres(genre);
} }
return entity; return entity;
} }
@GetMapping @GetMapping
public PageDto<GameDto> getAll( public String getAll(
@RequestParam(name = "typeId", defaultValue = "0") long typeId, @RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
//@RequestParam(name = "genres", defaultValue = "") List<Long> genres, Model model) {
@RequestParam(name = "genreId", defaultValue = "0") long genre, final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
@RequestParam(name = "page", defaultValue = "0") int page, gameService.getAll(0, 0, page, Constants.DEFAULT_PAGE_SIZE), this::toDto);
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size){ model.addAllAttributes(attributes);
return PageDtoMapper.toDto(gameService.getAll(typeId, genre, page, size), this::toDto); model.addAttribute(PAGE_ATTRIBUTE, page);
return GAME_VIEW;
} }
@GetMapping("/{id}") @GetMapping("/{id}")
public GameDto get(@PathVariable(name = "id") Long id){ public GameDto get(@PathVariable(name = "id") Long id) {
return toDto(gameService.get(id)); return toDto(gameService.get(id));
} }
@PostMapping @PostMapping
public GameDto create(@RequestBody @Valid GameDto dto){ public GameDto create(@RequestBody @Valid GameDto dto) {
return toDto(gameService.create(toEntity(dto))); return toDto(gameService.create(toEntity(dto)));
} }
@PutMapping("/{id}") @PutMapping("/{id}")
public GameDto update(@PathVariable(name = "id") Long id, @RequestBody GameDto dto){ public GameDto update(@PathVariable(name = "id") Long id, @RequestBody GameDto dto) {
return toDto(gameService.update(id, toEntity(dto))); return toDto(gameService.update(id, toEntity(dto)));
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public GameDto delete(@PathVariable(name = "id") Long id){ public GameDto delete(@PathVariable(name = "id") Long id) {
return toDto(gameService.delete(id)); return toDto(gameService.delete(id));
} }
} }

View File

@ -3,14 +3,11 @@ package com.example.demo.games.api;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min; import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
public class GameDto { public class GameDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotNull @NotNull
@Min(1) @Min(1)
@ -25,52 +22,52 @@ public class GameDto {
@NotBlank @NotBlank
private String description; private String description;
public Long getId(){ public Long getId() {
return id; return id;
} }
public void setId(Long id){ public void setId(Long id) {
this.id = id; this.id = id;
} }
public Long getTypeId(){ public Long getTypeId() {
return typeId; return typeId;
} }
public void setTypeId(Long typeId){ public void setTypeId(Long typeId) {
this.typeId = typeId; this.typeId = typeId;
} }
public List<Long> getGenres(){ public List<Long> getGenres() {
return genres; return genres;
} }
public void setGenres(List<Long> genres){ public void setGenres(List<Long> genres) {
this.genres.clear(); this.genres.clear();
this.genres.addAll(genres); this.genres.addAll(genres);
} }
public Double getPrice(){ public Double getPrice() {
return price; return price;
} }
public void setPrice(Double price){ public void setPrice(Double price) {
this.price = price; this.price = price;
} }
public String getName(){ public String getName() {
return name; return name;
} }
public void setName(String name){ public void setName(String name) {
this.name = name; this.name = name;
} }
public String getDescription(){ public String getDescription() {
return description; return description;
} }
public void setDescription(String description){ public void setDescription(String description) {
this.description = description; this.description = description;
} }

View File

@ -1,8 +1,11 @@
package com.example.demo.games.service; package com.example.demo.games.service;
import java.util.Collection;
import java.util.List; import java.util.List;
//import java.util.List; //import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -18,48 +21,57 @@ import com.example.demo.genres.service.GenreService;
public class GameService { public class GameService {
private final GameRepository repository; private final GameRepository repository;
public GameService(GameRepository repository, GenreService genreService){ public GameService(GameRepository repository, GenreService genreService) {
this.repository = repository; this.repository = repository;
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<GameEntity> getAll(long typeId, long genre){ public List<GameEntity> getAll(long typeId, long genre) {
if(!Objects.equals(typeId, 0L) && !Objects.equals(genre, 0L)){ if (!Objects.equals(typeId, 0L) && !Objects.equals(genre, 0L)) {
return repository.findByTypeIdAndGenres(typeId, genre); return repository.findByTypeIdAndGenres(typeId, genre);
} }
if(Objects.equals(typeId, 0L) && !Objects.equals(genre, 0L)){ if (Objects.equals(typeId, 0L) && !Objects.equals(genre, 0L)) {
return repository.findByGenres(genre); return repository.findByGenres(genre);
} }
if(!Objects.equals(typeId, 0L) && Objects.equals(genre, 0L)){ if (!Objects.equals(typeId, 0L) && Objects.equals(genre, 0L)) {
return repository.findByTypeId(typeId); return repository.findByTypeId(typeId);
} }
return repository.findAll(); return repository.findAll();
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Page<GameEntity> getAll(long typeId, long genre, int page, int size){ public Page<GameEntity> getAll(long typeId, long genre, int page, int size) {
final Pageable pageRequest = PageRequest.of(page, size); final Pageable pageRequest = PageRequest.of(page, size);
if(!Objects.equals(typeId, 0L) && !Objects.equals(genre, 0L)){ if (!Objects.equals(typeId, 0L) && !Objects.equals(genre, 0L)) {
return repository.findByTypeIdAndGenres(typeId, genre, pageRequest); return repository.findByTypeIdAndGenres(typeId, genre, pageRequest);
} }
if(Objects.equals(typeId, 0L) && !Objects.equals(genre, 0L)){ if (Objects.equals(typeId, 0L) && !Objects.equals(genre, 0L)) {
return repository.findByGenres(genre, pageRequest); return repository.findByGenres(genre, pageRequest);
} }
if(!Objects.equals(typeId, 0L) && Objects.equals(genre, 0L)){ if (!Objects.equals(typeId, 0L) && Objects.equals(genre, 0L)) {
return repository.findByTypeId(typeId, pageRequest); return repository.findByTypeId(typeId, pageRequest);
} }
return repository.findAll(pageRequest); return repository.findAll(pageRequest);
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public GameEntity get(Long id){ public GameEntity get(Long id) {
return repository.findOneById(id).orElseThrow(() -> new NotFoundException(GameEntity.class, id)); return repository.findOneById(id).orElseThrow(() -> new NotFoundException(GameEntity.class, id));
} }
@Transactional(readOnly = true)
public List<GameEntity> getByIds(Collection<Long> ids) {
final List<GameEntity> games = StreamSupport.stream(repository.findAllById(ids).spliterator(), false).toList();
if (games.size() < ids.size()) {
throw new IllegalArgumentException("Invalid type");
}
return games;
}
@Transactional @Transactional
public GameEntity create(GameEntity entity){ public GameEntity create(GameEntity entity) {
if (entity == null) { if (entity == null) {
throw new IllegalArgumentException("Entity is null"); throw new IllegalArgumentException("Entity is null");
} }
@ -67,21 +79,21 @@ public class GameService {
} }
@Transactional @Transactional
public GameEntity update(Long id, GameEntity entity){ public GameEntity update(Long id, GameEntity entity) {
final GameEntity existEntity = get(id); final GameEntity existEntity = get(id);
existEntity.setName(entity.getName()); existEntity.setName(entity.getName());
existEntity.setPrice(entity.getPrice()); existEntity.setPrice(entity.getPrice());
existEntity.setDescription(entity.getDescription()); existEntity.setDescription(entity.getDescription());
existEntity.setType(entity.getType()); existEntity.setType(entity.getType());
var genres = entity.getGenres(); var genres = entity.getGenres();
for(var genre : genres){ for (var genre : genres) {
existEntity.setGenres(genre); existEntity.setGenres(genre);
} }
return repository.save(existEntity); return repository.save(existEntity);
} }
@Transactional @Transactional
public GameEntity delete(Long id){ public GameEntity delete(Long id) {
final GameEntity existEntity = get(id); final GameEntity existEntity = get(id);
repository.delete(existEntity); repository.delete(existEntity);
return existEntity; return existEntity;

View File

@ -1,16 +1,14 @@
package com.example.demo.genres.api; package com.example.demo.genres.api;
import java.util.List;
import org.modelmapper.ModelMapper; import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping; 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.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; 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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.configuration.Constants; import com.example.demo.core.configuration.Constants;
import com.example.demo.genres.model.GenreEntity; import com.example.demo.genres.model.GenreEntity;
@ -18,47 +16,90 @@ import com.example.demo.genres.service.GenreService;
import jakarta.validation.Valid; import jakarta.validation.Valid;
@RestController @Controller
@RequestMapping(Constants.API_URL + "/genre") @RequestMapping(GenreController.URL)
public class GenreController { public class GenreController {
public static final String URL = Constants.ADMIN_PREFIX + "/genre";
private static final String GENRE_VIEW = "genre";
private static final String GENRE_EDIT_VIEW = "genre-edit";
private static final String GENRE_ATTRIBUTE = "genre";
private final GenreService genreService; private final GenreService genreService;
private final ModelMapper modelMapper; private final ModelMapper modelMapper;
public GenreController(GenreService genreService, ModelMapper modelMapper){ public GenreController(GenreService genreService, ModelMapper modelMapper) {
this.genreService = genreService; this.genreService = genreService;
this.modelMapper = modelMapper; this.modelMapper = modelMapper;
} }
private GenreDto toDto(GenreEntity entity){ private GenreDto toDto(GenreEntity entity) {
return modelMapper.map(entity, GenreDto.class); return modelMapper.map(entity, GenreDto.class);
} }
private GenreEntity toEntity(GenreDto dto){ private GenreEntity toEntity(GenreDto dto) {
return modelMapper.map(dto, GenreEntity.class); return modelMapper.map(dto, GenreEntity.class);
} }
@GetMapping @GetMapping
public List<GenreDto> getAll(){ public String getAll(Model model) {
return genreService.getAll().stream().map(this::toDto).toList(); model.addAttribute(
"items",
genreService.getAll().stream()
.map(this::toDto)
.toList());
return GENRE_VIEW;
} }
@GetMapping("/{id}") @GetMapping("/edit/")
public GenreDto get(@PathVariable(name="id") Long id){ public String create(Model model) {
return toDto(genreService.get(id)); model.addAttribute(GENRE_ATTRIBUTE, new GenreDto());
return GENRE_EDIT_VIEW;
} }
@PostMapping @PostMapping("/edit/")
public GenreDto create(@RequestBody @Valid GenreDto dto){ public String create(
return toDto(genreService.create(toEntity(dto))); @ModelAttribute(name = GENRE_ATTRIBUTE) @Valid GenreDto genre,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
return GENRE_EDIT_VIEW;
}
genreService.create(toEntity(genre));
return Constants.REDIRECT_VIEW + URL;
} }
@PutMapping("/{id}") @GetMapping("/edit/{id}")
public GenreDto update(@PathVariable(name="id") Long id, @RequestBody GenreDto dto){ public String update(
return toDto(genreService.update(id, toEntity(dto))); @PathVariable(name = "id") Long id,
Model model) {
if (id <= 0) {
throw new IllegalArgumentException();
}
model.addAttribute(GENRE_ATTRIBUTE, toDto(genreService.get(id)));
return GENRE_EDIT_VIEW;
} }
@DeleteMapping("/{id}") @PostMapping("/edit/{id}")
public GenreDto delete(@PathVariable(name="id") Long id){ public String update(
return toDto(genreService.delete(id)); @PathVariable(name = "id") Long id,
@ModelAttribute(name = GENRE_ATTRIBUTE) @Valid GenreDto genre,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
return GENRE_EDIT_VIEW;
}
if (id <= 0) {
throw new IllegalArgumentException();
}
genreService.update(id, toEntity(genre));
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/delete/{id}")
public String delete(
@PathVariable(name = "id") Long id) {
genreService.delete(id);
return Constants.REDIRECT_VIEW + URL;
} }
} }

View File

@ -1,83 +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.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.games.model.GameEntity;
import com.example.demo.games.service.GameService;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService;
import com.example.demo.users.service.UserService;
import com.example.demo.core.api.PageDtoMapper;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/user/{user}/order")
public class OrderController {
private final GameService gameService;
private final ModelMapper modelMapper;
private final OrderService orderService;
public OrderController(GameService gameService, ModelMapper modelMapper, OrderService orderService, UserService userService){
this.gameService = gameService;
this.modelMapper = modelMapper;
this.orderService = orderService;
}
private OrderDto toDto(OrderEntity entity){
var dto = new OrderDto();
dto.setId(entity.getId());
dto.setUserId(entity.getUser().getId());
dto.setGames(entity.getGames().stream().map(GameEntity::getId).toList());
return dto;
}
private OrderEntity toEntity(OrderDto dto){
final OrderEntity entity = modelMapper.map(dto, OrderEntity.class);
var games = dto.getGames();
for(var game : games){
entity.setGames(gameService.get(game));
}
return entity;
}
@GetMapping
public com.example.demo.core.api.PageDto<OrderDto> getAll(
@RequestParam(name = "userId", defaultValue = "") Long userId,
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE)int size){
return PageDtoMapper.toDto(orderService.getAll(userId, 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)));
}
@DeleteMapping("/{id}")
public OrderDto delete(
@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id){
return toDto(orderService.delete(userId, id));
}
}

View File

@ -3,40 +3,27 @@ package com.example.demo.orders.api;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
public class OrderDto { public class OrderDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotNull @NotNull
@Min(1)
private Long userId;
@NotNull
private final List<Long> games = new ArrayList<>(); private final List<Long> games = new ArrayList<>();
public Long getId(){ public Long getId() {
return id; return id;
} }
public void setId(Long id){
public void setId(Long id) {
this.id = id; this.id = id;
} }
public List<Long> getGames(){ public List<Long> getGames() {
return games; return games;
} }
public void setGames(List<Long> games){
public void setGames(List<Long> games) {
this.games.clear(); this.games.clear();
this.games.addAll(games); this.games.addAll(games);
} }
public Long getUserId(){
return userId;
}
public void setUserId(Long userId){
this.userId = userId;
}
} }

View File

@ -18,7 +18,7 @@ import jakarta.persistence.Table;
@Entity @Entity
@Table(name = "orders") @Table(name = "orders")
public class OrderEntity extends BaseEntity{ public class OrderEntity extends BaseEntity {
// @Column(nullable = false) // @Column(nullable = false)
// private double sum; // private double sum;
@ManyToOne @ManyToOne
@ -27,54 +27,57 @@ public class OrderEntity extends BaseEntity{
@ManyToMany() @ManyToMany()
private Set<GameEntity> games = new HashSet<>(); private Set<GameEntity> games = new HashSet<>();
public OrderEntity(){ public OrderEntity() {
} }
public OrderEntity(UserEntity user, List<GameEntity> games){ public OrderEntity(List<GameEntity> games) {
this.user = user;
this.games.clear(); this.games.clear();
this.games.addAll(games); this.games.addAll(games);
} }
// public double getSum(){ // public double getSum(){
// for(var game : games){ // for(var game : games){
// sum += game.getPrice(); // sum += game.getPrice();
// }
// return sum;
// } // }
public UserEntity getUser(){ // return sum;
// }
public UserEntity getUser() {
return user; return user;
} }
public void setUser(UserEntity user){
public void setUser(UserEntity user) {
this.user = user; this.user = user;
if(!user.getOrders().contains(this)){ if (!user.getOrders().contains(this)) {
user.getOrders().add(this); user.getOrders().add(this);
} }
} }
public Set<GameEntity> getGames(){ public Set<GameEntity> getGames() {
return games; return games;
} }
public void setGames(GameEntity game){
public void setGames(GameEntity game) {
this.games.add(game); this.games.add(game);
} }
@Override @Override
public int hashCode(){ public int hashCode() {
return Objects.hash(id, games); return Objects.hash(id, games);
} }
@Override @Override
public boolean equals(Object obj){ public boolean equals(Object obj) {
if(this == obj) return true; if (this == obj)
if(obj == null || getClass() != obj.getClass()) return false; return true;
if (obj == null || getClass() != obj.getClass())
return false;
final OrderEntity other = (OrderEntity) obj; final OrderEntity other = (OrderEntity) obj;
return Objects.equals(other.getId(), id) return Objects.equals(other.getId(), id)
//&& Objects.equals(other.getSum(), sum) // && Objects.equals(other.getSum(), sum)
&& Objects.equals(other.getGames(), games); && Objects.equals(other.getGames(), games);
} }
} }

View File

@ -11,7 +11,8 @@ import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.orders.model.OrderEntity; import com.example.demo.orders.model.OrderEntity;
public interface OrderRepository extends CrudRepository<OrderEntity, Long>, PagingAndSortingRepository<OrderEntity, Long> { public interface OrderRepository
extends CrudRepository<OrderEntity, Long>, PagingAndSortingRepository<OrderEntity, Long> {
Optional<OrderEntity> findOneByUserIdAndId(long userId, long id); Optional<OrderEntity> findOneByUserIdAndId(long userId, long id);
List<OrderEntity> findByUserId(long userId); List<OrderEntity> findByUserId(long userId);
@ -21,5 +22,5 @@ public interface OrderRepository extends CrudRepository<OrderEntity, Long>, Pagi
List<OrderEntity> findAll(); List<OrderEntity> findAll();
//Можно сделать запрос на сумму JPQL // Можно сделать запрос на сумму JPQL
} }

View File

@ -1,11 +1,13 @@
package com.example.demo.orders.service; package com.example.demo.orders.service;
import java.util.List; import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException; import com.example.demo.core.error.NotFoundException;
@ -19,37 +21,38 @@ public class OrderService {
private final OrderRepository repository; private final OrderRepository repository;
private final UserService userService; private final UserService userService;
public OrderService(OrderRepository repository, UserService userService){ public OrderService(OrderRepository repository, UserService userService) {
this.repository = repository; this.repository = repository;
this.userService = userService; this.userService = userService;
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Page<OrderEntity> getAll(long userId, int page, int size){ public Page<OrderEntity> getAll(long userId, int page, int size) {
final Pageable pageRequest = PageRequest.of(page, size); final Pageable pageRequest = PageRequest.of(page, size, Sort.by("id"));
userService.get(userId); userService.get(userId);
return repository.findByUserId(userId, pageRequest); return repository.findByUserId(userId, pageRequest);
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<OrderEntity> getAll(long userId){ public List<OrderEntity> getAll(long userId) {
userService.get(userId); userService.get(userId);
return repository.findByUserId(userId); return repository.findByUserId(userId);
} }
public List<OrderEntity> getAll(){
public List<OrderEntity> getAll() {
return repository.findAll(); return repository.findAll();
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public OrderEntity get(long userId, long id){ public OrderEntity get(long userId, long id) {
userService.get(userId); userService.get(userId);
return repository.findOneByUserIdAndId(userId, id).orElseThrow(() -> new NotFoundException(OrderEntity.class, id)); return repository.findOneByUserIdAndId(userId, id)
.orElseThrow(() -> new NotFoundException(OrderEntity.class, id));
} }
@Transactional @Transactional
public OrderEntity create(long userId, OrderEntity entity){ public OrderEntity create(long userId, OrderEntity entity) {
if(entity == null){ if (entity == null) {
throw new IllegalArgumentException("Entity is null"); throw new IllegalArgumentException("Entity is null");
} }
final UserEntity existsUser = userService.get(userId); final UserEntity existsUser = userService.get(userId);
@ -58,7 +61,17 @@ public class OrderService {
} }
@Transactional @Transactional
public OrderEntity delete(long userId, long id){ public List<OrderEntity> createAll(long userId, List<OrderEntity> entities) {
if (entities == null || entities.isEmpty()) {
throw new IllegalArgumentException("Orders list is null or empty");
}
final UserEntity existsUser = userService.get(userId);
entities.forEach(entity -> entity.setUser(existsUser));
return StreamSupport.stream(repository.saveAll(entities).spliterator(), false).toList();
}
@Transactional
public OrderEntity delete(long userId, long id) {
userService.get(userId); userService.get(userId);
final OrderEntity existsEntity = get(userId, id); final OrderEntity existsEntity = get(userId, id);
repository.delete(existsEntity); repository.delete(existsEntity);

View File

@ -1,16 +1,14 @@
package com.example.demo.types.api; package com.example.demo.types.api;
import java.util.List;
import org.modelmapper.ModelMapper; import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping; 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.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; 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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.configuration.Constants; import com.example.demo.core.configuration.Constants;
import com.example.demo.types.model.TypeEntity; import com.example.demo.types.model.TypeEntity;
@ -18,47 +16,90 @@ import com.example.demo.types.service.TypeService;
import jakarta.validation.Valid; import jakarta.validation.Valid;
@RestController @Controller
@RequestMapping(Constants.API_URL + "/type") @RequestMapping(TypeController.URL)
public class TypeController { 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 TypeService typeService;
private final ModelMapper modelMapper; private final ModelMapper modelMapper;
public TypeController(TypeService typeService, ModelMapper modelMapper){ public TypeController(TypeService typeService, ModelMapper modelMapper) {
this.typeService = typeService; this.typeService = typeService;
this.modelMapper = modelMapper; this.modelMapper = modelMapper;
} }
private TypeDto toDto(TypeEntity entity){ private TypeDto toDto(TypeEntity entity) {
return modelMapper.map(entity, TypeDto.class); return modelMapper.map(entity, TypeDto.class);
} }
private TypeEntity toEntity(TypeDto dto){ private TypeEntity toEntity(TypeDto dto) {
return modelMapper.map(dto, TypeEntity.class); return modelMapper.map(dto, TypeEntity.class);
} }
@GetMapping @GetMapping
public List<TypeDto> getAll(){ public String getAll(Model model) {
return typeService.getAll().stream().map(this::toDto).toList(); model.addAttribute(
"items",
typeService.getAll().stream()
.map(this::toDto)
.toList());
return TYPE_VIEW;
} }
@GetMapping("/{id}") @GetMapping("/edit/")
public TypeDto get(@PathVariable(name = "id") Long id){ public String create(Model model) {
return toDto(typeService.get(id)); model.addAttribute(TYPE_ATTRIBUTE, new TypeDto());
return TYPE_EDIT_VIEW;
} }
@PostMapping @PostMapping("/edit/")
public TypeDto create(@RequestBody @Valid TypeDto dto){ public String create(
return toDto(typeService.create(toEntity(dto))); @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;
} }
@PutMapping("/{id}") @GetMapping("/edit/{id}")
public TypeDto update(@PathVariable(name = "id") Long id, @RequestBody TypeDto dto){ public String update(
return toDto(typeService.update(id, toEntity(dto))); @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;
} }
@DeleteMapping("/{id}") @PostMapping("/edit/{id}")
public TypeDto delete(@PathVariable(name = "id") Long id){ public String update(
return toDto(typeService.delete(id)); @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,30 +1,27 @@
package com.example.demo.types.api; package com.example.demo.types.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
public class TypeDto { public class TypeDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotBlank @NotBlank
@Size(min = 1, max = 50) @Size(min = 1, max = 50)
private String name; private String name;
public Long getId(){ public Long getId() {
return id; return id;
} }
public void setId(Long id){ public void setId(Long id) {
this.id = id; this.id = id;
} }
public String getName(){ public String getName() {
return name; return name;
} }
public void setName(String name){ public void setName(String name) {
this.name = name; this.name = name;
} }
} }

View File

@ -0,0 +1,128 @@
package com.example.demo.users.api;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import com.example.demo.core.configuration.Constants;
import com.example.demo.core.security.UserPrincipal;
import com.example.demo.core.session.SessionCart;
import com.example.demo.games.api.GameDto;
import com.example.demo.games.model.GameEntity;
import com.example.demo.games.service.GameService;
import com.example.demo.genres.model.GenreEntity;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService;
import jakarta.validation.Valid;
@Controller
@RequestMapping(UserCartController.URL)
@SessionAttributes("games")
public class UserCartController {
public static final String URL = "/cart";
private static final String ORDER_VIEW = "cart";
private static final String ORDER_ATTRIBUTE = "order";
private static final String CART_ATTRIBUTE = "cart";
private final GameService gameService;
private final OrderService orderService;
private final SessionCart cart;
private final ModelMapper modelMapper;
public UserCartController(
GameService gameService,
OrderService orderService,
SessionCart cart,
ModelMapper modelMapper) {
this.gameService = gameService;
this.orderService = orderService;
this.cart = cart;
this.modelMapper = modelMapper;
}
private GameDto toGameDto(GameEntity entity) {
var dto = new GameDto();
dto.setId(entity.getId());
dto.setGenres(entity.getGenres().stream().map(GenreEntity::getId).toList());
dto.setDescription(entity.getDescription());
dto.setName(entity.getName());
dto.setPrice(entity.getPrice());
dto.setTypeId(entity.getType().getId());
return dto;
}
private List<OrderEntity> toOrderEntities(Collection<UserCartDto> dtos) {
final Set<Long> gameIds = dtos.stream()
.map(UserCartDto::getGame)
.collect(Collectors.toSet());
final Map<Long, GameEntity> games = gameService.getByIds(gameIds).stream()
.collect(Collectors.toMap(GameEntity::getId, Function.identity()));
return dtos.stream()
.map(dto -> {
final OrderEntity entity = modelMapper.map(dto, OrderEntity.class);
entity.setGames(games.get(dto.getGame()));
return entity;
}).toList();
}
@GetMapping
public String getCart(Model model) {
model.addAttribute("games",
gameService.getAll(0, 0).stream()
.map(this::toGameDto)
.toList());
model.addAttribute(ORDER_ATTRIBUTE, new UserCartDto());
model.addAttribute(CART_ATTRIBUTE, cart.values());
return ORDER_VIEW;
}
@PostMapping
public String addOrderToCart(
@ModelAttribute(name = ORDER_ATTRIBUTE) @Valid UserCartDto order,
BindingResult bindingResult,
SessionStatus status,
Model model) {
if (bindingResult.hasErrors()) {
return ORDER_VIEW;
}
status.setComplete();
order.setGameName(gameService.get(order.getGame()).getName());
order.setPrice(gameService.get(order.getGame()).getPrice());
cart.computeIfPresent(order.hashCode(), (key, value) -> {
return value;
});
cart.put(order.hashCode(), order);
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/save")
public String saveCart(
Model model,
@AuthenticationPrincipal UserPrincipal principal) {
orderService.createAll(principal.getId(), toOrderEntities(cart.values()));
cart.clear();
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/clear")
public String clearCart() {
cart.clear();
return Constants.REDIRECT_VIEW + URL;
}
}

View File

@ -0,0 +1,53 @@
package com.example.demo.users.api;
import java.util.Objects;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public class UserCartDto {
@NotNull
private Long game;
private String gameName;
@Min(1000)
private Double price;
public Long getGame() {
return game;
}
public void setGame(Long gameId) {
this.game = gameId;
}
public String getGameName() {
return gameName;
}
public void setGameName(String gameName) {
this.gameName = gameName;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public int hashCode() {
return Objects.hash(game, price);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
UserCartDto other = (UserCartDto) obj;
return Objects.equals(game, other.game) && Objects.equals(price, other.price);
}
}

View File

@ -1,18 +1,22 @@
package com.example.demo.users.api; package com.example.demo.users.api;
import java.util.Map;
import org.modelmapper.ModelMapper; import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping; 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.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; 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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.core.api.PageAttributesMapper;
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.core.configuration.Constants;
import com.example.demo.orders.service.OrderService; import com.example.demo.orders.service.OrderService;
import com.example.demo.users.model.UserEntity; import com.example.demo.users.model.UserEntity;
@ -20,49 +24,103 @@ import com.example.demo.users.service.UserService;
import jakarta.validation.Valid; import jakarta.validation.Valid;
@RestController @Controller
@RequestMapping(Constants.API_URL+"/user") @RequestMapping(UserController.URL)
public class UserController { 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 ModelMapper modelMapper; private final ModelMapper modelMapper;
private final UserService userService; private final UserService userService;
public UserController(OrderService orderService, ModelMapper modelMapper, UserService userService){ public UserController(OrderService orderService, ModelMapper modelMapper, UserService userService) {
this.modelMapper = modelMapper; this.modelMapper = modelMapper;
this.userService = userService; this.userService = userService;
} }
private UserDto toDto(UserEntity entity){ private UserDto toDto(UserEntity entity) {
return modelMapper.map(entity, UserDto.class); return modelMapper.map(entity, UserDto.class);
} }
private UserEntity toEntity(UserDto dto){ private UserEntity toEntity(UserDto dto) {
return modelMapper.map(dto, UserEntity.class); return modelMapper.map(dto, UserEntity.class);
} }
@GetMapping @GetMapping
public PageDto<UserDto> getAll( public String getAll(
@RequestParam(name = "page", defaultValue = "0") int page, @RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) { Model model) {
return PageDtoMapper.toDto(userService.getAll(page, size), this::toDto); final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
userService.getAll(page, Constants.DEFAULT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attributes);
model.addAttribute(PAGE_ATTRIBUTE, page);
return USER_VIEW;
} }
@GetMapping("/{id}") @GetMapping("/edit/")
public UserDto get(@PathVariable(name = "id") Long id){ public String create(
return toDto(userService.get(id)); @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 @PostMapping("/edit/")
public UserDto create(@RequestBody @Valid UserDto dto){ public String create(
return toDto(userService.create(toEntity(dto))); @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;
} }
@PutMapping("/{id}") @GetMapping("/edit/{id}")
public UserDto update(@PathVariable(name = "id") Long id, @RequestBody UserDto dto){ public String update(
return toDto(userService.update(id, toEntity(dto))); @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;
} }
@DeleteMapping("/{id}") @PostMapping("/edit/{id}")
public UserDto delete(@PathVariable(name = "id")Long 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 UserDto delete(@PathVariable(name = "id") Long id) {
return toDto(userService.delete(id)); return toDto(userService.delete(id));
} }
} }

View File

@ -1,12 +1,9 @@
package com.example.demo.users.api; package com.example.demo.users.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
public class UserDto { public class UserDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotBlank @NotBlank
@Size(min = 2, max = 20) @Size(min = 2, max = 20)
@ -14,35 +11,37 @@ public class UserDto {
@NotBlank @NotBlank
@Size(min = 2, max = 20) @Size(min = 2, max = 20)
private String email; private String email;
@NotBlank private String role;
@Size(min = 2, max = 20)
private String password;
public Long getId(){ public Long getId() {
return id; return id;
} }
public void setId(Long id){
public void setId(Long id) {
this.id = id; this.id = id;
} }
public String getLogin(){ public String getLogin() {
return login; return login;
} }
public void setLogin(String login){
public void setLogin(String login) {
this.login = login; this.login = login;
} }
public String getEmail(){ public String getEmail() {
return email; return email;
} }
public void setEmail(String email){
public void setEmail(String email) {
this.email = email; this.email = email;
} }
public String getPassword(){ public String getRole() {
return password; return role;
} }
public void setPassword(String password){
this.password = password; public void setRole(String role) {
this.role = role;
} }
} }

View File

@ -0,0 +1,82 @@
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.web.bind.annotation.GetMapping;
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.core.security.UserPrincipal;
import com.example.demo.games.api.GameDto;
import com.example.demo.games.model.GameEntity;
import com.example.demo.games.service.GameService;
import com.example.demo.genres.model.GenreEntity;
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.users.service.UserService;
@Controller
public class UserProfileController {
private static final String PROFILE_VIEW = "profile";
private static final String PAGE_ATTRIBUTE = "page";
private static final String TYPEID_ATTRIBUTE = "gameId";
private static final String PROFILE_ATTRIBUTE = "profile";
private final OrderService orderService;
private final GameService gameService;
private final UserService userService;
private final ModelMapper modelMapper;
public UserProfileController(
OrderService orderService,
GameService gameService,
UserService userService,
ModelMapper modelMapper) {
this.orderService = orderService;
this.gameService = gameService;
this.userService = userService;
this.modelMapper = modelMapper;
}
private OrderDto toDto(OrderEntity entity) {
var dto = new OrderDto();
dto.setId(entity.getId());
dto.setGames(entity.getGames().stream().map(GameEntity::getId).toList());
return dto;
}
private GameDto toGameDto(GameEntity entity) {
var dto = new GameDto();
dto.setId(entity.getId());
dto.setGenres(entity.getGenres().stream().map(GenreEntity::getId).toList());
dto.setDescription(entity.getDescription());
dto.setName(entity.getName());
dto.setPrice(entity.getPrice());
dto.setTypeId(entity.getType().getId());
return dto;
}
@GetMapping
public String getProfile(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@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(TYPEID_ATTRIBUTE, typeId);
model.addAllAttributes(PageAttributesMapper.toAttributes(
orderService.getAll(userId, page, Constants.DEFAULT_PAGE_SIZE),
this::toDto));
model.addAttribute("games",
gameService.getAll(0, 0).stream()
.map(this::toGameDto)
.toList());
return PROFILE_VIEW;
}
}

View File

@ -0,0 +1,63 @@
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

@ -0,0 +1,51 @@
package com.example.demo.users.api;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserSignupDto {
@NotBlank
@Size(min = 3, max = 20)
private String login;
@NotBlank
@Size(min = 3, max = 20)
private String email;
@NotBlank
@Size(min = 3, max = 20)
private String password;
@NotBlank
@Size(min = 3, max = 20)
private String passwordConfirm;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}

View File

@ -20,8 +20,9 @@ public class UserEntity extends BaseEntity{
private String login; private String login;
@Column(nullable = false, unique = true, length = 20) @Column(nullable = false, unique = true, length = 20)
private String email; private String email;
@Column(nullable = false, unique = true, length = 20) @Column(nullable = false, length = 60)
private String password; private String password;
private UserRole role;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL) @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
@OrderBy("id ASC") @OrderBy("id ASC")
private List<OrderEntity> orders = new ArrayList<>(); private List<OrderEntity> orders = new ArrayList<>();
@ -33,6 +34,7 @@ public class UserEntity extends BaseEntity{
this.login = login; this.login = login;
this.email = email; this.email = email;
this.password = password; this.password = password;
this.role = UserRole.USER;
} }
public String getLogin(){ public String getLogin(){
@ -56,6 +58,14 @@ public class UserEntity extends BaseEntity{
this.password = password; this.password = password;
} }
public UserRole getRole() {
return role;
}
public void setRole(UserRole role) {
this.role = role;
}
public List<OrderEntity> getOrders(){ public List<OrderEntity> getOrders(){
return orders; return orders;
} }

View File

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

View File

@ -4,60 +4,100 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport; import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
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.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;
import com.example.demo.core.configuration.Constants;
import com.example.demo.core.error.NotFoundException; 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.UserEntity;
import com.example.demo.users.model.UserRole;
import com.example.demo.users.repository.UserRepository; import com.example.demo.users.repository.UserRepository;
@Service @Service
public class UserService { public class UserService implements UserDetailsService {
private final UserRepository repository; private final UserRepository repository;
private final PasswordEncoder passwordEncoder;
public UserService(UserRepository repository){ public UserService(UserRepository repository, PasswordEncoder passwordEncoder) {
this.repository = repository; 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));
}
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<UserEntity> getAll(){ public List<UserEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList(); return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Page<UserEntity> getAll(int page, int size) { public Page<UserEntity> getAll(int page, int size) {
return repository.findAll(PageRequest.of(page, size)); return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public UserEntity get(Long id){ public UserEntity get(Long id) {
return repository.findById(id).orElseThrow(() -> new NotFoundException(UserEntity.class, id)); return repository.findById(id).orElseThrow(() -> new NotFoundException(UserEntity.class, id));
} }
@Transactional(readOnly = true)
public UserEntity getByLogin(String login) {
return repository.findByLoginIgnoreCase(login)
.orElseThrow(() -> new IllegalArgumentException("Invalid login"));
}
@Transactional @Transactional
public UserEntity create(UserEntity entity){ public UserEntity create(UserEntity entity) {
if (entity == null) { if (entity == null) {
throw new IllegalArgumentException("Entity is null"); throw new IllegalArgumentException("Entity is null");
} }
checkLogin(null, entity.getLogin());
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); return repository.save(entity);
} }
@Transactional @Transactional
public UserEntity update(Long id, UserEntity entity){ public UserEntity update(Long id, UserEntity entity) {
final UserEntity existEntity = get(id); final UserEntity existEntity = get(id);
checkLogin(id, entity.getLogin());
existEntity.setLogin(entity.getLogin()); existEntity.setLogin(entity.getLogin());
existEntity.setEmail(entity.getEmail()); existEntity.setEmail(entity.getEmail());
existEntity.setPassword(entity.getPassword());
repository.save(existEntity); repository.save(existEntity);
return existEntity; return existEntity;
} }
@Transactional @Transactional
public UserEntity delete(Long id){ public UserEntity delete(Long id) {
final UserEntity existEntity = get(id); final UserEntity existEntity = get(id);
repository.delete(existEntity); repository.delete(existEntity);
return existEntity; return existEntity;
} }
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final UserEntity existsUser = getByLogin(username);
return new UserPrincipal(existsUser);
}
} }

View File

@ -1,3 +1,4 @@
# Server
spring.main.banner-mode=off spring.main.banner-mode=off
server.port=8080 server.port=8080

View File

@ -0,0 +1,67 @@
html,
body {
height: 100%;
}
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: 32px;
color: rgba(255, 255, 255, 0.5);
}
.cart-image {
width: 3.1rem;
padding: 0.25rem;
border-radius: 0.5rem;
}
.cart-item {
height: auto;
}

View File

@ -0,0 +1,5 @@
<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: 478 B

View File

@ -0,0 +1,68 @@
<!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.gameName}]]
</div>
</div>
</div>
<div class=" mb-2 col-12 col-md-8 col-lg-6 d-flex justify-content-end">
</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="game" class="form-label">Товары</label>
<select th:field="*{game}" id="game" class="form-select">
<option selected value="">Укажите тип товара</option>
<option th:each="game : ${games}" th:value="${game.id}">[[${game.name}]]</option>
</select>
<div th:if="${#fields.hasErrors('game')}" th:errors="*{game}" 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,75 @@
<!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="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title layout:title-pattern="$LAYOUT_TITLE - $CONTENT_TITLE">My shop</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="bi bi-cart2 d-inline-block align-top me-1 logo"></i>
MyShop
</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, '')}">
<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/genre"
th:classappend="${activeLink.startsWith('/admin/genre') ? 'active' : ''}">
Жанры игр
</a>
<a class="nav-link" href="/admin/game"
th:classappend="${activeLink.startsWith('/admin/game') ? 'active' : ''}">
Игры
</a>
<a class="nav-link" href="/h2-console/" target="_blank">Консоль H2</a>
</th:block>
<a class="nav-link" href="/123" target="_blank">Ошибка 1</a>
<a class="nav-link" href="/admin/123" target="_blank">Ошибка 2</a>
</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>
<a class="navbar-brand" href="/cart">
<i class="bi bi-cart2 d-inline-block align-top me-1 logo"></i>
[[${#numbers.formatDecimal(totalCart, 1, 2)}]] &#8381;
</a>
</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,55 @@
<!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>Игры</h2>
<div>
<a href="/admin/game/edit/" class="btn btn-primary">Добавить игру</a>
</div>
<table class="table">
<caption></caption>
<thead>
<tr>
<th scope="col" class="w-10">ID</th>
<th scope="col" class="w-10">Название</th>
<th scope="col" class="w-10">Цена</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="game : ${items}">
<th scope="row" th:text="${game.id}"></th>
<td th:text="${game.name}"></td>
<td th:text="${game.price}"></td>
<td th:text="${game.description}"></td>
<td>
<form th:action="@{/admin/game/edit/{id}(id=${game.id})}" method="get">
<button type="submit" class="btn btn-link button-link">Редактировать</button>
</form>
</td>
<td>
<form th:action="@{/admin/game/delete/{id}(id=${game.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,28 @@
<!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/genre/edit/{id}(id=${genre.id})}" th:object="${genre}" method="post">
<div class="mb-3">
<label for="id" class="form-label">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">Жанр</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/genre">Отмена</a>
</div>
</form>
</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">
<th:block th:switch="${items.size()}">
<h2 th:case="0">Данные отсутствуют</h2>
<th:block th:case="*">
<h2>Жанры игр</h2>
<div>
<a href="/admin/genre/edit/" class="btn btn-primary">Добавить жанр игры</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="genre : ${items}">
<th scope="row" th:text="${genre.id}"></th>
<td th:text="${genre.name}"></td>
<td>
<form th:action="@{/admin/genre/edit/{id}(id=${genre.id})}" method="get">
<button type="submit" class="btn btn-link button-link">Редактировать</button>
</form>
</td>
<td>
<form th:action="@{/admin/genre/delete/{id}(id=${genre.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,42 @@
<!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">
<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">Имя пользователя</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">Пароль</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" 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>

View File

@ -0,0 +1,62 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<th:block th:fragment="orders (items, totalPages, currentPage), games (items, totalPages, currentPage)">
<th:block th:switch="${items.size()}">
<h2 th:case="0">Данные отсутствуют</h2>
<th:block th:case="*">
<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-10"></th>
</tr>
</thead>
<tbody>
<tr th:each="order : ${items}">
<th scope="row" th:text="${order.id}"></th>
<td>
<table class="table">
<thead>
<tr>
<th scope="col" class="w-10"></th>
<th scope="col" class="w-auto">Название игры</th>
</tr>
</thead>
<tbody>
<tr th:each="game : ${order.games}">
<th scope="row" th:text="${game}"></th>
</tr>
</tbody>
</table>
</td>
<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="typeId" th:value="${typeId}">
<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" href="/cart">Создать заказ</a>
</div>
</th:block>
</th:block>
</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,25 @@
<!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="nav nav-pills justify-content-center" role="tablist">
<li class="nav-item">
<a class="nav-link active" data-bs-toggle="pill" href="#orders">Заказы</a>
</li>
</ul> -->
<div class="tab-content mt-2">
<div class="tab-pane container active" id="orders">
<th:block
th:replace="~{ orders :: orders (items=${items}, totalPages=${totalPages}, currentPage=${currentPage})}" />
</div>
</div>
</main>
</body>
</html>

View File

@ -0,0 +1,40 @@
<!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">Имя пользователя</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="email" class="form-label">Почта</label>
<input type="email" th:field="*{email}" id="email" class="form-control">
<div th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="invalid-feedback"></div>
</div>
<div class="mb-3">
<label for="password" class="form-label">Пароль</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">Пароль (подтверждение)</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 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,28 @@
<!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/type/edit/{id}(id=${type.id})}" th:object="${type}" method="post">
<div class="mb-3">
<label for="id" class="form-label">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">Тип заказа</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>Типы игр</h2>
<div>
<a href="/admin/type/edit/" class="btn btn-primary">Добавить тип игры</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,34 @@
<!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/user/edit/{id}(id=${user.id},page=${page})}" th:object="${user}"
method="post">
<div class="mb-3">
<label for="id" class="form-label">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">Имя пользователя</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="email" class="form-label">Почта</label>
<input type="text" th:field="*{email}" id="email" class="form-control">
<div th:if="${#fields.hasErrors('email')}" th:errors="*{email}" 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,58 @@
<!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>Пользователи</h2>
<div>
<a th:href="@{/admin/user/edit/(page=${page})}" class="btn btn-primary">Добавить пользователя</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-10"></th>
<th scope="col" class="w-10"></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.email}"></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

@ -53,27 +53,27 @@ class OrderServiceTest {
private OrderEntity order1; private OrderEntity order1;
@BeforeEach @BeforeEach
void createData(){ void createData() {
genre1 = genreService.create(new GenreEntity("Приключения")); genre1 = genreService.create(new GenreEntity("Приключения"));
genre2 = genreService.create(new GenreEntity("Симулятор")); genre2 = genreService.create(new GenreEntity("Симулятор"));
type1 = typeService.create(new TypeEntity("Игра")); type1 = typeService.create(new TypeEntity("Игра"));
type2 = typeService.create(new TypeEntity("Программа")); type2 = typeService.create(new TypeEntity("Программа"));
genres1 = new ArrayList<GenreEntity>(); genres1 = new ArrayList<GenreEntity>();
genres1.add(genre1); genres1.add(genre1);
genres1.add(genre2); genres1.add(genre2);
genres2 = new ArrayList<GenreEntity>(); genres2 = new ArrayList<GenreEntity>();
genres2.add(genre2); genres2.add(genre2);
game1 = gameService.create(new GameEntity(type1,"Game1",2100.0,"good game", genres1)); game1 = gameService.create(new GameEntity(type1, "Game1", 2100.0, "good game", genres1));
game2 = gameService.create(new GameEntity( type2, "Game2", 1200.0,"bad game", genres2)); game2 = gameService.create(new GameEntity(type2, "Game2", 1200.0, "bad game", genres2));
games = new ArrayList<GameEntity>(); games = new ArrayList<GameEntity>();
games.add(game1); games.add(game1);
games.add(game2); games.add(game2);
user1 = userService.create(new UserEntity( "login1", "email@mail.com", "qwerty123")); user1 = userService.create(new UserEntity("login1", "email@mail.com", "qwerty123"));
order1 = orderService.create(user1.getId(), new OrderEntity(user1,games)); order1 = orderService.create(user1.getId(), new OrderEntity(games));
removeData(); removeData();
genre1 = genreService.create(new GenreEntity("Приключения")); genre1 = genreService.create(new GenreEntity("Приключения"));
@ -81,50 +81,51 @@ class OrderServiceTest {
type1 = typeService.create(new TypeEntity("Игра")); type1 = typeService.create(new TypeEntity("Игра"));
type2 = typeService.create(new TypeEntity("Программа")); type2 = typeService.create(new TypeEntity("Программа"));
genres1 = new ArrayList<GenreEntity>(); genres1 = new ArrayList<GenreEntity>();
genres1.add(genre1); genres1.add(genre1);
genres1.add(genre2); genres1.add(genre2);
genres2 = new ArrayList<GenreEntity>(); genres2 = new ArrayList<GenreEntity>();
genres2.add(genre2); genres2.add(genre2);
game1 = gameService.create(new GameEntity(type1,"Game1",2100.0,"good game", genres1)); game1 = gameService.create(new GameEntity(type1, "Game1", 2100.0, "good game", genres1));
game2 = gameService.create(new GameEntity( type2, "Game2", 1200.0,"bad game", genres2)); game2 = gameService.create(new GameEntity(type2, "Game2", 1200.0, "bad game", genres2));
games = new ArrayList<GameEntity>(); games = new ArrayList<GameEntity>();
games.add(game1); games.add(game1);
games.add(game2); games.add(game2);
user1 = userService.create(new UserEntity( "login1", "email@mail.com", "qwerty123")); user1 = userService.create(new UserEntity("login1", "email@mail.com", "qwerty123"));
order1 = orderService.create(user1.getId(), new OrderEntity(user1,games)); order1 = orderService.create(user1.getId(), new OrderEntity(games));
orderService.create(user1.getId(), new OrderEntity(user1,games)); orderService.create(user1.getId(), new OrderEntity(games));
} }
@AfterEach @AfterEach
void removeData(){ void removeData() {
orderService.getAll().forEach(item -> orderService.delete(item.getUser().getId(),item.getId())); orderService.getAll().forEach(item -> orderService.delete(item.getUser().getId(), item.getId()));
userService.getAll().forEach(item -> userService.delete(item.getId())); userService.getAll().forEach(item -> userService.delete(item.getId()));
gameService.getAll(0,0).forEach(item -> gameService.delete(item.getId())); gameService.getAll(0, 0).forEach(item -> gameService.delete(item.getId()));
typeService.getAll().forEach(item -> typeService.delete(item.getId())); typeService.getAll().forEach(item -> typeService.delete(item.getId()));
genreService.getAll().forEach(item -> genreService.delete(item.getId())); genreService.getAll().forEach(item -> genreService.delete(item.getId()));
} }
@Test @Test
void getTest(){ void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> gameService.get(0L)); Assertions.assertThrows(NotFoundException.class, () -> gameService.get(0L));
} }
@Test @Test
@Order(1) @Order(1)
void createTest(){ void createTest() {
Assertions.assertEquals(2, orderService.getAll(user1.getId()).size()); Assertions.assertEquals(2, orderService.getAll(user1.getId()).size());
} }
@Test @Test
@Order(2) @Order(2)
void deleteTest(){ void deleteTest() {
orderService.delete(user1.getId(),order1.getId()); orderService.delete(user1.getId(), order1.getId());
Assertions.assertEquals(1, orderService.getAll(user1.getId()).size()); Assertions.assertEquals(1, orderService.getAll(user1.getId()).size());
} }
} }
//зависимости, core->security, user(loadUserByUserName, userrole), core->configuration, дохуя контроллеров юзера core->session // зависимости, core->security, user(loadUserByUserName, userrole),
// core->configuration, дохуя контроллеров юзера core->session