lab45 в процессе

This commit is contained in:
Milana Ievlewa 2024-05-22 13:36:36 +04:00
parent f2f313b4f8
commit 68f1e0b0f8
75 changed files with 7154 additions and 405 deletions

View File

View File

@ -1,7 +1,7 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.5'
id 'io.spring.dependency-management' version '1.1.4'
id 'java'
id 'org.springframework.boot' version '3.2.5'
id 'io.spring.dependency-management' version '1.1.4'
}
group = 'com.example'
@ -10,7 +10,7 @@ version = '0.0.1-SNAPSHOT'
defaultTasks 'bootRun'
jar {
enabled = false
enabled = false
}
bootJar {
@ -19,25 +19,33 @@ bootJar {
assert System.properties['java.specification.version'] == '17' || '21'
java {
sourceCompatibility = '17'
sourceCompatibility = '17'
}
repositories {
mavenCentral()
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
implementation 'org.modelmapper:modelmapper:3.2.0'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.modelmapper:modelmapper:3.2.0'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.2.224'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.2.224'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:3.3.0'
runtimeOnly 'org.webjars.npm:bootstrap:5.3.3'
runtimeOnly 'org.webjars.npm:bootstrap-icons:1.11.3'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
useJUnitPlatform()
}

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@ -10,6 +10,8 @@ import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.demo.orders.api.OrderIventDto;
import com.example.demo.orders.service.OrderService;
import com.example.demo.ivents.model.IventEntity;
import com.example.demo.ivents.service.IventService;
import com.example.demo.types.model.TypeEntity;
@ -17,6 +19,7 @@ import com.example.demo.types.service.TypeService;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.places.service.PlaceService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.model.UserRole;
import com.example.demo.users.service.UserService;
@SpringBootApplication
@ -26,12 +29,15 @@ public class DemoApplication implements CommandLineRunner {
private final TypeService typeService;
private final PlaceService placeService;
private final IventService iventService;
private final OrderService orderService;
private final UserService userService;
public DemoApplication(PlaceService placeService, TypeService typeService, IventService iventService, UserService userService) {
public DemoApplication(PlaceService placeService, TypeService typeService, IventService iventService,
OrderService orderService, UserService userService) {
this.placeService = placeService;
this.typeService = typeService;
this.iventService = iventService;
this.orderService = orderService;
this.userService = userService;
}
@ -41,7 +47,6 @@ public class DemoApplication implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
if (args.length > 0 && Arrays.asList(args).contains("--populate")) {
log.info("Create default types&dates values");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate _date = LocalDate.parse("2023-10-15", formatter);
@ -55,18 +60,18 @@ public class DemoApplication implements CommandLineRunner {
final var place3 = placeService.create(new PlaceEntity("UK, London"));
log.info("Create default ivents values");
iventService.create(new IventEntity(
final var ivent1 = iventService.create(new IventEntity(
"Slipknot",
type1,
_date,
"Slipknot - американская ню-метал группа, основанная в 1995 году. Они известны своим агрессивным звучанием, смешением хардкор-панк и тяжелого метала с индастриалом и элементами альтернативного рока.",
"Slipknot(test) - американская ню-метал группа, основанная в 1995 году. Они известны своим агрессивным звучанием, смешением хардкор-панк и тяжелого метала с индастриалом и элементами альтернативного рока.",
"Участники группы Slipknot - это:<....>",
2500.33,
30,
place1,
""));
"https://sun9-78.userapi.com/impg/GqEhiQUHIxaQgbsA0xEL3LFSQDihGD_PCWrQiQ/-DaQ2XoijZE.jpg?size=500x600&quality=96&sign=0eb5cbb4139b47c00287dceacc1aa4c1&type=album"));
iventService.create(new IventEntity(
final var ivent2 = iventService.create(new IventEntity(
"Placebo",
type1,
_date,
@ -75,7 +80,7 @@ public class DemoApplication implements CommandLineRunner {
2500.33,
30,
place2,
""));
"https://sun9-32.userapi.com/impg/2pvZuqVQH4hOX2pDuR7G9VMA8d-yVoEkgeYtGQ/YUHaozp5U18.jpg?size=564x798&quality=96&sign=e60e12e163aa46f084f28cc6ce5487c5&type=album"));
iventService.create(new IventEntity(
"Radiohead",
@ -86,7 +91,7 @@ public class DemoApplication implements CommandLineRunner {
2500.33,
30,
place3,
""));
"https://sun7-21.userapi.com/impg/C5aKzJPvxULBB_CuWMgXIG6uj5AuB2qKlBVDxA/NR1B43MGKVs.jpg?size=500x629&quality=96&sign=ff85339d4ff11424738fe9d58c0b2d23&type=album"));
iventService.create(new IventEntity(
"Сияние",
@ -97,7 +102,7 @@ public class DemoApplication implements CommandLineRunner {
2500.33,
45,
place3,
""));
"https://sun9-3.userapi.com/impg/9oGzwF1Xx2OZmN_xzFGUo2AewBbuo2y2QYskTw/4euSR1gwhmE.jpg?size=556x832&quality=96&sign=d6e480044eedf3a0e0c24f16ad7473f7&type=album"));
iventService.create(new IventEntity(
"Мастер и Маргарита",
@ -108,12 +113,26 @@ public class DemoApplication implements CommandLineRunner {
2500.33,
30,
place2,
""));
"https://sun9-47.userapi.com/impg/AH0Cg6gGvoiKg324O8g4fipjZnNKf2SWg-oEUg/0L9VzH-6sGw.jpg?size=563x713&quality=96&sign=1b53e1cc0c69b3b09f6af2a5257757e7&type=album"));
log.info("Create default users values");
userService.create(new UserEntity("Admin", "Admin@gmail.com", "admin", "admin"));
userService.create(new UserEntity("Milana", "milana@gmail.com", "milana", "user"));
userService.create(new UserEntity("TestUser", "user@gmail.com", "test", "user"));
final var admin = new UserEntity("Admin", "Admin@gmail.com", "admin");
final var user1 = userService.create(new UserEntity("Milana", "milana@gmail.com", "milana"));
final var user2 = userService.create(new UserEntity("TestUser", "user@gmail.com", "test"));
admin.setRole(UserRole.ADMIN);
userService.create(admin);
log.info("Create default orders values");
OrderIventDto ivent10 = new OrderIventDto();
ivent10.setIventId(ivent1.getId());
ivent10.setQuantity(4);
OrderIventDto ivent20 = new OrderIventDto();
ivent20.setIventId(ivent2.getId());
ivent20.setQuantity(6);
orderService.create(user1.getId(), Arrays.asList(ivent10, ivent20));
}
}
}

View File

@ -0,0 +1,133 @@
package com.example.demo.cartItems.api;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
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.RequestParam;
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.orders.api.OrderIventDto;
import com.example.demo.orders.service.OrderService;
import com.example.demo.ivents.api.IventDto;
import com.example.demo.ivents.model.IventEntity;
import com.example.demo.ivents.service.IventService;
import jakarta.validation.Valid;
@Controller
@RequestMapping(CartItemController.URL)
@SessionAttributes("ivents")
public class CartItemController {
public static final String URL = "/cart";
private static final String ORDER_VIEW = "cart";
private static final String CART_ITEM_ATTRIBUTE = "cartItem";
private static final String CART_ATTRIBUTE = "cart";
private final OrderService orderService;
private final IventService iventService;
private final ModelMapper modelMapper;
private final SessionCart cart;
public CartItemController(IventService iventService, SessionCart cart, OrderService orderService,
ModelMapper modelMapper) {
this.iventService = iventService;
this.orderService = orderService;
this.modelMapper = modelMapper;
this.cart = cart;
}
private IventDto toIventDto(IventEntity entity) {
return modelMapper.map(entity, IventDto.class);
}
private List<OrderIventDto> toOrderIventDtos(Collection<CartItemDto> cartItems) {
return cartItems.stream().map(item -> {
final OrderIventDto dto = new OrderIventDto();
dto.setQuantity(item.getQuantity());
dto.setIventId(item.getIventId());
return dto;
}).toList();
}
@GetMapping
public String getCart(Model model, @AuthenticationPrincipal UserPrincipal principal) {
model.addAttribute("ivents",
iventService.getAll(0L, 0L, null, null).stream()
.map(this::toIventDto)
.toList());
model.addAttribute(CART_ITEM_ATTRIBUTE, new CartItemDto());
model.addAttribute(CART_ATTRIBUTE, cart.values());
return ORDER_VIEW;
}
@PostMapping
public String addItemToCart(
@ModelAttribute(name = CART_ITEM_ATTRIBUTE) @Valid CartItemDto cartItem,
BindingResult bindingResult,
@AuthenticationPrincipal UserPrincipal principal,
SessionStatus status,
Model model) {
if (bindingResult.hasErrors()) {
return ORDER_VIEW;
}
status.setComplete();
IventEntity ivent = iventService.get(cartItem.getIventId());
cartItem.setIventName(ivent.getName());
cartItem.setIventPrice(ivent.getPrice());
cart.computeIfPresent(cartItem.hashCode(), (key, value) -> {
value.setQuantity(value.getQuantity() + cartItem.getQuantity());
return value;
});
cart.putIfAbsent(cartItem.hashCode(), cartItem);
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/save")
public String createOrder(
Model model,
@AuthenticationPrincipal UserPrincipal principal) {
orderService.create(principal.getId(), toOrderIventDtos(cart.values()));
cart.clear();
return Constants.REDIRECT_VIEW + "/";
}
@PostMapping("/clear")
public String clearCart(@AuthenticationPrincipal UserPrincipal principal) {
cart.clear();
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/toggle-quantity")
public String increaseCartCount(
@RequestParam(name = "iventId", defaultValue = "0") Long iventId,
@RequestParam(name = "isIncrease", defaultValue = "false") boolean isIncrease,
@AuthenticationPrincipal UserPrincipal principal) {
if (iventId <= 0) {
throw new IllegalArgumentException();
}
cart.computeIfPresent(Objects.hash(iventId), (key, value) -> {
if (isIncrease) value.setQuantity(value.getQuantity() + 1);
else if (!isIncrease && value.getQuantity() - 1 > 0) value.setQuantity(value.getQuantity() - 1);
return value;
});
return Constants.REDIRECT_VIEW + URL;
}
}

View File

@ -0,0 +1,90 @@
package com.example.demo.cartItems.api;
import java.util.Objects;
import java.time.LocalDate;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public class CartItemDto {
private Long id;
@NotNull
@Min(1)
private Long iventId;
@NotNull
@Min(1)
private Integer quantity;
@NotNull
private String iventName;
@NotNull
private LocalDate iventDate;
@NotNull
@Min(1)
private Double iventPrice;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getIventId() {
return iventId;
}
public void setIventId(Long iventId) {
this.iventId = iventId;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public String getIventName() {
return iventName;
}
public void setIventName(String name) {
this.iventName = name;
}
public LocalDate getIventDate() {
return iventDate;
}
public void setIventDate(LocalDate date) {
this.iventDate = date;
}
public Double getIventPrice() {
return iventPrice;
}
public void setIventPrice(Double price) {
this.iventPrice = price;
}
@Override
public int hashCode() {
return Objects.hash(iventId);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
CartItemDto other = (CartItemDto) obj;
return Objects.equals(iventId, other.iventId) && Objects.equals(quantity, other.quantity);
}
}

View File

@ -0,0 +1,100 @@
package com.example.demo.catalog.api;
import java.util.Map;
import java.util.Objects;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import com.example.demo.cartItems.api.CartItemDto;
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.core.session.SessionCart;
import com.example.demo.ivents.api.ExpandedIventDto;
import com.example.demo.ivents.model.IventEntity;
import com.example.demo.ivents.service.IventService;
@Controller
public class CatalogController {
public static final String PRODUCTS_VIEW = "catalog";
private static final String PAGE_ATTRIBUTE = "page";
private final IventService iventService;
private final SessionCart cart;
private final ModelMapper modelMapper;
public CatalogController(IventService iventService,
ModelMapper modelMapper, SessionCart cart) {
this.iventService = iventService;
this.cart = cart;
this.modelMapper = modelMapper;
}
protected ExpandedIventDto toExpandedDto(IventEntity entity, Long userId) {
ExpandedIventDto dto = modelMapper.map(entity, ExpandedIventDto.class);
dto.setTypeName(entity.getType().getName());
final var t = cart.containsKey(Objects.hash(dto.getId()));
dto.setIsCartIvent(cart.containsKey(Objects.hash(dto.getId())));
return dto;
}
@GetMapping("/catalog")
public String getAll(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model,
@AuthenticationPrincipal UserPrincipal principal) {
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
iventService.getAll(0L, 0L, null, null, page, Constants.DEFAULT_PAGE_SIZE),
item -> toExpandedDto(item, principal.getId()));
model.addAllAttributes(attributes);
model.addAttribute(PAGE_ATTRIBUTE, page);
return PRODUCTS_VIEW;
}
@PostMapping("/buy")
public String addIventToCart(
Model model,
@RequestParam(name = "id") Long iventId,
@RequestParam(name = "isCartIvent") boolean isCartIvent,
SessionStatus status,
@AuthenticationPrincipal UserPrincipal principal) {
if (iventId <= 0) {
throw new IllegalArgumentException();
}
status.setComplete();
if (!isCartIvent)
buyIvent(iventId);
else
increaseCartItemQuantity(iventId);
return Constants.REDIRECT_VIEW + "/catalog";
}
private void buyIvent(Long iventId) {
IventEntity ivent = iventService.get(iventId);
CartItemDto cartItem = new CartItemDto();
cartItem.setIventId(iventId);
cartItem.setQuantity(1);
cartItem.setIventName(ivent.getName());
cartItem.setIventDate(ivent.getDate());
cartItem.setIventPrice(ivent.getPrice());
cart.putIfAbsent(cartItem.hashCode(), cartItem);
}
private void increaseCartItemQuantity(Long iventId) {
cart.computeIfPresent(Objects.hash(iventId), (key, value) -> {
value.setQuantity(value.getQuantity() + 1);
return value;
});
}
}

View File

@ -0,0 +1,27 @@
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;
@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() {
return cart.getSum();
}
}

View File

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

@ -1,9 +1,15 @@
package com.example.demo.core.configuration;
public class Constants {
public static final String SEQUENCE_NAME = "hibernate_sequence";
public static final String API_URL = "/api/1.0";
public static final String DEFAULT_PAGE_SIZE = "5";
public static final String SEQUENCE_NAME = "hibernate_sequence";
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() {
}

View File

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

View File

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

@ -18,10 +18,6 @@ public abstract class BaseEntity {
protected BaseEntity() {
}
protected BaseEntity(Long id) {
this.id = id;
}
public Long getId() {
return id;
}

View File

@ -1,17 +0,0 @@
package com.example.demo.core.repository;
import java.util.List;
public interface CommonRepository<E, T> {
List<E> getAll();
E get(T id);
E create(E entity);
E update(E entity);
E delete(E entity);
void deleteAll();
}

View File

@ -1,58 +0,0 @@
package com.example.demo.core.repository;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.example.demo.core.model.BaseEntity;
public abstract class MapRepository<E extends BaseEntity> implements CommonRepository<E, Long> {
private final Map<Long, E> entities = new TreeMap<>();
private Long lastId = 0L;
protected MapRepository() {
}
@Override
public List<E> getAll() {
return entities.values().stream().toList();
}
@Override
public E get(Long id) {
return entities.get(id);
}
@Override
public E create(E entity) {
lastId++;
entity.setId(lastId);
entities.put(lastId, entity);
return entity;
}
@Override
public E update(E entity) {
if (get(entity.getId()) == null) {
return null;
}
entities.put(entity.getId(), entity);
return entity;
}
@Override
public E delete(E entity) {
if (get(entity.getId()) == null) {
return null;
}
entities.remove(entity.getId());
return entity;
}
@Override
public void deleteAll() {
lastId = 0L;
entities.clear();
}
}

View File

@ -0,0 +1,64 @@
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,65 @@
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 handle;
private final String password;
private final Set<? extends GrantedAuthority> roles;
private final boolean active;
public UserPrincipal(UserEntity user) {
this.id = user.getId();
this.handle = user.getHandle();
this.password = user.getPassword();
this.roles = Set.of(user.getRole());
this.active = true;
}
public Long getId() {
return id;
}
@Override
public String getUsername() {
return handle;
}
@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,13 @@
package com.example.demo.core.session;
import java.util.HashMap;
import com.example.demo.cartItems.api.CartItemDto;
public class SessionCart extends HashMap<Integer, CartItemDto> {
public double getSum() {
return this.values().stream()
.mapToDouble(item -> item.getQuantity() * item.getIventPrice())
.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,20 +0,0 @@
package com.example.demo.core.utils;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public final class Formatter {
private Formatter() {
}
private static SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
public static String format(Date date) {
return dateFormatter.format(date);
}
public static Date parse(String date) throws ParseException {
return dateFormatter.parse(date);
}
}

View File

@ -0,0 +1,31 @@
package com.example.demo.ivents.api;
public class ExpandedIventDto extends IventDto {
private String typeName;
private String placeName;
private boolean isCartIvent;
public String getTypeName() {
return typeName;
}
public void setTypeName(String name) {
this.typeName = name;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String name) {
this.placeName = name;
}
public boolean getIsCartIvent() {
return isCartIvent;
}
public void setIsCartIvent(boolean flag) {
this.isCartIvent = flag;
}
}

View File

@ -1,32 +1,42 @@
package com.example.demo.ivents.api;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.Map;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.api.PageAttributesMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.core.security.UserPrincipal;
import com.example.demo.ivents.model.IventEntity;
import com.example.demo.ivents.service.IventService;
import com.example.demo.core.configuration.Constants;
import com.example.demo.types.service.TypeService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.api.TypeDto;
import com.example.demo.places.service.PlaceService;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.places.api.PlaceDto;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/ivents")
@Controller
@RequestMapping(IventController.URL)
public class IventController {
public static final String URL = Constants.ADMIN_PREFIX + "/ivent";
private static final String IVENT_VIEW = "ivent";
private static final String IVENT_EDIT_VIEW = "ivent-edit";
private static final String PAGE_ATTRIBUTE = "page";
private static final String IVENT_ATTRIBUTE = "ivent";
private final IventService iventService;
private final TypeService typeService;
private final PlaceService placeService;
@ -44,6 +54,21 @@ public class IventController {
return modelMapper.map(entity, IventDto.class);
}
private ExpandedIventDto toExpandedDto(IventEntity entity, Long userId) {
ExpandedIventDto dto = modelMapper.map(entity, ExpandedIventDto.class);
dto.setTypeName(typeService.get(dto.getTypeId()).getName());
dto.setPlaceName(placeService.get(dto.getPlaceId()).getName());
return dto;
}
private TypeDto toTypeDto(TypeEntity entity) {
return modelMapper.map(entity, TypeDto.class);
}
private PlaceDto toPlaceDto(PlaceEntity entity) {
return modelMapper.map(entity, PlaceDto.class);
}
private IventEntity toEntity(IventDto dto) {
final IventEntity entity = modelMapper.map(dto, IventEntity.class);
entity.setType(typeService.get(dto.getTypeId()));
@ -51,37 +76,86 @@ public class IventController {
return entity;
}
@GetMapping
public List<IventDto> getAll(
@RequestParam(name = "typeId", defaultValue = "0") Long typeId,
@RequestParam(name = "placeId", defaultValue = "0") Long placeId,
@RequestParam(name = "startDate", defaultValue = "0001-01-01") String startDate,
@RequestParam(name = "endDate", defaultValue = "9999-12-31") String endDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate _startDate = LocalDate.parse(startDate, formatter);
LocalDate _endDate = LocalDate.parse(endDate, formatter);
return iventService.getAll(typeId, placeId, _startDate, _endDate).stream().map(this::toDto).toList();
public String getAll(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model,
@AuthenticationPrincipal UserPrincipal principal) {
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
iventService.getAll(0L, 0L, null, null, page, Constants.DEFAULT_PAGE_SIZE),
item -> toExpandedDto(item, principal.getId()));
model.addAllAttributes(attributes);
model.addAttribute(PAGE_ATTRIBUTE, page);
return IVENT_VIEW;
}
@GetMapping("/{id}")
public IventDto get(@PathVariable(name = "id") Long id) {
return toDto(iventService.get(id));
@GetMapping("/edit/")
public String create(Model model) {
model.addAttribute(IVENT_ATTRIBUTE, new IventDto());
model.addAttribute("types",
typeService.getAll().stream()
.map(this::toTypeDto)
.toList());
model.addAttribute("places",
placeService.getAll().stream()
.map(this::toPlaceDto)
.toList());
return IVENT_EDIT_VIEW;
}
@PostMapping
public IventDto create(@RequestBody @Valid IventDto dto) {
return toDto(iventService.create(toEntity(dto)));
@PostMapping("/edit/")
public String create(
@ModelAttribute(name = IVENT_ATTRIBUTE) @Valid IventDto ivent,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
return IVENT_EDIT_VIEW;
}
iventService.create(toEntity(ivent));
return Constants.REDIRECT_VIEW + URL;
}
@PutMapping("/{id}")
public IventDto update(@PathVariable(name = "id") Long id, @RequestBody IventDto dto) {
return toDto(iventService.update(id, toEntity(dto)));
@GetMapping("/edit/{id}")
public String update(@PathVariable(name = "id") Long id, Model model) {
if (id <= 0) {
throw new IllegalArgumentException();
}
model.addAttribute("types",
typeService.getAll().stream()
.map(this::toTypeDto)
.toList());
model.addAttribute("places",
placeService.getAll().stream()
.map(this::toPlaceDto)
.toList());
model.addAttribute(IVENT_ATTRIBUTE, toDto(iventService.get(id)));
return IVENT_EDIT_VIEW;
}
@DeleteMapping("/{id}")
public IventDto delete(@PathVariable(name = "id") Long id) {
return toDto(iventService.delete(id));
@PostMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@ModelAttribute(name = IVENT_ATTRIBUTE) @Valid IventDto ivent,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
return IVENT_EDIT_VIEW;
}
if (id <= 0) {
throw new IllegalArgumentException();
}
iventService.update(id, toEntity(ivent));
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/delete/{id}")
public String delete(
@PathVariable(name = "id") Long id) {
iventService.delete(id);
return Constants.REDIRECT_VIEW + URL;
}
}

View File

@ -2,6 +2,7 @@ package com.example.demo.ivents.model;
import java.util.Objects;
import java.time.LocalDate;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.places.model.PlaceEntity;

View File

@ -9,8 +9,6 @@ import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.ivents.model.IventEntity;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.types.model.TypeEntity;
public interface IventRepository extends CrudRepository<IventEntity, Long> , PagingAndSortingRepository<IventEntity, Long> {
List<IventEntity> findByTypeId(Long typeId);

View File

@ -8,6 +8,7 @@ import java.util.Optional;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -17,8 +18,7 @@ import com.example.demo.ivents.model.IventEntity;
import com.example.demo.ivents.repository.IventRepository;
import com.example.demo.types.repository.TypeRepository;
import com.example.demo.places.repository.PlaceRepository;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.types.model.TypeEntity;
@Service
public class IventService {
@ -66,7 +66,8 @@ public class IventService {
}
@Transactional
public Page<IventEntity> getAll(Long typeId, Long placeId, LocalDate startDate, LocalDate endDate, Pageable pageable) {
public Page<IventEntity> getAll(Long typeId, Long placeId, LocalDate startDate, LocalDate endDate, int page, int size) {
final PageRequest pageable = PageRequest.of(page, size);
Page<IventEntity> resultPage;
if (startDate != null || endDate != null) {
@ -102,7 +103,7 @@ public class IventService {
@Transactional(readOnly = true)
public IventEntity get(Long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(IventEntity.class, id));
.orElseThrow(() -> new NotFoundException(IventEntity.class, id));
}
@Transactional
@ -133,13 +134,4 @@ public class IventService {
repository.delete(existsEntity);
return existsEntity;
}
/*public List<IventEntity> getAllDate(LocalDate startDate, LocalDate endDate) {
if (startDate == null) {
throw new IllegalArgumentException("Дата 'от' должна быть указана");
}
LocalDate end = Objects.requireNonNullElse(endDate, LocalDate.now());
return repository.getAll().stream()
.filter(item -> item.getDate().isAfter(startDate.minusDays(1)) && item.getDate().isBefore(end.plusDays(1))) // использование методов isAfter и isBefore для LocalDate
.collect(Collectors.toList());
}*/
}

View File

@ -0,0 +1,33 @@
package com.example.demo.orders.api;
import java.time.LocalDate;
public class ExpandedOrderIventDto extends OrderIventDto {
private String iventName;
private LocalDate iventDate;
private Double iventPrice;
public String getIventName() {
return iventName;
}
public void setIventName(String name) {
this.iventName = name;
}
public LocalDate getIventDate() {
return iventDate;
}
public void setIventName(LocalDate date) {
this.iventDate= date;
}
public Double getIventPrice() {
return iventPrice;
}
public void setIventPrice(Double price) {
this.iventPrice = price;
}
}

View File

@ -0,0 +1,86 @@
package com.example.demo.orders.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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.demo.core.api.PageAttributesMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.core.security.UserPrincipal;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.model.OrderIventEntity;
import com.example.demo.orders.service.OrderIventService;
import com.example.demo.orders.service.OrderService;
import com.example.demo.ivents.model.IventEntity;
import com.example.demo.ivents.service.IventService;
@Controller
@RequestMapping(OrderController.URL)
public class OrderController {
public static final String URL = "/orders";
private static final String ORDER_VIEW = "orders";
private static final String ORDER_DETAILS_VIEW = "order-details";
private static final String ORDER_ATTRIBUTE = "order";
private static final String PAGE_ATTRIBUTE = "page";
private final OrderService orderService;
private final OrderIventService orderIventService;
private final ModelMapper modelMapper;
private final IventService iventService;
public OrderController(
OrderService orderService,
OrderIventService orderIventService,
IventService iventService,
ModelMapper modelMapper) {
this.orderService = orderService;
this.iventService = iventService;
this.orderIventService = orderIventService;
this.modelMapper = modelMapper;
}
private OrderDto toDto(OrderEntity entity) {
return modelMapper.map(entity, OrderDto.class);
}
private ExpandedOrderIventDto toOrderIventDto(OrderIventEntity entity) {
ExpandedOrderIventDto dto = modelMapper.map(entity, ExpandedOrderIventDto.class);
IventEntity ivent = iventService.get(dto.getIventId());
dto.setIventName(ivent.getName());
dto.setIventPrice(ivent.getPrice());
return dto;
}
@GetMapping
public String getProfile(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model,
@AuthenticationPrincipal UserPrincipal principal) {
final long userId = principal.getId();
model.addAttribute(PAGE_ATTRIBUTE, page);
model.addAllAttributes(PageAttributesMapper.toAttributes(
orderService.getAll(userId, page, Constants.DEFAULT_PAGE_SIZE),
this::toDto));
return ORDER_VIEW;
}
@GetMapping("/details/{id}")
public String getOrderDetails(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model,
@AuthenticationPrincipal UserPrincipal principal) {
final long userId = principal.getId();
model.addAttribute(ORDER_ATTRIBUTE, orderService.get(userId, id));
model.addAllAttributes(PageAttributesMapper.toAttributes(
orderIventService.getAll(id, page, Constants.DEFAULT_PAGE_SIZE),
this::toOrderIventDto));
return ORDER_DETAILS_VIEW;
}
}

View File

@ -0,0 +1,46 @@
package com.example.demo.orders.api;
import java.time.LocalDate;
import java.util.List;
import org.springframework.cglib.core.Local;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class OrderDto {
private Long id;
private LocalDate date;
@NotNull
@Size(min = 1)
private List<OrderIventDto> orderIvents;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<OrderIventDto> getOrderIvents() {
return orderIvents;
}
public void setOrderIvents(List<OrderIventDto> orderIvents) {
this.orderIvents = orderIvents;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
}

View File

@ -0,0 +1,43 @@
package com.example.demo.orders.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public class OrderIventDto {
private Long id;
@NotNull
@Min(1)
private Long iventId;
@NotNull
@Min(1)
private Integer quantity;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getIventId() {
return iventId;
}
public void setIventId(Long iventId) {
this.iventId = iventId;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
}

View File

@ -0,0 +1,20 @@
package com.example.demo.orders.model;
public class ExpandedOrderEntity extends OrderEntity {
private Double total;
public ExpandedOrderEntity(OrderEntity order, Double total) {
// Вызов конструктора суперкласса для установки общих полей заказа
super(order.getUser(), order.getDate());
this.setId(order.getId()); // Устанавливаем идентификатор заказа
this.total = total; // Устанавливаем общую сумму
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
}

View File

@ -0,0 +1,95 @@
package com.example.demo.orders.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.users.model.UserEntity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
@Entity
@Table(name = "orders")
public class OrderEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "userId", nullable = false)
private UserEntity user;
@Column(nullable = false)
private Date date = new Date();
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@OrderBy("id ASC")
private List<OrderIventEntity> items = new ArrayList<>();
public OrderEntity() {
}
public OrderEntity(UserEntity user, Date date) {
this.user = user;
this.date = date;
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
if (!user.getOrders().contains(this)) {
user.getOrders().add(this);
}
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List<OrderIventEntity> getItems() {
return items;
}
public void setItems(List<OrderIventEntity> items) {
this.items = items;
}
public void addItem(OrderIventEntity orderIvent) {
if (orderIvent.getOrder() != this) {
orderIvent.setOrder(this);
}
items.add(orderIvent);
}
@Override
public int hashCode() {
return Objects.hash(id, user, items, date);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final OrderEntity other = (OrderEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getItems(), items)
&& Objects.equals(other.getDate(), date)
&& Objects.equals(other.getUser(), user);
}
}

View File

@ -0,0 +1,78 @@
package com.example.demo.orders.model;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.ivents.model.IventEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "orderIvents")
public class OrderIventEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "iventId", nullable = false)
private IventEntity ivent;
@ManyToOne
@JoinColumn(name = "orderId", nullable = false)
private OrderEntity order;
@Column(nullable = false)
private Integer quantity;
public OrderIventEntity() {
}
public OrderIventEntity(IventEntity ivent, Integer quantity) {
this.ivent = ivent;
this.quantity = quantity;
}
public OrderEntity getOrder() {
return order;
}
public void setOrder(OrderEntity order) {
this.order = order;
if (!order.getItems().contains(this)) {
order.getItems().add(this);
}
}
public IventEntity getIvent() {
return ivent;
}
public void setIvent(IventEntity ivent) {
this.ivent = ivent;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
@Override
public int hashCode() {
return Objects.hash(id, order, ivent, quantity);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final OrderIventEntity other = (OrderIventEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getOrder(), order)
&& Objects.equals(other.getIvent(), ivent)
&& Objects.equals(other.getQuantity(), quantity);
}
}

View File

@ -0,0 +1,17 @@
package com.example.demo.orders.repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.orders.model.OrderIventEntity;
public interface OrderIventRepository extends CrudRepository<OrderIventEntity, Long>,
PagingAndSortingRepository<OrderIventEntity, Long> {
List<OrderIventEntity> findByOrderId(long orderId);
Page<OrderIventEntity> findByOrderId(long orderId, Pageable pageable);
}

View File

@ -0,0 +1,31 @@
package com.example.demo.orders.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import com.example.demo.orders.model.ExpandedOrderEntity;
import com.example.demo.orders.model.OrderEntity;
public interface OrderRepository extends CrudRepository<OrderEntity, Long>,
PagingAndSortingRepository<OrderEntity, Long> {
List<OrderEntity> findByUserId(long userId);
Page<OrderEntity> findByUserId(long userId, Pageable pageable);
Optional<OrderEntity> findByUserIdAndId(long userId, long id);
@Query("SELECT NEW com.example.demo.orders.model.ExpandedOrderEntity(o, SUM(oi.quantity * p.price)) " +
"FROM OrderEntity o " +
"JOIN o.items oi " +
"JOIN oi.ivent p " +
"WHERE o.id = :orderId " +
"GROUP BY o")
ExpandedOrderEntity findOrderWithTotal(@Param("orderId") Long orderId);
}

View File

@ -0,0 +1,46 @@
package com.example.demo.orders.service;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.orders.model.OrderIventEntity;
import com.example.demo.orders.repository.OrderIventRepository;
@Service
public class OrderIventService {
private final OrderIventRepository repository;
public OrderIventService(OrderIventRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public List<OrderIventEntity> getAll(Long orderId) {
return repository.findByOrderId(orderId);
}
@Transactional(readOnly = true)
public Page<OrderIventEntity> getAll(long orderId, int page, int size) {
final Pageable pageable = PageRequest.of(page, size, Sort.by("id"));
return repository.findByOrderId(orderId, pageable);
}
@Transactional(readOnly = true)
public OrderIventEntity get(Long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(OrderIventEntity.class, id));
}
@Transactional
public List<OrderIventEntity> createMany(List<OrderIventEntity> orderIvents) {
repository.saveAll(orderIvents);
return orderIvents;
}
}

View File

@ -0,0 +1,78 @@
package com.example.demo.orders.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.orders.api.OrderIventDto;
import com.example.demo.orders.model.ExpandedOrderEntity;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.model.OrderIventEntity;
import com.example.demo.orders.repository.OrderRepository;
import com.example.demo.ivents.service.IventService;
import com.example.demo.users.service.UserService;
@Service
public class OrderService {
private final UserService userService;
private final OrderRepository repository;
private final OrderIventService orderIventService;
private final IventService iventService;
public OrderService(OrderRepository repository,
OrderIventService orderIventService,
UserService userService, IventService iventService) {
this.repository = repository;
this.orderIventService = orderIventService;
this.userService = userService;
this.iventService = iventService;
}
@Transactional(readOnly = true)
public List<OrderEntity> getAll(Long userId) {
userService.get(userId);
return repository.findByUserId(userId);
}
@Transactional(readOnly = true)
public Page<OrderEntity> getAll(long userId, int page, int size) {
final Pageable pageable = PageRequest.of(page, size, Sort.by("id"));
userService.get(userId);
return repository.findByUserId(userId, pageable);
}
@Transactional(readOnly = true)
public ExpandedOrderEntity get(Long userId, Long id) {
userService.get(userId);
return repository.findOrderWithTotal(id);
}
@Transactional
public OrderEntity create(Long userId, List<OrderIventDto> list) {
OrderEntity entity = new OrderEntity(userService.get(userId), new Date());
List<OrderIventEntity> orderIvents = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
OrderIventEntity oie = new OrderIventEntity(iventService.get(list.get(i)
.getIventId()),
list.get(i).getQuantity());
oie.setOrder(entity);
orderIvents.add(oie);
}
entity.setItems(orderIvents);
OrderEntity order = repository.save(entity);
orderIventService.createMany(order.getItems());
return order;
}
}

View File

@ -1,26 +1,38 @@
package com.example.demo.places.api;
import java.util.List;
import java.util.Map;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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.places.model.PlaceEntity;
import com.example.demo.places.service.PlaceService;
import com.example.demo.types.api.TypeDto;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/place")
@Controller
@RequestMapping(PlaceController.URL)
public class PlaceController {
public static final String URL = Constants.ADMIN_PREFIX + "/place";
public static final String PLACE_VIEW = "place";
public static final String PLACE_EDIT_VIEW = "place-edit";
public static final String PLACE_ATTRIBUTE = "place";
private static final String PAGE_ATTRIBUTE = "page";
private final PlaceService placeService;
private final ModelMapper modelMapper;
@ -38,28 +50,66 @@ public class PlaceController {
}
@GetMapping
public List<PlaceDto> getAll() {
return placeService.getAll().stream().map(this::toDto).toList();
public String getAll(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
placeService.getAll(page, Constants.DEFAULT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attributes);
model.addAttribute(PAGE_ATTRIBUTE, page);
return PLACE_VIEW;
}
@GetMapping("/{id}")
public PlaceDto get(@PathVariable(name = "id") Long id) {
return toDto(placeService.get(id));
@GetMapping("/edit/")
public String create(Model model) {
model.addAttribute(PLACE_ATTRIBUTE, new PlaceDto());
return PLACE_EDIT_VIEW;
}
@PostMapping
public PlaceDto create(@RequestBody @Valid PlaceDto dto) {
return toDto(placeService.create(toEntity(dto)));
@PostMapping("/edit/")
public String create(
@ModelAttribute(name = PLACE_ATTRIBUTE) @Valid PlaceDto place,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
return PLACE_EDIT_VIEW;
}
placeService.create(toEntity(place));
return Constants.REDIRECT_VIEW + URL;
}
@PutMapping("/{id}")
public PlaceDto update(@PathVariable(name = "id") Long id, @RequestBody PlaceDto dto) {
return toDto(placeService.update(id, toEntity(dto)));
@GetMapping("/edit/{id}")
public String update(@PathVariable(name = "id") Long id, Model model) {
if (id <= 0) {
throw new IllegalArgumentException();
}
model.addAttribute(PLACE_ATTRIBUTE, toDto(placeService.get(id)));
return PLACE_EDIT_VIEW;
}
@DeleteMapping("/{id}")
public PlaceDto delete(@PathVariable(name = "id") Long id) {
return toDto(placeService.delete(id));
@PostMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@ModelAttribute(name = PLACE_ATTRIBUTE) @Valid PlaceDto place,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
return PLACE_EDIT_VIEW;
}
if (id <= 0) {
throw new IllegalArgumentException();
}
placeService.update(id, toEntity(place));
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/delete/{id}")
public String delete(
@PathVariable(name = "id") Long id) {
placeService.delete(id);
return Constants.REDIRECT_VIEW + URL;
}
}

View File

@ -1,11 +1,8 @@
package com.example.demo.places.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
public class PlaceDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
private String name;

View File

@ -3,9 +3,11 @@ package com.example.demo.places.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.places.model.PlaceEntity;
public interface PlaceRepository extends CrudRepository<PlaceEntity, Long> {
public interface PlaceRepository extends CrudRepository<PlaceEntity, Long>, PagingAndSortingRepository<PlaceEntity, Long> {
Optional<PlaceEntity> findByNameIgnoreCase(String name);
}

View File

@ -3,12 +3,16 @@ package com.example.demo.places.service;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.places.repository.PlaceRepository;
import com.example.demo.types.model.TypeEntity;
@Service
public class PlaceService {
@ -30,6 +34,11 @@ public class PlaceService {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<PlaceEntity> getAll(int page, int size) {
return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
}
@Transactional(readOnly = true)
public PlaceEntity get(Long id) {
return repository.findById(id)

View File

@ -1,26 +1,37 @@
package com.example.demo.types.api;
import java.util.List;
import java.util.Map;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/type")
@Controller
@RequestMapping(TypeController.URL)
public class TypeController {
public static final String URL = Constants.ADMIN_PREFIX + "/type";
public static final String CATEGORY_VIEW = "type";
public static final String CATEGORY_EDIT_VIEW = "type-edit";
public static final String CATEGORY_ATTRIBUTE = "type";
private static final String PAGE_ATTRIBUTE = "page";
private final TypeService typeService;
private final ModelMapper modelMapper;
@ -37,29 +48,67 @@ public class TypeController {
return modelMapper.map(dto, TypeEntity.class);
}
@GetMapping
public List<TypeDto> getAll() {
return typeService.getAll().stream().map(this::toDto).toList();
@GetMapping
public String getAll(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
typeService.getAll(page, Constants.DEFAULT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attributes);
model.addAttribute(PAGE_ATTRIBUTE, page);
return CATEGORY_VIEW;
}
@GetMapping("/{id}")
public TypeDto get(@PathVariable(name = "id") Long id) {
return toDto(typeService.get(id));
@GetMapping("/edit/")
public String create(Model model) {
model.addAttribute(CATEGORY_ATTRIBUTE, new TypeDto());
return CATEGORY_EDIT_VIEW;
}
@PostMapping
public TypeDto create(@RequestBody @Valid TypeDto dto) {
return toDto(typeService.create(toEntity(dto)));
@PostMapping("/edit/")
public String create(
@ModelAttribute(name = CATEGORY_ATTRIBUTE) @Valid TypeDto type,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
return CATEGORY_EDIT_VIEW;
}
typeService.create(toEntity(type));
return Constants.REDIRECT_VIEW + URL;
}
@PutMapping("/{id}")
public TypeDto update(@PathVariable(name = "id") Long id, @RequestBody TypeDto dto) {
return toDto(typeService.update(id, toEntity(dto)));
@GetMapping("/edit/{id}")
public String update(@PathVariable(name = "id") Long id, Model model) {
if (id <= 0) {
throw new IllegalArgumentException();
}
model.addAttribute(CATEGORY_ATTRIBUTE, toDto(typeService.get(id)));
return CATEGORY_EDIT_VIEW;
}
@DeleteMapping("/{id}")
public TypeDto delete(@PathVariable(name = "id") Long id) {
return toDto(typeService.delete(id));
@PostMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@ModelAttribute(name = CATEGORY_ATTRIBUTE) @Valid TypeDto type,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
return CATEGORY_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,11 +1,8 @@
package com.example.demo.types.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
public class TypeDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
private String name;

View File

@ -3,9 +3,11 @@ package com.example.demo.types.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.types.model.TypeEntity;
public interface TypeRepository extends CrudRepository<TypeEntity, Long> {
Optional<TypeEntity> findByNameIgnoreCase(String name);
public interface TypeRepository extends CrudRepository<TypeEntity, Long>, PagingAndSortingRepository<TypeEntity, Long> {
Optional<TypeEntity> findByNameIgnoreCase(String name);
}

View File

@ -3,6 +3,9 @@ package com.example.demo.types.service;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -29,6 +32,11 @@ public class TypeService {
public List<TypeEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<TypeEntity> getAll(int page, int size) {
return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
}
@Transactional(readOnly = true)
public TypeEntity get(Long id) {

View File

@ -1,27 +1,40 @@
package com.example.demo.users.api;
import java.util.Map;
import org.modelmapper.ModelMapper;
import org.springframework.data.domain.jaxb.SpringDataJaxb.PageDto;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.core.api.PageDto;
import com.example.demo.core.api.PageDtoMapper;
import com.example.demo.core.api.PageAttributesMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/user")
@Controller
@RequestMapping(UserController.URL)
public class UserController {
public static final String URL = Constants.ADMIN_PREFIX + "/user";
private static final String USER_VIEW = "user";
private static final String USER_EDIT_VIEW = "user-edit";
private static final String USER_CREATE_VIEW = "user-create";
private static final String PAGE_ATTRIBUTE = "page";
private static final String USER_ATTRIBUTE = "user";
private final UserService userService;
private final ModelMapper modelMapper;
@ -39,29 +52,81 @@ public class UserController {
}
@GetMapping
public PageDto<UserDto> getAll(
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
return PageDtoMapper.toDto(userService.getAll(page, size), this::toDto);
public String getAll(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
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}")
public UserDto get(@PathVariable(name = "id") Long id) {
return toDto(userService.get(id));
@GetMapping("/create/")
public String create(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
model.addAttribute(USER_ATTRIBUTE, new UserDto());
model.addAttribute(PAGE_ATTRIBUTE, page);
return USER_CREATE_VIEW;
}
@PostMapping
public UserDto create(@RequestBody @Valid UserDto dto) {
return toDto(userService.create(toEntity(dto)));
@PostMapping("/create/")
public String create(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserDto user,
BindingResult bindingResult,
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return USER_CREATE_VIEW;
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
userService.create(toEntity(user));
return Constants.REDIRECT_VIEW + URL;
}
@PutMapping("/{id}")
public UserDto update(@PathVariable(name = "id") Long id, @RequestBody @Valid UserDto dto) {
return toDto(userService.update(id, toEntity(dto)));
@GetMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
if (id <= 0) {
throw new IllegalArgumentException();
}
model.addAttribute(USER_ATTRIBUTE, toDto(userService.get(id)));
model.addAttribute(PAGE_ATTRIBUTE, page);
return USER_EDIT_VIEW;
}
@DeleteMapping("/{id}")
public UserDto delete(@PathVariable(name = "id") Long id) {
return toDto(userService.delete(id));
@PostMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserDto user,
BindingResult bindingResult,
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return USER_EDIT_VIEW;
}
if (id <= 0) {
throw new IllegalArgumentException();
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
userService.update(id, toEntity(user));
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/delete/{id}")
public String delete(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
userService.delete(id);
return Constants.REDIRECT_VIEW + URL;
}
}

View File

@ -49,13 +49,5 @@ public class UserDto {
public void setPassword(String password) {
this.password = password;
}
public String getAccessLevel() {
return accessLevel;
}
public void setAccessLevel(String accessLevel) {
this.accessLevel = accessLevel;
}
}

View File

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

View File

@ -0,0 +1,39 @@
package com.example.demo.users.api;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserSignupDto {
@NotBlank
private String handle;
@NotBlank
@Size(min = 3, max = 20)
private String password;
@NotBlank
@Size(min = 3, max = 20)
private String passwordConfirm;
public String getLogin() {
return handle;
}
public void setLogin(String handle) {
this.handle = handle;
}
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

@ -1,8 +1,8 @@
package com.example.demo.users.model;
import java.util.HashSet;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import java.util.Set;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
@ -11,6 +11,9 @@ import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.orders.model.OrderEntity;
@Entity
@Table(name = "users")
public class UserEntity extends BaseEntity {
@ -20,17 +23,20 @@ public class UserEntity extends BaseEntity {
private String email;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String accessLevel;
private UserRole role;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
@OrderBy("id ASC")
private Set<OrderEntity> orders = new HashSet<>();
public UserEntity() {
}
public UserEntity(String handle, String email, String password, String accessLevel) {
public UserEntity(String handle, String email, String password) {
this.handle = handle;
this.email = email;
this.password = password;
this.accessLevel = accessLevel;
}
public String getHandle() {
@ -57,17 +63,28 @@ public class UserEntity extends BaseEntity {
this.password = password;
}
public String getAccessLevel() {
return accessLevel;
public Set<OrderEntity> getOrders() {
return orders;
}
public void setAccessLevel(String accessLevel) {
this.accessLevel = accessLevel;
public UserRole getRole() {
return role;
}
public void setRole(UserRole role) {
this.role = role;
}
public void addOrder(OrderEntity order) {
if (order.getUser() != this) {
order.setUser(this);
}
orders.add(order);
}
@Override
public int hashCode() {
return Objects.hash(id, handle, email, password, accessLevel);
return Objects.hash(id, handle, password, orders, role);
}
@Override
@ -79,9 +96,9 @@ public class UserEntity extends BaseEntity {
final UserEntity other = (UserEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getHandle(), handle)
&& Objects.equals(other.getEmail(), email)
&& Objects.equals(other.getPassword(), password)
&& Objects.equals(other.getAccessLevel(), accessLevel);
&& Objects.equals(other.getRole(), role)
&& Objects.equals(other.getOrders(), orders);
}
}

View File

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

View File

@ -1,23 +1,34 @@
package com.example.demo.users.service;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.example.demo.core.configuration.Constants;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.core.security.UserPrincipal;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.model.UserRole;
import com.example.demo.users.repository.UserRepository;
@Service
public class UserService {
public class UserService implements UserDetailsService {
private final UserRepository repository;
private final PasswordEncoder passwordEncoder;
public UserService(UserRepository repository) {
public UserService(UserRepository repository, PasswordEncoder passwordEncoder) {
this.repository = repository;
this.passwordEncoder = passwordEncoder;
}
private void checkHandle(String handle) {
@ -49,6 +60,12 @@ public class UserService {
throw new IllegalArgumentException("Entity is null");
}
checkHandle(entity.getHandle());
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);
}
@ -58,7 +75,6 @@ public class UserService {
existsEntity.setHandle(entity.getHandle());
existsEntity.setEmail(entity.getEmail());
existsEntity.setPassword(entity.getPassword());
existsEntity.setAccessLevel(entity.getAccessLevel());
repository.save(existsEntity);
return existsEntity;
}
@ -69,5 +85,19 @@ public class UserService {
repository.delete(existsEntity);
return existsEntity;
}
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final UserEntity existsUser = getByHandle(username);
return new UserPrincipal(existsUser);
}
@Transactional(readOnly = true)
public UserEntity getByHandle(String login) {
return repository.findByHandleIgnoreCase(
login)
.orElseThrow(() -> new IllegalArgumentException("Invalid handle"));
}
}

View File

@ -0,0 +1,188 @@
html,
header nav {
font-family: 'Correction Tape', sans-serif;
background-color:#2F2727;
color: #faebd7;
z-index: 1;
}
@media (min-width: 768px) {
header nav {
height: 54px;
}
}
header nav a:hover {
font-family: 'Correction Tape', sans-serif;
text-decoration: overline rgb(255, 119, 0);
z-index: 1;
}
body{
background-color: #3E3333;
font-family: 'Correction Tape', sans-serif;
color: #000000;
}
.card{
margin:10px;
}
footer {
font-family: 'Correction Tape', sans-serif;
background-color: #2F2727;
color: #faebd7;
padding-top: 20px;
}
.text-body-secondary {
margin-bottom: 0.5em; /* Указывайте здесь нужное вам расстояние */
}
.btn-primary{
background-color: #ff5500;
border-radius: 4px;
}
.btn-primary:hover{
background-color: #5233ff;
color:aqua;
}
.btn-secondary{
background-color: #523352;
color:#ff5500;
}
.btn-secondary:hover {
background-color: #006585;
color:aqua;
}
#remember-me:checked {
background-color: #ff5500; /*изменяет фон чекбокса при выборе*/
border-color: #5233ff; /*изменяет цвет рамки чекбокса*/
}
/*видео,*/
.video-foreground {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
align-items: center;
justify-content: center;
}
.video-foreground iframe {
width: 100%;
height: 100%;
pointer-events: none;
}
/*DEFAULT*/
#menu-wrapper {
position: fixed;
top: 56px;
left: -250px;
width: 250px;
height: 100%;
background-color: #3E3333;
transition: left 0.3s ease;
z-index: 1;
border-right: 3px solid #ff5500;
border-top: 3px solid #523352; /* Добавляем белую границу справа */
}
#menu-wrapper.open {
left: 0;
}
#menu {
padding: 20px;
}
#menu ul {
list-style-type: none;
padding: 0;
margin: 0;
}
#menu li {
margin-bottom: 10px;
}
#menu a {
text-decoration: none;
color: #ff5500;
font-size: 25px;
z-index: 1;
}
#toggle-menu {
cursor: pointer;
font-weight: bold;
}
#content {
margin-left: 250px;
padding: 20px;
}
/*INDEX*/
#video-container {
position: fixed;
left: 0px;
width: 100%;
height:100%;
}
#video-container video {
width: 100%;
height: 100%;
object-fit: cover;
z-index: -1;
}
#video-container .text-button-overlay {
position: absolute;
top: 40%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
color: #faebd7;
z-index: 1;
}
.text-button-overlay .text-overlay {
font-size: 120px;
white-space: nowrap;
}
.text-button-overlay .underText-overlay {
font-size: 50px;
color: #faebd7;
white-space: nowrap;
}
.text-button-overlay .button-overlay {
margin-top: 5%;
z-index: 1;
}
.button-overlay{
background-color: #ff5500;
border-color: #5233ff;
border-radius: 4px;
font-size: 25px;
z-index: 1;
}
.button-overlay:hover {
background-color: #5233ff;
border-color: #ff5500;
color:aqua;
}

View File

@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-ticket-detailed" viewBox="0 0 16 16">
<path d="M4 5.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5m0 5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5M5 7a1 1 0 0 0 0 2h6a1 1 0 1 0 0-2z"/>
<path d="M0 4.5A1.5 1.5 0 0 1 1.5 3h13A1.5 1.5 0 0 1 16 4.5V6a.5.5 0 0 1-.5.5 1.5 1.5 0 0 0 0 3 .5.5 0 0 1 .5.5v1.5a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 0 11.5V10a.5.5 0 0 1 .5-.5 1.5 1.5 0 1 0 0-3A.5.5 0 0 1 0 6zM1.5 4a.5.5 0 0 0-.5.5v1.05a2.5 2.5 0 0 1 0 4.9v1.05a.5.5 0 0 0 .5.5h13a.5.5 0 0 0 .5-.5v-1.05a2.5 2.5 0 0 1 0-4.9V4.5a.5.5 0 0 0-.5-.5z"/>
</svg>

After

Width:  |  Height:  |  Size: 666 B

View File

@ -0,0 +1,83 @@
<!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.iventName}]] ([[${#numbers.formatDecimal(cartItem.iventPrice, 1, 2)}]]) *
[[${cartItem.quantity}]]
=
[[${#numbers.formatDecimal(cartItem.iventPrice * cartItem.quantity, 1, 2)}]]
</div>
<div class="col-3 d-flex justify-content-end">
<div class="col-3 d-flex justify-content-end">
<form action="#"
th:action="@{/cart/toggle-quantity?iventId={iventId}&isIncrease=true(iventId=${cartItem.iventId})}"
method="post">
<button type="submit" class="btn btn-primary">
<i class="bi bi-plus-lg"></i>
</button>
</form>
<form action="#"
th:action="@{/cart/toggle-quantity?iventId={iventId}&isIncrease=false(iventId=${cartItem.iventId})}"
method="post">
<button class="btn btn-danger">
<i class="bi bi-dash-lg"></i>
</button>
</form>
</div>
</div>
</div>
</div>
<div class=" mb-2 col-12 col-md-8 col-lg-6 d-flex justify-content-end">
<!-- suda total -->
</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="${cartItem}" method="post">
<input type="text" th:value="*{id}" id="id" class="visually-hidden">
<div class="mb-2">
<label for="iventId" class="form-label">Товары</label>
<select th:field="*{iventId}" id="iventId" class="form-select">
<option selected value="">Укажите товар</option>
<option th:each="ivent : ${ivents}" th:value="${ivent.id}">[[${ivent.name}]]</option>
</select>
<div th:if="${#fields.hasErrors('iventId')}" th:errors="*{iventId}" class="invalid-feedback"></div>
</div>
<div class="mb-2">
<label for="quantity" class="form-label">Количество</label>
<input type="number" th:field="*{quantity}" id="quantity" class="form-control" value="0" step="1">
<div th:if="${#fields.hasErrors('quantity')}" th:errors="*{quantity}" class="invalid-feedback"></div>
</div>
<button type="submit" class="btn btn-primary">Добавить в корзину</button>
</form>
</div>-->
</main>
</body>
</html>
</html>

View File

@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Каталог</title>
</head>
<body>
<main layout:fragment="content">
<div id="video-container">
<div class="video-foreground">
<iframe src="https://www.youtube.com/embed/XEEasR7hVhA?autoplay=1&controls=0&loop=1&showinfo=0&mute=1" allowfullscreen title="iframe_video"></iframe>
</div>
<th:block th:switch="${items.size()}">
<h2 th:case="0">Данные отсутствуют</h2>
<th:block th:case="*">
<div class="mt-4" style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px">
<div class="card" th:each="ivent : ${items}">
<div class="card-body">
<img src="${ivent.image}" alt="s">
<h5 class="card-title mb-0" th:text="${ivent.name}"></h5>
<p class="card-text"><small class="text-body-secondary" th:text="${ivent.typeName}"></small></p>
<p class="card-text"><small class="text-body-secondary" th:text="${ivent.placeName}"></small></p>
<p class="card-text"><small class="text-body-secondary">[[${ivent.price}]] руб.</small></p>
<form
th:action="@{/buy?id={id}&isCartIvent={isCartIvent}(id=${ivent.id},isCartIvent=${ivent.isCartIvent})}"
method="post">
<button type="submit" class="btn btn-primary"
th:text="'Добавить в корзину'"></button>
</form>
</div>
</div>
</div>
</div>
<th:block th:replace="~{ pagination :: pagination (
url='',
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</th:block>
</th:block>
</main>
</body>
</html>

View File

@ -0,0 +1,119 @@
<!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">TicketsBook</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 href="https://fonts.cdnfonts.com/css/correction-tape" rel="stylesheet">
<link rel="stylesheet" href="/css/style.css" />
</head>
<body class="h-100 d-flex flex-column">
<div id="menu-wrapper">
<div id="menu">
<ul class=" me-auto link" th:with="activeLink=${#objects.nullSafe(servletPath, '')}">
<li>
<a class="nav-link" href="/catalog"
th:classappend="${activeLink.startsWith('/catalog') ? 'active' : ''}">
◌ Каталог
</a>
</li>
<li>
<a class="nav-link" href="/orders"
th:classappend="${activeLink.startsWith('/orders') ? 'active' : ''}">
◌ Личный кабинет
</a>
</li>
<th:block sec:authorize="hasRole('ADMIN')">
<li>
<a class="nav-link" href="/admin/user"
th:classappend="${activeLink.startsWith('/admin/user') ? 'active' : ''}">
◌ Пользователи
</a>
</li>
<li>
<a class="nav-link" href="/admin/type"
th:classappend="${activeLink.startsWith('/admin/type') ? 'active' : ''}">
◌ Типы
</a>
</li>
<li>
<a class="nav-link" href="/admin/place"
th:classappend="${activeLink.startsWith('/admin/place') ? 'active' : ''}">
◌ Площадки
</a>
</li>
<li>
<a class="nav-link" href="/admin/ivent"
th:classappend="${activeLink.startsWith('/admin/ivent') ? 'active' : ''}">
◌ Мероприятия
</a>
</li>
<li>
<a class="nav-link" href="/h2-console/" target="_blank">◌ Консоль H2</a>
</li>
</th:block>
</ul>
</div>
</div>
<nav class="navbar navbar-expand-md navbar-dark" data-bs-theme="dark">
<div class="container-fluid">
<a class="navbar-brand" id="toggle-menu">
<i class="bi bi-ticket-detailed" onclick="toggleMenu()"></i>
</a>
<a class="navbar-brand" id="toggle-menu" href="/">
TicketsBook
</a>
<th:block sec:authorize="isAuthenticated()" th:with="userName=${#authentication.name}">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#main-navbar"
aria-controls="main-navbar" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="main-navbar">
<ul class="navbar-nav me-auto link" th:with="activeLink=${#objects.nullSafe(servletPath, '')}">
<a class="nav-link" href="/catalog"
th:classappend="${activeLink.startsWith('/catalog') ? 'active' : ''}">
Каталог
</a>
<a class="nav-link" href="/orders"
th:classappend="${activeLink.startsWith('/orders') ? 'active' : ''}">
Личный кабинет
</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-cart-check"></i>
[[${#numbers.formatDecimal(totalCart, 1, 2)}]] &#8381;
</a>
</ul>
</div>
</th:block>
</div>
</nav>
<main class="container-fluid" layout:fragment="content">
</main>
<footer class="footer mt-auto d-flex flex-shrink-0 justify-content-center align-items-center">
Автор, [[${#dates.year(#dates.createNow())}]]
</footer>
<script>
function toggleMenu() {
var menuWrapper = document.getElementById("menu-wrapper");
menuWrapper.classList.toggle("open");
}
</script>
</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,45 @@
<!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="row">
<div class="center">
<div id="video-container">
<div class="video-foreground">
<iframe src="https://www.youtube.com/embed/UCCyoocDxBA?autoplay=1&controls=0&loop=1&showinfo=0&mute=1" allowfullscreen title="iframe_video"></iframe>
</div>
<div class="text-button-overlay">
<div class="text-overlay">
TicketsBook
</div>
<div class="underText-overlay">
Сайт для покупки билетов
</div>
<div>
<a class="btn button-overlay" href="/catalog">Начать покупку -></a>
</div>
</div>
</div>
</div>
</div>
</main>
<script>
document.addEventListener('DOMContentLoaded', function() {
var videos = [
'https://www.youtube.com/embed/f0pdwd0miqs?autoplay=1&controls=0&loop=1&showinfo=0&mute=1',
'https://www.youtube.com/embed/ijxk-fgcg7c?autoplay=1&controls=0&loop=1&showinfo=0&mute=1',
'https://www.youtube.com/embed/UCCyoocDxBA?autoplay=1&controls=0&loop=1&showinfo=0&mute=1'
];
const randomSource = videos[Math.floor(Math.random() * videos.length)];
document.getElementById('w').src = randomSource;
});
</script>
</body>
</html>

View File

@ -0,0 +1,87 @@
<!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="row">
<main class="center">
<div id="video-container">
<div class="video-foreground">
<iframe src="https://www.youtube.com/embed/f0pdwd0miqs?autoplay=1&controls=0&loop=1&showinfo=0&mute=1" allowfullscreen title="iframe_video"></iframe>
</div>
<div class="text-button-overlay">
<div class="container mt-3">
<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="d-flex justify-content-center">
<button class="btn btn-primary" type="submit" style="margin-right: 10px;">Войти</button>
<a class="btn btn-secondary" href="/signup">Регистрация</a>
</div>
</form>
</div>
</div>
/div>
</main>
</div>
</main>
<script>
function getRandomVideo() {
var videos = [
"https://www.youtube.com/embed/f0pdwd0miqs?autoplay=1&controls=0&loop=1&showinfo=0&mute=1",
"https://www.youtube.com/embed/f0pdwd0miqs?autoplay=1&controls=0&loop=1&showinfo=0&mute=1",
"https://www.youtube.com/embed/f0pdwd0miqs?autoplay=1&controls=0&loop=1&showinfo=0&mute=1",
"https://www.youtube.com/embed/f0pdwd0miqs?autoplay=1&controls=0&loop=1&showinfo=0&mute=1"
];
var randomIndex = Math.floor(Math.random() * videos.length);
var randomVideo = videos[randomIndex];
var videoElement = document.getElementById("video");
videoElement.src = randomVideo;
}
function setOverlayPosition() {
var videoElement = document.getElementById("video");
var textOverlayElement = document.getElementById("text-overlay");
textOverlayElement.style.top = (videoElement.offsetHeight / 2 - textOverlayElement.offsetHeight / 2) + "px";
textOverlayElement.style.left = (videoElement.offsetWidth / 2 - textOverlayElement.offsetWidth / 2) + "px";
}
window.addEventListener('DOMContentLoaded', (event) => {
getRandomVideo();
setOverlayPosition();
});
window.addEventListener('resize', (event) => {
setOverlayPosition();
});
</script>
</body>
</html>
</html>

View File

@ -0,0 +1,38 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" layout:decorate="~{default}">
<body>
<main layout:fragment="content">
<button class="btn btn-link button-link" onclick="history.back()">Назад</button>
<h1>Заказ №[[${order.id}]], [[${#dates.format(order.date, 'HH:mm dd-MM-yyyy')}]]</h1>
<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-auto">Название товара</th>
<th scope="col" class="w-10">Цена</th>
<th scope="col" class="w-10">Количество</th>
</tr>
</thead>
<tbody>
<tr th:each="item : ${items}">
<td th:text="${item.iventName}"></td>
<td th:text="${#numbers.formatDecimal(item.iventPrice, 1, 2)}"></td>
<td th:text="${item.quantity}"></td>
</tr>
</tbody>
</table>
</th:block>
<th:block th:replace="~{ pagination :: pagination (
url='',
totalPages=${totalPages},
currentPage=${currentPage}) }" />
<h2>Итого: [[${#numbers.formatDecimal(order.total, 1, 2)}]] руб</h2>
</th:block>
</main>
</body>
</html>

View File

@ -0,0 +1,46 @@
<!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="*">
<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>
</tr>
</thead>
<tbody>
<tr th:each="order : ${items}">
<th scope="row" th:text="${order.id}"></th>
<td th:text="${#dates.format(order.date, 'HH:mm dd-MM-yyyy')}"></td>
<td>
<form th:action="@{/orders/details/{id}(id=${order.id})}" method="get">
<button type="submit" class="btn btn-link button-link">Детали</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>
</main>
</body>
</html>

View File

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

View File

@ -0,0 +1,41 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Редакторовать продукт</title>
</head>
<body>
<main layout:fragment="content">
<form action="#" th:action="@{/admin/ivent/edit/{id}(id=${ivent.id})}" th:object="${ivent}" 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">
<label for="price" class="form-label">Цена</label>
<input type="number" th:field="*{price}" id="price" class="form-control" min="1" step="1">
<div th:if="${#fields.hasErrors('price')}" th:errors="*{price}" class="invalid-feedback"></div>
</div>
<div class="mb-3">
<label for="typeId" class="form-label">Тип</label>
<select th:field="*{typeId}" id="typeId" class="form-select">
<option selected value="">Укажите категорию</option>
<option th:each="type : ${types}" th:value="${type.id}">[[${type.name}]]</option>
</select>
<div th:if="${#fields.hasErrors('typeId')}" th:errors="*{typeId}" 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/ivent">Отмена</a>
</div>
</form>
</main>
</body>
</html>

View File

@ -0,0 +1,59 @@
<!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/ivent/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-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="ivent : ${items}">
<th scope="row" th:text="${ivent.id}"></th>
<td th:text="${ivent.name}"></td>
<td th:text="${ivent.typeName}"></td>
<td th:text="${ivent.price}"></td>
<td>
<form th:action="@{/admin/ivent/edit/{id}(id=${ivent.id})}" method="get">
<button type="submit" class="btn btn-link button-link">Редактировать</button>
</form>
</td>
<td>
<form th:action="@{/admin/ivent/delete/{id}(id=${ivent.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>
<th:block th:replace="~{ pagination :: pagination (
url=${'admin/ivent'},
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</th:block>
</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">
<div class="video-foreground">
<iframe src="https://www.youtube.com/embed/RRKJiM9Njr8?autoplay=1&controls=0&loop=1&showinfo=0&mute=1" allowfullscreen title="iframe_video"></iframe>
</div>
<form action="#" th:action="@{/signup}" th:object="${user}" method="post">
<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">
<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>
</html>

View File

@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Редакторовать тип</title>
</head>
<body>
<main layout:fragment="content">
<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,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/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>
<th:block th:replace="~{ pagination :: pagination (
url=${'admin/type'},
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</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/create/(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="password" class="form-label">Пароль</label>
<input type="text" 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 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,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 visually-hidden">
<label for="password" class="form-label">Пароль</label>
<input type="text" 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 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,56 @@
<!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/user/create/" 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="user : ${items}">
<th scope="row" th:text="${user.id}"></th>
<td th:text="${user.login}"></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

@ -25,9 +25,9 @@ class UserServiceTests {
void createData() {
removeData();
user = userService.create(new UserEntity("Admin", "admin@gmail.com", "admin", "admin"));
userService.create(new UserEntity("Milana", "milana@gmail.com", "milana", "user"));
userService.create(new UserEntity("TestUser", "user@gmail.com", "test", "user"));
user = userService.create(new UserEntity("Admin", "admin@gmail.com", "admin"));
userService.create(new UserEntity("Milana", "milana@gmail.com", "milana"));
userService.create(new UserEntity("TestUser", "user@gmail.com", "test"));
}
@AfterEach
@ -49,13 +49,13 @@ class UserServiceTests {
@Test
void createNotUniqueTest() {
final UserEntity nonUniqueUser = new UserEntity("Milana", "milana@gmail.com", "milana", "user");
final UserEntity nonUniqueUser = new UserEntity("Milana", "milana@gmail.com", "milana");
Assertions.assertThrows(IllegalArgumentException.class, () -> userService.create(nonUniqueUser));
}
@Test
void createNullableTest() {
final UserEntity nullableUser = new UserEntity(null, "email@gamil.com", "pass", "admin");
final UserEntity nullableUser = new UserEntity(null, "email@gamil.com", "pass");
Assertions.assertThrows(DataIntegrityViolationException.class, () -> userService.create(nullableUser));
}
@ -65,7 +65,7 @@ class UserServiceTests {
final String test = "TEST";
final String oldLogin = user.getHandle();
final UserEntity newEntity = userService.update(user.getId(),
new UserEntity(test, "admin@gmail.com", "admin", "admin"));
new UserEntity(test, "admin@gmail.com", "admin"));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(newEntity, userService.get(user.getId()));
Assertions.assertEquals(test, newEntity.getHandle());
@ -78,7 +78,7 @@ class UserServiceTests {
Assertions.assertEquals(2, userService.getAll().size());
final UserEntity newEntity = userService
.create(new UserEntity("Admin", "admin@gmail.com", "admin", "admin"));
.create(new UserEntity("Admin", "admin@gmail.com", "admin"));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertNotEquals(user.getId(), newEntity.getId());
}