diff --git a/front/src/pages/Orders.jsx b/front/src/pages/Orders.jsx index e83d407..f831f8a 100644 --- a/front/src/pages/Orders.jsx +++ b/front/src/pages/Orders.jsx @@ -11,15 +11,15 @@ export default function Orders() { // хук для запоминания индекса элемента, вызвавшего модальное окно const [currEditItem, setCurrEditItem] = useState(0); // для выпадающих значений - const [customerName, setCustomerName] = useState(''); - const [customer, setCustomer] = useState([]); + const [userName, setUserName] = useState(''); + const [user, setUser] = useState([]); const [sessionName, setSessionName] = useState(''); const [count, setCount] = useState(1); const [session, setSession] = useState([]); const [orderSessions, setOrderSessions] = useState([]); useEffect(() => { - getAll('customer').then((data) => setCustomer(data)) + getAll('user').then((data) => setUser(data)) getAll('session').then((data) => setSession(data)) getAll('order').then((data) => setUsers(data)) }, []) @@ -33,12 +33,12 @@ export default function Orders() { function handleSubmit(e) { e.preventDefault(); - if (customer.length <= 0) { + if (user.length <= 0) { throw 'Form not submit' } handleSubmitCreate(e) console.log('Form submit') - setCustomer('') + setUser('') } // принимаем событие от кнопки "добавить" @@ -52,10 +52,10 @@ export default function Orders() { "Content-Type": "application/json" } }; - await fetch(`http://localhost:8080/order?customer=${customerName}`, requestParams) + await fetch(`http://localhost:8080/order?user=${userName}`, requestParams) .then((data) => { - getCustomerOrders(customerName) - getAll('customer').then((data) => setCustomer(data)) + getUserOrders(userName) + getAll('user').then((data) => setUser(data)) }) .catch(function (error) { console.error('Error:', error); @@ -127,8 +127,8 @@ export default function Orders() { }); }; - async function getCustomerOrders(id) { - Service.read(`customer/${id}`) + async function getUserOrders(id) { + Service.read(`user/${id}`) .then(function (data) { setUsers(data.orders); console.info('End'); @@ -158,12 +158,12 @@ export default function Orders() { const Content = ( <> - { + setUserName(e.target.value) + getUserOrders(e.target.value) }} > - {customer ? customer.map(elem => + {user ? user.map(elem => ) : null} @@ -176,7 +176,7 @@ export default function Orders() { # - Customer + User DateOfPurchase @@ -199,7 +199,7 @@ export default function Orders() { diff --git a/front/src/pages/Registration.jsx b/front/src/pages/Registration.jsx index 543c1f3..243f983 100644 --- a/front/src/pages/Registration.jsx +++ b/front/src/pages/Registration.jsx @@ -22,7 +22,7 @@ export default function Registration() { }, []) async function getAll() { - const requestUrl = "http://localhost:8080/customer" + const requestUrl = "http://localhost:8080/user" const response = await fetch(requestUrl) const temp = await response.json() setUsers(temp) @@ -51,7 +51,7 @@ export default function Registration() { "Content-Type": "application/json" } }; - await fetch(`http://localhost:8080/customer?login=${login}&password=${password}`, requestParams) + await fetch(`http://localhost:8080/user?login=${login}&password=${password}`, requestParams) .then(() => { getAll() }) @@ -60,7 +60,7 @@ export default function Registration() { function handleEdit(id) { console.info(`Start edit script`); - Service.read(`customer/${id}`) + Service.read(`user/${id}`) .then(function (data) { setLoginEdit(data.login); setPasswordEdit(data.password); @@ -79,7 +79,7 @@ export default function Registration() { "Content-Type": "application/json" } }; - const requestUrl = `http://localhost:8080/customer/${id}?login=${loginEdit}&password=${passwordEdit}` + const requestUrl = `http://localhost:8080/user/${id}?login=${loginEdit}&password=${passwordEdit}` const response = await fetch(requestUrl, requestParams) const temp = await response.json() .then((data) => { @@ -101,7 +101,7 @@ export default function Registration() { function handleDelete(id) { console.info('Try to remove item'); - Service.delete(`customer/${id}`) + Service.delete(`user/${id}`) .then(() => { setUsers(users.filter(elem => elem.id !== id)) console.log("Removed") diff --git a/front/src/pages/Sessions.jsx b/front/src/pages/Sessions.jsx index 20986cc..ab9143a 100644 --- a/front/src/pages/Sessions.jsx +++ b/front/src/pages/Sessions.jsx @@ -7,7 +7,7 @@ import CinemaDto from './models/CinemaDto' export default function Sessions() { const [price, setPrice] = useState(1); - const [timestamp, setTimestamp] = useState(new Date()); + const [dateTime, setTimestamp] = useState(new Date()); const [maxCount, setMaxCount] = useState(1); const [priceEdit, setPriceEdit] = useState(''); const [users, setUsers] = useState([]); @@ -55,7 +55,7 @@ export default function Sessions() { "Content-Type": "application/json" } }; - await fetch(`http://localhost:8080/session?price=${price}×tamp=${timestamp}&cinemaid=${cinemaName}&capacity=${maxCount}`, requestParams) + await fetch(`http://localhost:8080/session?price=${price}&dateTime=${dateTime}&cinemaid=${cinemaName}&capacity=${maxCount}`, requestParams) .then(() => { getAll('session').then((data) => setUsers(data)) getAll('cinema').then((data) => setCinema(data)) @@ -140,9 +140,9 @@ export default function Sessions() { {error && price.length <= 0 ? : null}
- setTimestamp(e.target.value)} placeholder="Введите дату" /> + setTimestamp(e.target.value)} placeholder="Введите дату" />
- {error && timestamp.length <= 0 ? : null} + {error && dateTime.length <= 0 ? : null}
diff --git a/front/src/pages/components/OrderItem.jsx b/front/src/pages/components/OrderItem.jsx index 273715a..49d8564 100644 --- a/front/src/pages/components/OrderItem.jsx +++ b/front/src/pages/components/OrderItem.jsx @@ -5,7 +5,7 @@ export default function OrderItem(props) { return ( {props.item.id} - {props.item.customer} + {props.item.user} {props.item.dateOfPurchase} diff --git a/front/src/pages/components/OrderSessionItem.jsx b/front/src/pages/components/OrderSessionItem.jsx index a283d93..27e43bf 100644 --- a/front/src/pages/components/OrderSessionItem.jsx +++ b/front/src/pages/components/OrderSessionItem.jsx @@ -8,7 +8,7 @@ export default function OrderSessionItem(props) { {props.item.session.id} {props.item.session.price} {props.item.session.cinema.name} - {new Date(props.item.session.timestamp).toLocaleString('RU-ru')} + {new Date(props.item.session.dateTime).toLocaleString('RU-ru')} {props.item.count} diff --git a/front/src/pages/components/SessionItem.jsx b/front/src/pages/components/SessionItem.jsx index 4d865da..d1d72a1 100644 --- a/front/src/pages/components/SessionItem.jsx +++ b/front/src/pages/components/SessionItem.jsx @@ -2,7 +2,7 @@ import React, { useEffect, useState } from "react" import MyButton from './MyButton' export default function SessionItem(props) { - const date = new Date(props.item.timestamp).toLocaleString('RU-ru') + const date = new Date(props.item.dateTime).toLocaleString('RU-ru') return ( diff --git a/front/src/pages/models/CustomerDto.js b/front/src/pages/models/CustomerDto.js index 61ff30e..e3b3269 100644 --- a/front/src/pages/models/CustomerDto.js +++ b/front/src/pages/models/CustomerDto.js @@ -1,10 +1,10 @@ -export default class CustomerDto { +export default class UserDto { constructor(login, password, id) { this.login = login; this.password = password; this.id = parseInt(id); } static createFrom(item) { - return new CustomerDto(item.login, item.password, item.id); + return new UserDto(item.login, item.password, item.id); } } \ No newline at end of file diff --git a/src/main/java/com/labwork1/app/configuration/SecurityConfiguration.java b/src/main/java/com/labwork1/app/configuration/SecurityConfiguration.java index 5e1d3d3..e412087 100644 --- a/src/main/java/com/labwork1/app/configuration/SecurityConfiguration.java +++ b/src/main/java/com/labwork1/app/configuration/SecurityConfiguration.java @@ -2,7 +2,7 @@ package com.labwork1.app.configuration; import com.labwork1.app.student.controller.UserSignupMvcController; import com.labwork1.app.student.model.UserRole; -import com.labwork1.app.student.service.CustomerService; +import com.labwork1.app.student.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; @@ -23,9 +23,9 @@ import org.springframework.security.web.SecurityFilterChain; public class SecurityConfiguration { private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class); private static final String LOGIN_URL = "/login"; - private final CustomerService userService; + private final UserService userService; - public SecurityConfiguration(CustomerService userService) { + public SecurityConfiguration(UserService userService) { this.userService = userService; createAdminOnStartup(); } diff --git a/src/main/java/com/labwork1/app/student/controller/CustomerController.java b/src/main/java/com/labwork1/app/student/controller/CustomerController.java deleted file mode 100644 index 6409a72..0000000 --- a/src/main/java/com/labwork1/app/student/controller/CustomerController.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.labwork1.app.student.controller; - -import com.labwork1.app.configuration.WebConfiguration; -import com.labwork1.app.student.model.UserSignupDto; -import com.labwork1.app.student.service.CustomerService; -import jakarta.validation.Valid; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -@RestController -@RequestMapping(WebConfiguration.REST_API + "/customer") -public class CustomerController { - private final CustomerService customerService; - - public CustomerController(CustomerService customerService) { - this.customerService = customerService; - } - - @GetMapping("/{id}") - public CustomerDto getCustomer(@PathVariable Long id) { - return new CustomerDto(customerService.findCustomer(id)); - } - - @GetMapping - public List getCustomers() { - return customerService.findAllCustomers().stream() - .map(CustomerDto::new) - .toList(); - } - - @PostMapping - public CustomerDto createCustomer(@RequestBody @Valid UserSignupDto userSignupDto) { - return new CustomerDto(customerService.addCustomer(userSignupDto)); - } - - @PutMapping("/{id}") - public CustomerDto updateCustomer(@PathVariable Long id, - @RequestParam("login") String login, - @RequestParam("password") String password) { - return new CustomerDto(customerService.updateCustomer(id, login, password)); - } - - @DeleteMapping("/{id}") - public CustomerDto deleteCustomer(@PathVariable Long id) { - return new CustomerDto(customerService.deleteCustomer(id)); - } -} diff --git a/src/main/java/com/labwork1/app/student/controller/CustomerDto.java b/src/main/java/com/labwork1/app/student/controller/CustomerDto.java deleted file mode 100644 index 5af72c2..0000000 --- a/src/main/java/com/labwork1/app/student/controller/CustomerDto.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.labwork1.app.student.controller; - -import com.labwork1.app.student.model.Customer; -import com.labwork1.app.student.model.Order; -import com.labwork1.app.student.model.OrderSession; -import com.labwork1.app.student.model.UserRole; - -import java.util.ArrayList; -import java.util.List; - -public class CustomerDto { - private long id; - private String login; - private String password; - private List orders; - private UserRole role; - - public CustomerDto() { - } - - public CustomerDto(Customer customer) { - this.id = customer.getId(); - this.login = customer.getLogin(); - this.password = customer.getPassword(); - this.orders = new ArrayList<>(); - this.role = customer.getRole(); - if (customer.getOrders() != null) { - orders = customer.getOrders().stream() - .map(OrderDto::new).toList(); - } - } - - public void setId(long id) { - this.id = id; - } - - public void setLogin(String login) { - this.login = login; - } - - public void setPassword(String password) { - this.password = password; - } - - public void setOrders(List orders) { - this.orders = orders; - } - - public long getId() { - return id; - } - - public String getLogin() { - return login; - } - - public String getPassword() { - return password; - } - - public List getOrders() { - return orders; - } - - public UserRole getRole() { - return role; - } -} diff --git a/src/main/java/com/labwork1/app/student/controller/CustomerMvcController.java b/src/main/java/com/labwork1/app/student/controller/CustomerMvcController.java deleted file mode 100644 index 9b4fa5e..0000000 --- a/src/main/java/com/labwork1/app/student/controller/CustomerMvcController.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.labwork1.app.student.controller; - -import com.labwork1.app.student.model.UserRole; -import com.labwork1.app.student.service.CustomerService; -import jakarta.validation.Valid; -import org.springframework.data.domain.Page; -import org.springframework.security.access.annotation.Secured; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.*; - -import java.util.List; -import java.util.stream.IntStream; - -@Controller -@RequestMapping("/customer") -@Secured({UserRole.AsString.ADMIN}) -public class CustomerMvcController { - private final CustomerService customerService; - - public CustomerMvcController(CustomerService customerService) { - this.customerService = customerService; - } - - @GetMapping - public String getCustomers(@RequestParam(defaultValue = "1") int page, - @RequestParam(defaultValue = "5") int size, - Model model) { - final Page users = customerService.findAllPages(page, size) - .map(CustomerDto::new); - model.addAttribute("customers", users); - final int totalPages = users.getTotalPages(); - final List pageNumbers = IntStream.rangeClosed(1, totalPages) - .boxed() - .toList(); - model.addAttribute("pages", pageNumbers); - model.addAttribute("totalPages", totalPages); - return "customer"; - } - - @GetMapping(value = {"/edit", "/edit/{id}"}) - public String editCustomer(@PathVariable(required = false) Long id, - Model model) { - if (id == null || id <= 0) { - model.addAttribute("customerDto", new CustomerDto()); - } else { - model.addAttribute("customerId", id); - model.addAttribute("customerDto", new CustomerDto(customerService.findCustomer(id))); - } - return "customer-edit"; - } - - @PostMapping("/delete/{id}") - public String deleteCustomer(@PathVariable Long id) { - customerService.deleteCustomer(id); - return "redirect:/customer"; - } -} diff --git a/src/main/java/com/labwork1/app/student/controller/OrderController.java b/src/main/java/com/labwork1/app/student/controller/OrderController.java index 808ed8b..756de90 100644 --- a/src/main/java/com/labwork1/app/student/controller/OrderController.java +++ b/src/main/java/com/labwork1/app/student/controller/OrderController.java @@ -28,8 +28,8 @@ public class OrderController { } @PostMapping - public OrderDto createOrder(@RequestParam("customer") Long customer) { - return new OrderDto(orderService.addOrder(customer)); + public OrderDto createOrder(@RequestParam("user") Long user) { + return new OrderDto(orderService.addOrder(user)); } @PutMapping("/{id}") diff --git a/src/main/java/com/labwork1/app/student/controller/OrderDto.java b/src/main/java/com/labwork1/app/student/controller/OrderDto.java index 7ae4e42..20accf4 100644 --- a/src/main/java/com/labwork1/app/student/controller/OrderDto.java +++ b/src/main/java/com/labwork1/app/student/controller/OrderDto.java @@ -1,6 +1,6 @@ package com.labwork1.app.student.controller; -import com.labwork1.app.student.model.Customer; +import com.labwork1.app.student.model.User; import com.labwork1.app.student.model.Order; import com.labwork1.app.student.model.OrderSession; @@ -9,9 +9,8 @@ import java.util.List; public class OrderDto { private long id; - private Date dateOfPurchase; - private Long customerId; - private String customer; + private Long userId; + private String user; private List sessions; public OrderDto() { @@ -19,34 +18,29 @@ public class OrderDto { public OrderDto(Order order) { this.id = order.getId(); - this.dateOfPurchase = order.getDateOfPurchase(); - this.customerId = order.getCustomer().getId(); - this.customer = order.getCustomer().getLogin(); - if (order.getSessions() != null && order.getSessions().size() > 0) + this.userId = order.getUser().getId(); + this.user = order.getUser().getLogin(); + if (order.getSessions() != null && !order.getSessions().isEmpty()) this.sessions = order.getSessions() .stream() .map(x -> new OrderSessionDto(new SessionDto(x.getSession()), x.getId().getOrderId(), x.getCount())).toList(); } - public Long getCustomerId() { - return customerId; + public Long getUserId() { + return userId; } - public void setCustomerId(Long customerId) { - this.customerId = customerId; + public void setUserId(Long userId) { + this.userId = userId; } public void setId(long id) { this.id = id; } - public void setDateOfPurchase(Date dateOfPurchase) { - this.dateOfPurchase = dateOfPurchase; - } - - public void setCustomer(String customer) { - this.customer = customer; + public void setUser(String user) { + this.user = user; } public void setSessions(List sessions) { @@ -57,12 +51,8 @@ public class OrderDto { return id; } - public Date getDateOfPurchase() { - return dateOfPurchase; - } - - public String getCustomer() { - return customer; + public String getUser() { + return user; } public List getSessions() { diff --git a/src/main/java/com/labwork1/app/student/controller/OrderMvcController.java b/src/main/java/com/labwork1/app/student/controller/OrderMvcController.java index ca34d1a..dbc2a08 100644 --- a/src/main/java/com/labwork1/app/student/controller/OrderMvcController.java +++ b/src/main/java/com/labwork1/app/student/controller/OrderMvcController.java @@ -1,10 +1,10 @@ package com.labwork1.app.student.controller; -import com.labwork1.app.student.model.Customer; +import com.labwork1.app.student.model.User; import com.labwork1.app.student.model.Order; import com.labwork1.app.student.model.SessionExtension; import com.labwork1.app.student.model.UserRole; -import com.labwork1.app.student.service.CustomerService; +import com.labwork1.app.student.service.UserService; import com.labwork1.app.student.service.OrderService; import com.labwork1.app.student.service.SessionService; import jakarta.validation.Valid; @@ -25,24 +25,24 @@ import java.util.Objects; public class OrderMvcController { private final OrderService orderService; private final SessionService sessionService; - private final CustomerService customerService; + private final UserService userService; - public OrderMvcController(OrderService orderService, SessionService sessionService, CustomerService customerService) { + public OrderMvcController(OrderService orderService, SessionService sessionService, UserService userService) { this.orderService = orderService; this.sessionService = sessionService; - this.customerService = customerService; + this.userService = userService; } @GetMapping public String getOrders(Model model, Principal principal) { - Customer customer = customerService.findByLogin(principal.getName()); - if (customer.getRole() == UserRole.USER) + User user = userService.findByLogin(principal.getName()); + if (user.getRole() == UserRole.USER) model.addAttribute("orders", orderService.findAllOrders().stream() .map(OrderDto::new) - .filter(orderDto -> Objects.equals(orderDto.getCustomerId(), - customer.getId())) + .filter(orderDto -> Objects.equals(orderDto.getUserId(), + user.getId())) .toList()); else model.addAttribute("orders", @@ -62,8 +62,8 @@ public class OrderMvcController { return "order-edit"; } else { Order order = orderService.findOrder(id); - Customer customer = customerService.findByLogin(principal.getName()); - if (!Objects.equals(order.getCustomer().getId(), customer.getId()) && customer.getRole() == UserRole.USER) + User user = userService.findByLogin(principal.getName()); + if (!Objects.equals(order.getUser().getId(), user.getId()) && user.getRole() == UserRole.USER) return "redirect:/order"; List temp = order.getSessions() .stream().map(x -> new OrderSessionDto(new SessionDto(x.getSession()), @@ -88,12 +88,12 @@ public class OrderMvcController { BindingResult bindingResult, Model model, Principal principal) { - Long customerId = customerService.findByLogin(principal.getName()).getId(); + Long userId = userService.findByLogin(principal.getName()).getId(); if (bindingResult.hasErrors()) { model.addAttribute("errors", bindingResult.getAllErrors()); return "order-edit"; } - orderService.addOrder(customerId); + orderService.addOrder(userId); return "redirect:/order"; } @@ -104,8 +104,8 @@ public class OrderMvcController { Model model, Principal principal) { Order order = orderService.findOrder(id); - Customer customer = customerService.findByLogin(principal.getName()); - if (!Objects.equals(order.getCustomer().getId(), customer.getId()) && customer.getRole() == UserRole.USER) + User user = userService.findByLogin(principal.getName()); + if (!Objects.equals(order.getUser().getId(), user.getId()) && user.getRole() == UserRole.USER) return "/order"; if (count == null) orderService.deleteSessionInOrder(id, session, Integer.MAX_VALUE); @@ -118,8 +118,8 @@ public class OrderMvcController { public String deleteOrder(@PathVariable Long id, Principal principal) { Order order = orderService.findOrder(id); - Customer customer = customerService.findByLogin(principal.getName()); - if (!Objects.equals(order.getCustomer().getId(), customer.getId()) && customer.getRole() == UserRole.USER) + User user = userService.findByLogin(principal.getName()); + if (!Objects.equals(order.getUser().getId(), user.getId()) && user.getRole() == UserRole.USER) return "redirect:/order"; orderService.deleteOrder(id); return "redirect:/order"; diff --git a/src/main/java/com/labwork1/app/student/controller/SessionController.java b/src/main/java/com/labwork1/app/student/controller/SessionController.java index 1f691f9..c5dc8e1 100644 --- a/src/main/java/com/labwork1/app/student/controller/SessionController.java +++ b/src/main/java/com/labwork1/app/student/controller/SessionController.java @@ -4,9 +4,11 @@ import com.labwork1.app.configuration.WebConfiguration; import com.labwork1.app.student.service.SessionService; import org.springframework.web.bind.annotation.*; +import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; +import java.time.ZoneId; import java.util.Date; import java.util.List; @@ -33,15 +35,16 @@ public class SessionController { @PostMapping public SessionDto createSession(@RequestParam("price") String price, - @RequestParam("timestamp") String timestamp, - @RequestParam("cinemaid") Long cinemaId, + @RequestParam("dateTime") String dateTime, + @RequestParam("cinemaId") Long cinemaId, @RequestParam("capacity") Integer capacity) throws ParseException { - SimpleDateFormat format = new SimpleDateFormat(); - format.applyPattern("yyyy-MM-dd-HH:mm"); - Date docDate = format.parse(timestamp.replace('T', '-')); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:ss"); + Date docDate = format.parse(dateTime.replace('T', '-')); + LocalDateTime localDateTime = LocalDateTime.ofInstant(docDate.toInstant(), ZoneId.systemDefault()); + return new SessionDto(sessionService.findSession( sessionService.addSession(Double.parseDouble(price), - LocalDateTime.now(), cinemaId, capacity).getId())); + localDateTime, cinemaId, capacity).getId())); } @PutMapping("/{id}") @@ -55,5 +58,4 @@ public class SessionController { public SessionDto deleteSession(@PathVariable Long id) { return new SessionDto(sessionService.deleteSession(id)); } - } diff --git a/src/main/java/com/labwork1/app/student/controller/SessionMvcController.java b/src/main/java/com/labwork1/app/student/controller/SessionMvcController.java index 8fae836..45d7f93 100644 --- a/src/main/java/com/labwork1/app/student/controller/SessionMvcController.java +++ b/src/main/java/com/labwork1/app/student/controller/SessionMvcController.java @@ -67,11 +67,11 @@ public class SessionMvcController { @PostMapping(value = "/") @Secured({UserRole.AsString.ADMIN}) public String saveSession(@RequestParam("price") String price, - @RequestParam("timestamp") LocalDateTime timestamp, - @RequestParam("cinemaid") Long cinemaId, + @RequestParam("dateTime") LocalDateTime dateTime, + @RequestParam("cinemaId") Long cinemaId, @RequestParam("maxCount") Integer capacity, Model model) { - sessionService.addSession(Double.parseDouble(price), timestamp, + sessionService.addSession(Double.parseDouble(price), dateTime, cinemaId, capacity); return "redirect:/session"; } diff --git a/src/main/java/com/labwork1/app/student/controller/UserController.java b/src/main/java/com/labwork1/app/student/controller/UserController.java new file mode 100644 index 0000000..be468c1 --- /dev/null +++ b/src/main/java/com/labwork1/app/student/controller/UserController.java @@ -0,0 +1,59 @@ +package com.labwork1.app.student.controller; + +import com.labwork1.app.configuration.WebConfiguration; +import com.labwork1.app.student.model.UserSignupDto; +import com.labwork1.app.student.service.UserService; +import jakarta.validation.Valid; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping(WebConfiguration.REST_API + "/user") +public class UserController { + private final UserService userService; + + public UserController(UserService userService) { + this.userService = userService; + } + + @GetMapping("/{id}") + public UserDto getUser(@PathVariable Long id) { + return new UserDto(userService.findUser(id)); + } + + @GetMapping + public List getUsers() { + return userService.findAllUsers().stream() + .map(UserDto::new) + .toList(); + } + + @PostMapping + public UserDto createUser(@RequestBody @Valid UserSignupDto userSignupDto) { + return new UserDto(userService.addUser(userSignupDto)); + } + + @PutMapping("/{id}") + public UserDto updateUser(@PathVariable Long id, + @RequestParam("login") String login, + @RequestParam("password") String password) { + return new UserDto(userService.updateUser(id, login, password)); + } + + @PutMapping("/{id}/cart") + public UserDto updateUserCart(@PathVariable Long id, + @RequestParam("session") Long session, + @RequestParam(value = "count", required = false) Integer count) { + if (count == null) + return new UserDto(userService.deleteSessionInCart(id, session, Integer.MAX_VALUE)); + if (count > 0) + return new UserDto(userService.addSession(id, session, count)); + return new UserDto(userService.deleteSessionInCart(id, session, -count)); + } + + @DeleteMapping("/{id}") + public UserDto deleteUser(@PathVariable Long id) { + return new UserDto(userService.deleteUser(id)); + } +} diff --git a/src/main/java/com/labwork1/app/student/controller/UserDto.java b/src/main/java/com/labwork1/app/student/controller/UserDto.java new file mode 100644 index 0000000..fdbd7a6 --- /dev/null +++ b/src/main/java/com/labwork1/app/student/controller/UserDto.java @@ -0,0 +1,53 @@ +package com.labwork1.app.student.controller; + +import com.labwork1.app.student.model.User; + +import java.util.ArrayList; +import java.util.List; + +public class UserDto { + private long id; + private String login; + private String password; + private List orders; + private List sessions; + + public UserDto() { + } + + public UserDto(User user) { + this.id = user.getId(); + this.login = user.getLogin(); + this.password = user.getPassword(); + this.orders = new ArrayList<>(); + if (user.getOrders() != null) { + orders = user.getOrders().stream() + .map(OrderDto::new).toList(); + } + if (user.getSessions() != null && user.getSessions().size() > 0) + this.sessions = user.getSessions() + .stream() + .map(x -> new UserSessionDto(new SessionDto(x.getSession()), + x.getId().getUserId(), x.getCount())).toList(); + } + + public long getId() { + return id; + } + + public String getLogin() { + return login; + } + + public String getPassword() { + return password; + } + + public List getOrders() { + return orders; + } + + public List getSessions() { + return sessions; + } +} diff --git a/src/main/java/com/labwork1/app/student/controller/UserMvcController.java b/src/main/java/com/labwork1/app/student/controller/UserMvcController.java new file mode 100644 index 0000000..9ddb3c4 --- /dev/null +++ b/src/main/java/com/labwork1/app/student/controller/UserMvcController.java @@ -0,0 +1,57 @@ +package com.labwork1.app.student.controller; + +import com.labwork1.app.student.model.UserRole; +import com.labwork1.app.student.service.UserService; +import org.springframework.data.domain.Page; +import org.springframework.security.access.annotation.Secured; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.stream.IntStream; + +@Controller +@RequestMapping("/user") +@Secured({UserRole.AsString.ADMIN}) +public class UserMvcController { + private final UserService userService; + + public UserMvcController(UserService userService) { + this.userService = userService; + } + + @GetMapping + public String getUsers(@RequestParam(defaultValue = "1") int page, + @RequestParam(defaultValue = "5") int size, + Model model) { + final Page users = userService.findAllPages(page, size) + .map(UserDto::new); + model.addAttribute("users", users); + final int totalPages = users.getTotalPages(); + final List pageNumbers = IntStream.rangeClosed(1, totalPages) + .boxed() + .toList(); + model.addAttribute("pages", pageNumbers); + model.addAttribute("totalPages", totalPages); + return "user"; + } + + @GetMapping(value = {"/edit", "/edit/{id}"}) + public String editUser(@PathVariable(required = false) Long id, + Model model) { + if (id == null || id <= 0) { + model.addAttribute("userDto", new UserDto()); + } else { + model.addAttribute("userId", id); + model.addAttribute("userDto", new UserDto(userService.findUser(id))); + } + return "user-edit"; + } + + @PostMapping("/delete/{id}") + public String deleteUser(@PathVariable Long id) { + userService.deleteUser(id); + return "redirect:/user"; + } +} diff --git a/src/main/java/com/labwork1/app/student/controller/UserSessionDto.java b/src/main/java/com/labwork1/app/student/controller/UserSessionDto.java new file mode 100644 index 0000000..96d51af --- /dev/null +++ b/src/main/java/com/labwork1/app/student/controller/UserSessionDto.java @@ -0,0 +1,28 @@ +package com.labwork1.app.student.controller; + +public class UserSessionDto { + private SessionDto session; + private Long userId; + private Integer count; + + public UserSessionDto() { + } + + public UserSessionDto(SessionDto session, Long userId, Integer count) { + this.session = session; + this.userId = userId; + this.count = count; + } + + public SessionDto getSession() { + return session; + } + + public Long getUserId() { + return userId; + } + + public Integer getCount() { + return count; + } +} diff --git a/src/main/java/com/labwork1/app/student/controller/UserSignupMvcController.java b/src/main/java/com/labwork1/app/student/controller/UserSignupMvcController.java index 1101034..5490127 100644 --- a/src/main/java/com/labwork1/app/student/controller/UserSignupMvcController.java +++ b/src/main/java/com/labwork1/app/student/controller/UserSignupMvcController.java @@ -1,8 +1,8 @@ package com.labwork1.app.student.controller; -import com.labwork1.app.student.model.Customer; +import com.labwork1.app.student.model.User; import com.labwork1.app.student.model.UserSignupDto; -import com.labwork1.app.student.service.CustomerService; +import com.labwork1.app.student.service.UserService; import jakarta.validation.Valid; import jakarta.validation.ValidationException; import org.springframework.stereotype.Controller; @@ -18,9 +18,9 @@ import org.springframework.web.bind.annotation.RequestMapping; public class UserSignupMvcController { public static final String SIGNUP_URL = "/signup"; - private final CustomerService userService; + private final UserService userService; - public UserSignupMvcController(CustomerService userService) { + public UserSignupMvcController(UserService userService) { this.userService = userService; } @@ -39,7 +39,7 @@ public class UserSignupMvcController { return "signup"; } try { - final Customer user = userService.addCustomer( + final User user = userService.addUser( userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm()); return "redirect:/login?created=" + user.getLogin(); } catch (ValidationException e) { diff --git a/src/main/java/com/labwork1/app/student/model/Order.java b/src/main/java/com/labwork1/app/student/model/Order.java index 3ed3ab4..1532b8d 100644 --- a/src/main/java/com/labwork1/app/student/model/Order.java +++ b/src/main/java/com/labwork1/app/student/model/Order.java @@ -14,12 +14,9 @@ public class Order { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - @NotNull(message = "dateOfPurchase can't be null or empty") - @Temporal(TemporalType.DATE) - private Date dateOfPurchase; @ManyToOne(fetch = FetchType.EAGER) - @JoinColumn(name = "customer_fk") - private Customer customer; + @JoinColumn(name = "user_fk") + private User user; @OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade = { CascadeType.REMOVE, @@ -31,10 +28,6 @@ public class Order { public Order() { } - public Order(Date dateOfPurchase) { - this.dateOfPurchase = dateOfPurchase; - } - public void addSession(OrderSession orderSession) { if (sessions == null) { sessions = new ArrayList<>(); @@ -65,30 +58,21 @@ public class Order { public String toString() { return "Order {" + "id=" + id + - ", date='" + dateOfPurchase.toString() + '\'' + - ", customer='" + customer.toString() + '\''; + ", user='" + user.toString() + '\''; } public Long getId() { return id; } - public Date getDateOfPurchase() { - return dateOfPurchase; + public User getUser() { + return user; } - public void setDateOfPurchase(Date dateOfPurchase) { - this.dateOfPurchase = dateOfPurchase; - } - - public Customer getCustomer() { - return customer; - } - - public void setCustomer(Customer customer) { - this.customer = customer; - if (!customer.getOrders().contains(this)) { - customer.setOrder(this); + public void setUser(User user) { + this.user = user; + if (!user.getOrders().contains(this)) { + user.setOrder(this); } } diff --git a/src/main/java/com/labwork1/app/student/model/Session.java b/src/main/java/com/labwork1/app/student/model/Session.java index 9573690..aebf1d9 100644 --- a/src/main/java/com/labwork1/app/student/model/Session.java +++ b/src/main/java/com/labwork1/app/student/model/Session.java @@ -17,13 +17,15 @@ public class Session { protected Long id; @NotNull(message = "price can't be null or empty") protected Double price; - @NotNull(message = "timestamp can't be null or empty") + @NotNull(message = "dateTime can't be null or empty") @Column @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm") - protected LocalDateTime timestamp; + protected LocalDateTime dateTime; @OneToMany(mappedBy = "session", fetch = FetchType.EAGER) private List orders; + @OneToMany(mappedBy = "session", fetch = FetchType.EAGER) + private List users; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "cinema_fk") protected Cinema cinema; @@ -38,17 +40,18 @@ public class Session { return maxCount; } - public Session(Double price, LocalDateTime timestamp, Integer maxCount) { + public Session(Double price, LocalDateTime dateTime, Integer maxCount) { this.price = price; - this.timestamp = timestamp; + this.dateTime = dateTime; this.maxCount = maxCount; } public Session(Session session) { this.id = session.getId(); this.price = session.getPrice(); - this.timestamp = session.getTimestamp(); + this.dateTime = session.getTimestamp(); this.orders = session.getOrders(); + this.users = session.getUsers(); this.cinema = session.getCinema(); this.maxCount = session.getMaxCount(); } @@ -76,6 +79,36 @@ public class Session { this.orders.remove(orderSession); } + public LocalDateTime getDateTime() { + return dateTime; + } + + public void setUsers(List users) { + this.users = users; + } + + public void setDateTime(LocalDateTime dateTime) { + this.dateTime = dateTime; + } + + public List getUsers() { + return users; + } + + public void addUser(UserSession userSession){ + if (users == null){ + users = new ArrayList<>(); + } + if (!users.contains(userSession)) { + this.users.add(userSession); + } + } + + public void removeUser(UserSession userSession){ + if (users.contains(userSession)) + this.users.remove(userSession); + } + @Override public boolean equals(Object o) { if (this == o) return true; @@ -94,7 +127,7 @@ public class Session { return "Session {" + "id=" + id + ", price='" + price + '\'' + - ", timestamp='" + timestamp.toString() + '\'' + + ", dateTime='" + dateTime.toString() + '\'' + ", maxCount='" + maxCount.toString() + '\'' + ", cinema='" + cinema.toString() + '\'' + '}'; @@ -125,11 +158,11 @@ public class Session { } public LocalDateTime getTimestamp() { - return timestamp; + return dateTime; } - public void setTimestamp(LocalDateTime timestamp) { - this.timestamp = timestamp; + public void setTimestamp(LocalDateTime dateTime) { + this.dateTime = dateTime; } public List getOrders() { diff --git a/src/main/java/com/labwork1/app/student/model/Customer.java b/src/main/java/com/labwork1/app/student/model/User.java similarity index 62% rename from src/main/java/com/labwork1/app/student/model/Customer.java rename to src/main/java/com/labwork1/app/student/model/User.java index 9e637ca..dd76e61 100644 --- a/src/main/java/com/labwork1/app/student/model/Customer.java +++ b/src/main/java/com/labwork1/app/student/model/User.java @@ -9,7 +9,8 @@ import java.util.List; import java.util.Objects; @Entity -public class Customer { +@Table(name = "tab_user") +public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @@ -21,38 +22,60 @@ public class Customer { @NotBlank(message = "password can't be null or empty") @Size(min = 6, max = 64) private String password; - @OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = {CascadeType.MERGE,CascadeType.REMOVE}) + @OneToMany(fetch = FetchType.EAGER, mappedBy = "user", cascade = {CascadeType.MERGE,CascadeType.REMOVE}) private List orders; + @OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = + { + CascadeType.REMOVE, + CascadeType.MERGE, + CascadeType.PERSIST + }, orphanRemoval = true) + private List sessions; private UserRole role; - public Customer() { + public User() { } - public Customer(String login, String password) { + public User(String login, String password) { this.login = login; this.password = password; this.orders = new ArrayList<>(); + this.sessions = new ArrayList<>(); this.role = UserRole.USER; } - public Customer(String login, String password, UserRole role) { + public User(String login, String password, UserRole role) { this.login = login; this.password = password; this.orders = new ArrayList<>(); + this.sessions = new ArrayList<>(); this.role = role; } - public Customer(UserSignupDto userSignupDto) { + public User(UserSignupDto userSignupDto) { this.login = userSignupDto.getLogin(); this.password = userSignupDto.getPassword(); this.role = UserRole.USER; } + public void addSession(UserSession userSession) { + if (sessions == null) { + sessions = new ArrayList<>(); + } + if (!sessions.contains(userSession)) + this.sessions.add(userSession); + } + + public void removeSession(UserSession userSession){ + if (sessions.contains(userSession)) + this.sessions.remove(userSession); + } + @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; - Customer customer = (Customer) o; - return Objects.equals(id, customer.id); + User user = (User) o; + return Objects.equals(id, user.id); } @Override @@ -62,7 +85,7 @@ public class Customer { @Override public String toString() { - return "Customer {" + + return "User {" + "id=" + id + ", login='" + login + '\'' + ", password='" + password + '\'' + @@ -93,12 +116,16 @@ public class Customer { this.password = password; } + public List getSessions() { + return sessions; + } + public List getOrders() { return orders; } public void setOrder(Order order) { - if (order.getCustomer().equals(this)) { + if (order.getUser().equals(this)) { this.orders.add(order); } } diff --git a/src/main/java/com/labwork1/app/student/model/UserSession.java b/src/main/java/com/labwork1/app/student/model/UserSession.java new file mode 100644 index 0000000..b2ba588 --- /dev/null +++ b/src/main/java/com/labwork1/app/student/model/UserSession.java @@ -0,0 +1,62 @@ +package com.labwork1.app.student.model; + +import jakarta.persistence.*; + +@Entity +@Table(name = "user_session") +public class UserSession { + @EmbeddedId + private UserSessionKey id; + @ManyToOne + @MapsId("sessionId") + @JoinColumn(name = "session_id") + private Session session; + @ManyToOne + @MapsId("userId") + @JoinColumn(name = "user_id") + private User user; + @Column(name = "count") + private Integer count; + + public UserSession() { + } + + public UserSession(User user, Session session, Integer count) { + this.user = user; + this.session = session; + this.count = count; + this.id = new UserSessionKey(session.getId(), user.getId()); + } + + public UserSessionKey getId() { + return id; + } + + public void setId(UserSessionKey id) { + this.id = id; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Session getSession() { + return session; + } + + public void setSession(Session session) { + this.session = session; + } + + public Integer getCount() { + return count; + } + + public void setCount(Integer count) { + this.count = count; + } +} \ No newline at end of file diff --git a/src/main/java/com/labwork1/app/student/model/UserSessionKey.java b/src/main/java/com/labwork1/app/student/model/UserSessionKey.java new file mode 100644 index 0000000..12f56e0 --- /dev/null +++ b/src/main/java/com/labwork1/app/student/model/UserSessionKey.java @@ -0,0 +1,49 @@ +package com.labwork1.app.student.model; + +import jakarta.persistence.Embeddable; + +import java.io.Serializable; +import java.util.Objects; + +@Embeddable +public class UserSessionKey implements Serializable { + private Long sessionId; + private Long userId; + + public UserSessionKey() { + } + + public UserSessionKey(Long sessionId, Long userId) { + this.sessionId = sessionId; + this.userId = userId; + } + + public Long getSessionId() { + return sessionId; + } + + public void setSessionId(Long sessionId) { + this.sessionId = sessionId; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof UserSessionKey that)) return false; + return Objects.equals(getSessionId(), that.getSessionId()) && Objects.equals(getUserId(), that.getUserId()); + } + + @Override + public int hashCode() { + return Objects.hash(getSessionId(), getUserId()); + } +} + diff --git a/src/main/java/com/labwork1/app/student/repository/CustomerRepository.java b/src/main/java/com/labwork1/app/student/repository/CustomerRepository.java deleted file mode 100644 index 40ce715..0000000 --- a/src/main/java/com/labwork1/app/student/repository/CustomerRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.labwork1.app.student.repository; - -import com.labwork1.app.student.model.Customer; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import java.util.Optional; - -public interface CustomerRepository extends JpaRepository { - Customer findOneByLoginIgnoreCase(String login); -} diff --git a/src/main/java/com/labwork1/app/student/repository/UserRepository.java b/src/main/java/com/labwork1/app/student/repository/UserRepository.java new file mode 100644 index 0000000..37cda83 --- /dev/null +++ b/src/main/java/com/labwork1/app/student/repository/UserRepository.java @@ -0,0 +1,13 @@ +package com.labwork1.app.student.repository; + +import com.labwork1.app.student.model.User; +import com.labwork1.app.student.model.UserSession; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface UserRepository extends JpaRepository { + User findOneByLoginIgnoreCase(String login); + @Query("Select us from UserSession us where us.user.id = :userId and us.session.id = :sessionId") + UserSession getUserSession(@Param("userId") Long userId, @Param("sessionId") Long sessionId); +} diff --git a/src/main/java/com/labwork1/app/student/service/CustomerNotFoundException.java b/src/main/java/com/labwork1/app/student/service/CustomerNotFoundException.java deleted file mode 100644 index 6f2317b..0000000 --- a/src/main/java/com/labwork1/app/student/service/CustomerNotFoundException.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.labwork1.app.student.service; - -public class CustomerNotFoundException extends RuntimeException { - public CustomerNotFoundException(Long id) { - super(String.format("Customer with id [%s] is not found", id)); - } -} diff --git a/src/main/java/com/labwork1/app/student/service/CustomerService.java b/src/main/java/com/labwork1/app/student/service/CustomerService.java deleted file mode 100644 index c1309aa..0000000 --- a/src/main/java/com/labwork1/app/student/service/CustomerService.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.labwork1.app.student.service; - -import com.labwork1.app.student.model.Customer; -import com.labwork1.app.student.model.UserRole; -import com.labwork1.app.student.model.UserSignupDto; -import com.labwork1.app.student.repository.CustomerRepository; -import com.labwork1.app.util.validation.ValidatorUtil; -import jakarta.validation.ValidationException; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Sort; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -@Service -public class CustomerService implements UserDetailsService { - private final CustomerRepository customerRepository; - private final PasswordEncoder passwordEncoder; - private final ValidatorUtil validatorUtil; - - public CustomerService(CustomerRepository customerRepository, PasswordEncoder passwordEncoder, ValidatorUtil validatorUtil) { - this.customerRepository = customerRepository; - this.passwordEncoder = passwordEncoder; - this.validatorUtil = validatorUtil; - } - - public Page findAllPages(int page, int size) { - return customerRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending())); - } - - public Customer findByLogin(String login) { - return customerRepository.findOneByLoginIgnoreCase(login); - } - - @Transactional - public Customer addCustomer(String login, String password, String passwordConfirm) { - return createUser(login, password, passwordConfirm, UserRole.USER); - } - - @Transactional - public Customer addCustomer(UserSignupDto userSignupDto) { - if (findByLogin(userSignupDto.getLogin()) != null) { - throw new ValidationException(String.format("User '%s' already exists", userSignupDto.getLogin())); - } - if (!Objects.equals(userSignupDto.getPassword(), userSignupDto.getPasswordConfirm())) { - throw new ValidationException("Passwords not equals"); - } - final Customer user = new Customer(userSignupDto); - validatorUtil.validate(user); - return customerRepository.save(user); - } - - public Customer createUser(String login, String password, String passwordConfirm, UserRole role) { - if (findByLogin(login) != null) { - throw new ValidationException(String.format("User '%s' already exists", login)); - } - final Customer user = new Customer(login, passwordEncoder.encode(password), role); - validatorUtil.validate(user); - if (!Objects.equals(password, passwordConfirm)) { - throw new ValidationException("Passwords not equals"); - } - return customerRepository.save(user); - } - - @Transactional(readOnly = true) - public Customer findCustomer(Long id) { - final Optional customer = customerRepository.findById(id); - return customer.orElseThrow(() -> new CustomerNotFoundException(id)); - } - - @Transactional(readOnly = true) - public List findAllCustomers() { - return customerRepository.findAll(); - } - - @Transactional - public Customer updateCustomer(Long id, String login, String password) { - final Customer currentCustomer = findCustomer(id); - currentCustomer.setLogin(login); - currentCustomer.setPassword(password); - validatorUtil.validate(currentCustomer); - return customerRepository.save(currentCustomer); - } - - @Transactional - public Customer deleteCustomer(Long id) { - final Customer customer = findCustomer(id); - customerRepository.deleteById(id); - return customer; - } - - @Transactional - public void deleteAllCustomers() { - customerRepository.deleteAll(); - } - - @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - final Customer userEntity = findByLogin(username); - if (userEntity == null) { - throw new UsernameNotFoundException(username); - } - return new org.springframework.security.core.userdetails.User( - userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole())); - } -} diff --git a/src/main/java/com/labwork1/app/student/service/OrderService.java b/src/main/java/com/labwork1/app/student/service/OrderService.java index a65390a..8903312 100644 --- a/src/main/java/com/labwork1/app/student/service/OrderService.java +++ b/src/main/java/com/labwork1/app/student/service/OrderService.java @@ -14,22 +14,22 @@ import java.util.Optional; @Service public class OrderService { private final OrderRepository orderRepository; - private final CustomerService customerService; + private final UserService userService; private final SessionService sessionService; private final ValidatorUtil validatorUtil; - public OrderService(OrderRepository orderRepository, CustomerService customerService, SessionService sessionService, ValidatorUtil validatorUtil) { + public OrderService(OrderRepository orderRepository, UserService userService, SessionService sessionService, ValidatorUtil validatorUtil) { this.orderRepository = orderRepository; - this.customerService = customerService; + this.userService = userService; this.sessionService = sessionService; this.validatorUtil = validatorUtil; } @Transactional - public Order addOrder(Long customerId) { - final Order order = new Order(new Date(System.currentTimeMillis())); - final Customer customer = customerService.findCustomer(customerId); - order.setCustomer(customer); + public Order addOrder(Long userId) { + final Order order = new Order(); + final User user = userService.findUser(userId); + order.setUser(user); validatorUtil.validate(order); return orderRepository.save(order); } diff --git a/src/main/java/com/labwork1/app/student/service/UserNotFoundException.java b/src/main/java/com/labwork1/app/student/service/UserNotFoundException.java new file mode 100644 index 0000000..e66de35 --- /dev/null +++ b/src/main/java/com/labwork1/app/student/service/UserNotFoundException.java @@ -0,0 +1,7 @@ +package com.labwork1.app.student.service; + +public class UserNotFoundException extends RuntimeException { + public UserNotFoundException(Long id) { + super(String.format("User with id [%s] is not found", id)); + } +} diff --git a/src/main/java/com/labwork1/app/student/service/UserService.java b/src/main/java/com/labwork1/app/student/service/UserService.java new file mode 100644 index 0000000..46179c9 --- /dev/null +++ b/src/main/java/com/labwork1/app/student/service/UserService.java @@ -0,0 +1,160 @@ +package com.labwork1.app.student.service; + +import com.labwork1.app.student.model.*; +import com.labwork1.app.student.repository.UserRepository; +import com.labwork1.app.util.validation.ValidatorUtil; +import jakarta.persistence.EntityNotFoundException; +import jakarta.validation.ValidationException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +@Service +public class UserService implements UserDetailsService { + private final UserRepository userRepository; + private final SessionService sessionService; + private final PasswordEncoder passwordEncoder; + private final ValidatorUtil validatorUtil; + + public UserService(UserRepository userRepository, SessionService sessionService, PasswordEncoder passwordEncoder, ValidatorUtil validatorUtil) { + this.userRepository = userRepository; + this.sessionService = sessionService; + this.passwordEncoder = passwordEncoder; + this.validatorUtil = validatorUtil; + } + + public Page findAllPages(int page, int size) { + return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending())); + } + + public User findByLogin(String login) { + return userRepository.findOneByLoginIgnoreCase(login); + } + + @Transactional + public User addUser(String login, String password, String passwordConfirm) { + return createUser(login, password, passwordConfirm, UserRole.USER); + } + + @Transactional + public User addUser(UserSignupDto userSignupDto) { + if (findByLogin(userSignupDto.getLogin()) != null) { + throw new ValidationException(String.format("User '%s' already exists", userSignupDto.getLogin())); + } + if (!Objects.equals(userSignupDto.getPassword(), userSignupDto.getPasswordConfirm())) { + throw new ValidationException("Passwords not equals"); + } + final User user = new User(userSignupDto); + validatorUtil.validate(user); + return userRepository.save(user); + } + + public User createUser(String login, String password, String passwordConfirm, UserRole role) { + if (findByLogin(login) != null) { + throw new ValidationException(String.format("User '%s' already exists", login)); + } + final User user = new User(login, passwordEncoder.encode(password), role); + validatorUtil.validate(user); + if (!Objects.equals(password, passwordConfirm)) { + throw new ValidationException("Passwords not equals"); + } + return userRepository.save(user); + } + + @Transactional(readOnly = true) + public User findUser(Long id) { + final Optional user = userRepository.findById(id); + return user.orElseThrow(() -> new UserNotFoundException(id)); + } + + @Transactional(readOnly = true) + public List findAllUsers() { + return userRepository.findAll(); + } + + @Transactional + public User updateUser(Long id, String login, String password) { + final User currentUser = findUser(id); + currentUser.setLogin(login); + currentUser.setPassword(password); + validatorUtil.validate(currentUser); + return userRepository.save(currentUser); + } + + @Transactional + public User deleteUser(Long id) { + final User user = findUser(id); + userRepository.deleteById(id); + return user; + } + + @Transactional + public User addSession(Long id, Long sessionId, Integer count) { + final Session currentSession = sessionService.findSession(sessionId); + final User currentUser = findUser(id); + final UserSession currentUserSession = userRepository.getUserSession(id, sessionId); + + final Integer currentSessionCapacity = currentSession.getMaxCount() - sessionService.getCapacity(sessionId); + if (currentSessionCapacity < count || + (currentUserSession != null && currentUserSession.getCount() + count > currentSession.getMaxCount())) { + throw new IllegalArgumentException(String.format("No more tickets in session. Capacity: %1$s. Count: %2$s", + currentSessionCapacity, count)); + } + + if (currentUserSession == null) { + currentUser.addSession(new UserSession(currentUser, currentSession, count)); + } + else if (currentUserSession.getCount() + count <= currentSession.getMaxCount()) { + currentUser.removeSession(currentUserSession); + currentUser.addSession(new UserSession(currentUser, currentSession, + currentUserSession.getCount() + count)); + } + + return userRepository.save(currentUser); + } + + @Transactional + public User deleteSessionInCart(Long id, Long session, Integer count) { + final User currentUser = findUser(id); + final Session currentSession = sessionService.findSession(session); + final UserSession currentUserSession = userRepository.getUserSession(id, session); + if (currentUserSession == null) + throw new EntityNotFoundException(); + + if (count >= currentUserSession.getCount()) { + currentUser.removeSession(currentUserSession); + } + else { + currentUser.removeSession(currentUserSession); + currentUser.addSession(new UserSession(currentUser, currentSession, + currentUserSession.getCount() - count)); + } + return userRepository.save(currentUser); + } + + @Transactional + public void deleteAllUsers() { + userRepository.deleteAll(); + } + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + final User userEntity = findByLogin(username); + if (userEntity == null) { + throw new UsernameNotFoundException(username); + } + return new org.springframework.security.core.userdetails.User( + userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole())); + } +} diff --git a/src/main/java/com/labwork1/app/util/error/AdviceController.java b/src/main/java/com/labwork1/app/util/error/AdviceController.java index 278aac6..5d7bf7b 100644 --- a/src/main/java/com/labwork1/app/util/error/AdviceController.java +++ b/src/main/java/com/labwork1/app/util/error/AdviceController.java @@ -1,7 +1,7 @@ package com.labwork1.app.util.error; import com.labwork1.app.student.service.CinemaNotFoundException; -import com.labwork1.app.student.service.CustomerNotFoundException; +import com.labwork1.app.student.service.UserNotFoundException; import com.labwork1.app.student.service.OrderNotFoundException; import com.labwork1.app.student.service.SessionNotFoundException; import com.labwork1.app.util.validation.ValidationException; @@ -17,7 +17,7 @@ import java.util.stream.Collectors; @ControllerAdvice public class AdviceController { @ExceptionHandler({ - CustomerNotFoundException.class, + UserNotFoundException.class, OrderNotFoundException.class, SessionNotFoundException.class, CinemaNotFoundException.class, diff --git a/src/main/resources/templates/customer-edit.html b/src/main/resources/templates/customer-edit.html index d81d122..010eb8e 100644 --- a/src/main/resources/templates/customer-edit.html +++ b/src/main/resources/templates/customer-edit.html @@ -8,21 +8,21 @@
Пользователь
-
+
- +
- +
- + Назад
diff --git a/src/main/resources/templates/customer.html b/src/main/resources/templates/customer.html index 96cf3e9..bccb775 100644 --- a/src/main/resources/templates/customer.html +++ b/src/main/resources/templates/customer.html @@ -17,23 +17,23 @@ - - - - - + + + + + - -
@@ -44,9 +44,9 @@
diff --git a/src/main/resources/templates/default.html b/src/main/resources/templates/default.html index 4cc898e..e18df74 100644 --- a/src/main/resources/templates/default.html +++ b/src/main/resources/templates/default.html @@ -32,7 +32,7 @@