This commit is contained in:
dasha 2023-12-12 19:01:47 +04:00
parent a41fcf5618
commit 76adccc186
42 changed files with 705 additions and 490 deletions

View File

@ -11,15 +11,15 @@ export default function Orders() {
// хук для запоминания индекса элемента, вызвавшего модальное окно // хук для запоминания индекса элемента, вызвавшего модальное окно
const [currEditItem, setCurrEditItem] = useState(0); const [currEditItem, setCurrEditItem] = useState(0);
// для выпадающих значений // для выпадающих значений
const [customerName, setCustomerName] = useState(''); const [userName, setUserName] = useState('');
const [customer, setCustomer] = useState([]); const [user, setUser] = useState([]);
const [sessionName, setSessionName] = useState(''); const [sessionName, setSessionName] = useState('');
const [count, setCount] = useState(1); const [count, setCount] = useState(1);
const [session, setSession] = useState([]); const [session, setSession] = useState([]);
const [orderSessions, setOrderSessions] = useState([]); const [orderSessions, setOrderSessions] = useState([]);
useEffect(() => { useEffect(() => {
getAll('customer').then((data) => setCustomer(data)) getAll('user').then((data) => setUser(data))
getAll('session').then((data) => setSession(data)) getAll('session').then((data) => setSession(data))
getAll('order').then((data) => setUsers(data)) getAll('order').then((data) => setUsers(data))
}, []) }, [])
@ -33,12 +33,12 @@ export default function Orders() {
function handleSubmit(e) { function handleSubmit(e) {
e.preventDefault(); e.preventDefault();
if (customer.length <= 0) { if (user.length <= 0) {
throw 'Form not submit' throw 'Form not submit'
} }
handleSubmitCreate(e) handleSubmitCreate(e)
console.log('Form submit') console.log('Form submit')
setCustomer('') setUser('')
} }
// принимаем событие от кнопки "добавить" // принимаем событие от кнопки "добавить"
@ -52,10 +52,10 @@ export default function Orders() {
"Content-Type": "application/json" "Content-Type": "application/json"
} }
}; };
await fetch(`http://localhost:8080/order?customer=${customerName}`, requestParams) await fetch(`http://localhost:8080/order?user=${userName}`, requestParams)
.then((data) => { .then((data) => {
getCustomerOrders(customerName) getUserOrders(userName)
getAll('customer').then((data) => setCustomer(data)) getAll('user').then((data) => setUser(data))
}) })
.catch(function (error) { .catch(function (error) {
console.error('Error:', error); console.error('Error:', error);
@ -127,8 +127,8 @@ export default function Orders() {
}); });
}; };
async function getCustomerOrders(id) { async function getUserOrders(id) {
Service.read(`customer/${id}`) Service.read(`user/${id}`)
.then(function (data) { .then(function (data) {
setUsers(data.orders); setUsers(data.orders);
console.info('End'); console.info('End');
@ -158,12 +158,12 @@ export default function Orders() {
const Content = ( const Content = (
<> <>
<select required className="form-select" name="customer" id="customer" value={customer.value} onChange={e => { <select required className="form-select" name="user" id="user" value={user.value} onChange={e => {
setCustomerName(e.target.value) setUserName(e.target.value)
getCustomerOrders(e.target.value) getUserOrders(e.target.value)
}} > }} >
<option value='' defaultValue disabled>Выберите значение</option> <option value='' defaultValue disabled>Выберите значение</option>
{customer ? customer.map(elem => {user ? user.map(elem =>
<option key={elem.id} value={elem.id}>{elem.login}</option> <option key={elem.id} value={elem.id}>{elem.login}</option>
) : null} ) : null}
</select> </select>
@ -176,7 +176,7 @@ export default function Orders() {
<thead> <thead>
<tr> <tr>
<th scope="col">#</th> <th scope="col">#</th>
<th scope="col">Customer</th> <th scope="col">User</th>
<th scope="col">DateOfPurchase</th> <th scope="col">DateOfPurchase</th>
<th scope="col"></th> <th scope="col"></th>
</tr> </tr>
@ -199,7 +199,7 @@ export default function Orders() {
<select required className="form-control" name="session" id="session" value={session.value} onChange={e => setSessionName(e.target.value)} > <select required className="form-control" name="session" id="session" value={session.value} onChange={e => setSessionName(e.target.value)} >
<option value='' defaultValue disabled>Выберите значение</option> <option value='' defaultValue disabled>Выберите значение</option>
{session ? session.map(elem => {session ? session.map(elem =>
<option key={elem.id} value={elem.id}>{elem.cinema.name} {new Date(elem.timestamp).toLocaleString('RU-ru')}</option> <option key={elem.id} value={elem.id}>{elem.cinema.name} {new Date(elem.dateTime).toLocaleString('RU-ru')}</option>
) : null} ) : null}
</select> </select>
</div> </div>

View File

@ -22,7 +22,7 @@ export default function Registration() {
}, []) }, [])
async function getAll() { async function getAll() {
const requestUrl = "http://localhost:8080/customer" const requestUrl = "http://localhost:8080/user"
const response = await fetch(requestUrl) const response = await fetch(requestUrl)
const temp = await response.json() const temp = await response.json()
setUsers(temp) setUsers(temp)
@ -51,7 +51,7 @@ export default function Registration() {
"Content-Type": "application/json" "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(() => { .then(() => {
getAll() getAll()
}) })
@ -60,7 +60,7 @@ export default function Registration() {
function handleEdit(id) { function handleEdit(id) {
console.info(`Start edit script`); console.info(`Start edit script`);
Service.read(`customer/${id}`) Service.read(`user/${id}`)
.then(function (data) { .then(function (data) {
setLoginEdit(data.login); setLoginEdit(data.login);
setPasswordEdit(data.password); setPasswordEdit(data.password);
@ -79,7 +79,7 @@ export default function Registration() {
"Content-Type": "application/json" "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 response = await fetch(requestUrl, requestParams)
const temp = await response.json() const temp = await response.json()
.then((data) => { .then((data) => {
@ -101,7 +101,7 @@ export default function Registration() {
function handleDelete(id) { function handleDelete(id) {
console.info('Try to remove item'); console.info('Try to remove item');
Service.delete(`customer/${id}`) Service.delete(`user/${id}`)
.then(() => { .then(() => {
setUsers(users.filter(elem => elem.id !== id)) setUsers(users.filter(elem => elem.id !== id))
console.log("Removed") console.log("Removed")

View File

@ -7,7 +7,7 @@ import CinemaDto from './models/CinemaDto'
export default function Sessions() { export default function Sessions() {
const [price, setPrice] = useState(1); const [price, setPrice] = useState(1);
const [timestamp, setTimestamp] = useState(new Date()); const [dateTime, setTimestamp] = useState(new Date());
const [maxCount, setMaxCount] = useState(1); const [maxCount, setMaxCount] = useState(1);
const [priceEdit, setPriceEdit] = useState(''); const [priceEdit, setPriceEdit] = useState('');
const [users, setUsers] = useState([]); const [users, setUsers] = useState([]);
@ -55,7 +55,7 @@ export default function Sessions() {
"Content-Type": "application/json" "Content-Type": "application/json"
} }
}; };
await fetch(`http://localhost:8080/session?price=${price}&timestamp=${timestamp}&cinemaid=${cinemaName}&capacity=${maxCount}`, requestParams) await fetch(`http://localhost:8080/session?price=${price}&dateTime=${dateTime}&cinemaid=${cinemaName}&capacity=${maxCount}`, requestParams)
.then(() => { .then(() => {
getAll('session').then((data) => setUsers(data)) getAll('session').then((data) => setUsers(data))
getAll('cinema').then((data) => setCinema(data)) getAll('cinema').then((data) => setCinema(data))
@ -140,9 +140,9 @@ export default function Sessions() {
{error && price.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод цены</label> : null} {error && price.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод цены</label> : null}
<div> <div>
<label className="form-label">Дата</label> <label className="form-label">Дата</label>
<input className="form-control mainInput" type="datetime-local" value={timestamp} onChange={e => setTimestamp(e.target.value)} placeholder="Введите дату" /> <input className="form-control mainInput" type="datetime-local" value={dateTime} onChange={e => setTimestamp(e.target.value)} placeholder="Введите дату" />
</div> </div>
{error && timestamp.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод даты</label> : null} {error && dateTime.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод даты</label> : null}
<div> <div>
<button className="btn btn-success my-3" type="button" onClick={handleSubmit}>Сохранить</button> <button className="btn btn-success my-3" type="button" onClick={handleSubmit}>Сохранить</button>
</div> </div>

View File

@ -5,7 +5,7 @@ export default function OrderItem(props) {
return ( return (
<tr> <tr>
<td>{props.item.id}</td> <td>{props.item.id}</td>
<td>{props.item.customer}</td> <td>{props.item.user}</td>
<td>{props.item.dateOfPurchase}</td> <td>{props.item.dateOfPurchase}</td>
<td><MyButton value={props} /></td> <td><MyButton value={props} /></td>
</tr> </tr>

View File

@ -8,7 +8,7 @@ export default function OrderSessionItem(props) {
<td>{props.item.session.id}</td> <td>{props.item.session.id}</td>
<td>{props.item.session.price}</td> <td>{props.item.session.price}</td>
<td>{props.item.session.cinema.name}</td> <td>{props.item.session.cinema.name}</td>
<td>{new Date(props.item.session.timestamp).toLocaleString('RU-ru')}</td> <td>{new Date(props.item.session.dateTime).toLocaleString('RU-ru')}</td>
<td>{props.item.count}</td> <td>{props.item.count}</td>
<td><MyButton value={props} /></td> <td><MyButton value={props} /></td>
</tr> </tr>

View File

@ -2,7 +2,7 @@ import React, { useEffect, useState } from "react"
import MyButton from './MyButton' import MyButton from './MyButton'
export default function SessionItem(props) { 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 ( return (
<tr> <tr>

View File

@ -1,10 +1,10 @@
export default class CustomerDto { export default class UserDto {
constructor(login, password, id) { constructor(login, password, id) {
this.login = login; this.login = login;
this.password = password; this.password = password;
this.id = parseInt(id); this.id = parseInt(id);
} }
static createFrom(item) { static createFrom(item) {
return new CustomerDto(item.login, item.password, item.id); return new UserDto(item.login, item.password, item.id);
} }
} }

View File

@ -2,7 +2,7 @@ package com.labwork1.app.configuration;
import com.labwork1.app.student.controller.UserSignupMvcController; import com.labwork1.app.student.controller.UserSignupMvcController;
import com.labwork1.app.student.model.UserRole; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
@ -23,9 +23,9 @@ import org.springframework.security.web.SecurityFilterChain;
public class SecurityConfiguration { public class SecurityConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class); private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
private static final String LOGIN_URL = "/login"; 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; this.userService = userService;
createAdminOnStartup(); createAdminOnStartup();
} }

View File

@ -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<CustomerDto> 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));
}
}

View File

@ -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<OrderDto> 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<OrderDto> orders) {
this.orders = orders;
}
public long getId() {
return id;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public List<OrderDto> getOrders() {
return orders;
}
public UserRole getRole() {
return role;
}
}

View File

@ -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<CustomerDto> users = customerService.findAllPages(page, size)
.map(CustomerDto::new);
model.addAttribute("customers", users);
final int totalPages = users.getTotalPages();
final List<Integer> 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";
}
}

View File

@ -28,8 +28,8 @@ public class OrderController {
} }
@PostMapping @PostMapping
public OrderDto createOrder(@RequestParam("customer") Long customer) { public OrderDto createOrder(@RequestParam("user") Long user) {
return new OrderDto(orderService.addOrder(customer)); return new OrderDto(orderService.addOrder(user));
} }
@PutMapping("/{id}") @PutMapping("/{id}")

View File

@ -1,6 +1,6 @@
package com.labwork1.app.student.controller; 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.Order;
import com.labwork1.app.student.model.OrderSession; import com.labwork1.app.student.model.OrderSession;
@ -9,9 +9,8 @@ import java.util.List;
public class OrderDto { public class OrderDto {
private long id; private long id;
private Date dateOfPurchase; private Long userId;
private Long customerId; private String user;
private String customer;
private List<OrderSessionDto> sessions; private List<OrderSessionDto> sessions;
public OrderDto() { public OrderDto() {
@ -19,34 +18,29 @@ public class OrderDto {
public OrderDto(Order order) { public OrderDto(Order order) {
this.id = order.getId(); this.id = order.getId();
this.dateOfPurchase = order.getDateOfPurchase(); this.userId = order.getUser().getId();
this.customerId = order.getCustomer().getId(); this.user = order.getUser().getLogin();
this.customer = order.getCustomer().getLogin(); if (order.getSessions() != null && !order.getSessions().isEmpty())
if (order.getSessions() != null && order.getSessions().size() > 0)
this.sessions = order.getSessions() this.sessions = order.getSessions()
.stream() .stream()
.map(x -> new OrderSessionDto(new SessionDto(x.getSession()), .map(x -> new OrderSessionDto(new SessionDto(x.getSession()),
x.getId().getOrderId(), x.getCount())).toList(); x.getId().getOrderId(), x.getCount())).toList();
} }
public Long getCustomerId() { public Long getUserId() {
return customerId; return userId;
} }
public void setCustomerId(Long customerId) { public void setUserId(Long userId) {
this.customerId = customerId; this.userId = userId;
} }
public void setId(long id) { public void setId(long id) {
this.id = id; this.id = id;
} }
public void setDateOfPurchase(Date dateOfPurchase) { public void setUser(String user) {
this.dateOfPurchase = dateOfPurchase; this.user = user;
}
public void setCustomer(String customer) {
this.customer = customer;
} }
public void setSessions(List<OrderSessionDto> sessions) { public void setSessions(List<OrderSessionDto> sessions) {
@ -57,12 +51,8 @@ public class OrderDto {
return id; return id;
} }
public Date getDateOfPurchase() { public String getUser() {
return dateOfPurchase; return user;
}
public String getCustomer() {
return customer;
} }
public List<OrderSessionDto> getSessions() { public List<OrderSessionDto> getSessions() {

View File

@ -1,10 +1,10 @@
package com.labwork1.app.student.controller; 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.Order;
import com.labwork1.app.student.model.SessionExtension; import com.labwork1.app.student.model.SessionExtension;
import com.labwork1.app.student.model.UserRole; 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.OrderService;
import com.labwork1.app.student.service.SessionService; import com.labwork1.app.student.service.SessionService;
import jakarta.validation.Valid; import jakarta.validation.Valid;
@ -25,24 +25,24 @@ import java.util.Objects;
public class OrderMvcController { public class OrderMvcController {
private final OrderService orderService; private final OrderService orderService;
private final SessionService sessionService; 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.orderService = orderService;
this.sessionService = sessionService; this.sessionService = sessionService;
this.customerService = customerService; this.userService = userService;
} }
@GetMapping @GetMapping
public String getOrders(Model model, public String getOrders(Model model,
Principal principal) { Principal principal) {
Customer customer = customerService.findByLogin(principal.getName()); User user = userService.findByLogin(principal.getName());
if (customer.getRole() == UserRole.USER) if (user.getRole() == UserRole.USER)
model.addAttribute("orders", model.addAttribute("orders",
orderService.findAllOrders().stream() orderService.findAllOrders().stream()
.map(OrderDto::new) .map(OrderDto::new)
.filter(orderDto -> Objects.equals(orderDto.getCustomerId(), .filter(orderDto -> Objects.equals(orderDto.getUserId(),
customer.getId())) user.getId()))
.toList()); .toList());
else else
model.addAttribute("orders", model.addAttribute("orders",
@ -62,8 +62,8 @@ public class OrderMvcController {
return "order-edit"; return "order-edit";
} else { } else {
Order order = orderService.findOrder(id); Order order = orderService.findOrder(id);
Customer customer = customerService.findByLogin(principal.getName()); User user = userService.findByLogin(principal.getName());
if (!Objects.equals(order.getCustomer().getId(), customer.getId()) && customer.getRole() == UserRole.USER) if (!Objects.equals(order.getUser().getId(), user.getId()) && user.getRole() == UserRole.USER)
return "redirect:/order"; return "redirect:/order";
List<OrderSessionDto> temp = order.getSessions() List<OrderSessionDto> temp = order.getSessions()
.stream().map(x -> new OrderSessionDto(new SessionDto(x.getSession()), .stream().map(x -> new OrderSessionDto(new SessionDto(x.getSession()),
@ -88,12 +88,12 @@ public class OrderMvcController {
BindingResult bindingResult, BindingResult bindingResult,
Model model, Model model,
Principal principal) { Principal principal) {
Long customerId = customerService.findByLogin(principal.getName()).getId(); Long userId = userService.findByLogin(principal.getName()).getId();
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors()); model.addAttribute("errors", bindingResult.getAllErrors());
return "order-edit"; return "order-edit";
} }
orderService.addOrder(customerId); orderService.addOrder(userId);
return "redirect:/order"; return "redirect:/order";
} }
@ -104,8 +104,8 @@ public class OrderMvcController {
Model model, Model model,
Principal principal) { Principal principal) {
Order order = orderService.findOrder(id); Order order = orderService.findOrder(id);
Customer customer = customerService.findByLogin(principal.getName()); User user = userService.findByLogin(principal.getName());
if (!Objects.equals(order.getCustomer().getId(), customer.getId()) && customer.getRole() == UserRole.USER) if (!Objects.equals(order.getUser().getId(), user.getId()) && user.getRole() == UserRole.USER)
return "/order"; return "/order";
if (count == null) if (count == null)
orderService.deleteSessionInOrder(id, session, Integer.MAX_VALUE); orderService.deleteSessionInOrder(id, session, Integer.MAX_VALUE);
@ -118,8 +118,8 @@ public class OrderMvcController {
public String deleteOrder(@PathVariable Long id, public String deleteOrder(@PathVariable Long id,
Principal principal) { Principal principal) {
Order order = orderService.findOrder(id); Order order = orderService.findOrder(id);
Customer customer = customerService.findByLogin(principal.getName()); User user = userService.findByLogin(principal.getName());
if (!Objects.equals(order.getCustomer().getId(), customer.getId()) && customer.getRole() == UserRole.USER) if (!Objects.equals(order.getUser().getId(), user.getId()) && user.getRole() == UserRole.USER)
return "redirect:/order"; return "redirect:/order";
orderService.deleteOrder(id); orderService.deleteOrder(id);
return "redirect:/order"; return "redirect:/order";

View File

@ -4,9 +4,11 @@ import com.labwork1.app.configuration.WebConfiguration;
import com.labwork1.app.student.service.SessionService; import com.labwork1.app.student.service.SessionService;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.sql.Timestamp;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -33,15 +35,16 @@ public class SessionController {
@PostMapping @PostMapping
public SessionDto createSession(@RequestParam("price") String price, public SessionDto createSession(@RequestParam("price") String price,
@RequestParam("timestamp") String timestamp, @RequestParam("dateTime") String dateTime,
@RequestParam("cinemaid") Long cinemaId, @RequestParam("cinemaId") Long cinemaId,
@RequestParam("capacity") Integer capacity) throws ParseException { @RequestParam("capacity") Integer capacity) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:ss");
format.applyPattern("yyyy-MM-dd-HH:mm"); Date docDate = format.parse(dateTime.replace('T', '-'));
Date docDate = format.parse(timestamp.replace('T', '-')); LocalDateTime localDateTime = LocalDateTime.ofInstant(docDate.toInstant(), ZoneId.systemDefault());
return new SessionDto(sessionService.findSession( return new SessionDto(sessionService.findSession(
sessionService.addSession(Double.parseDouble(price), sessionService.addSession(Double.parseDouble(price),
LocalDateTime.now(), cinemaId, capacity).getId())); localDateTime, cinemaId, capacity).getId()));
} }
@PutMapping("/{id}") @PutMapping("/{id}")
@ -55,5 +58,4 @@ public class SessionController {
public SessionDto deleteSession(@PathVariable Long id) { public SessionDto deleteSession(@PathVariable Long id) {
return new SessionDto(sessionService.deleteSession(id)); return new SessionDto(sessionService.deleteSession(id));
} }
} }

View File

@ -67,11 +67,11 @@ public class SessionMvcController {
@PostMapping(value = "/") @PostMapping(value = "/")
@Secured({UserRole.AsString.ADMIN}) @Secured({UserRole.AsString.ADMIN})
public String saveSession(@RequestParam("price") String price, public String saveSession(@RequestParam("price") String price,
@RequestParam("timestamp") LocalDateTime timestamp, @RequestParam("dateTime") LocalDateTime dateTime,
@RequestParam("cinemaid") Long cinemaId, @RequestParam("cinemaId") Long cinemaId,
@RequestParam("maxCount") Integer capacity, @RequestParam("maxCount") Integer capacity,
Model model) { Model model) {
sessionService.addSession(Double.parseDouble(price), timestamp, sessionService.addSession(Double.parseDouble(price), dateTime,
cinemaId, capacity); cinemaId, capacity);
return "redirect:/session"; return "redirect:/session";
} }

View File

@ -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<UserDto> 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));
}
}

View File

@ -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<OrderDto> orders;
private List<UserSessionDto> 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<OrderDto> getOrders() {
return orders;
}
public List<UserSessionDto> getSessions() {
return sessions;
}
}

View File

@ -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<UserDto> users = userService.findAllPages(page, size)
.map(UserDto::new);
model.addAttribute("users", users);
final int totalPages = users.getTotalPages();
final List<Integer> 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";
}
}

View File

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

View File

@ -1,8 +1,8 @@
package com.labwork1.app.student.controller; 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.model.UserSignupDto;
import com.labwork1.app.student.service.CustomerService; import com.labwork1.app.student.service.UserService;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import jakarta.validation.ValidationException; import jakarta.validation.ValidationException;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
@ -18,9 +18,9 @@ import org.springframework.web.bind.annotation.RequestMapping;
public class UserSignupMvcController { public class UserSignupMvcController {
public static final String SIGNUP_URL = "/signup"; 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; this.userService = userService;
} }
@ -39,7 +39,7 @@ public class UserSignupMvcController {
return "signup"; return "signup";
} }
try { try {
final Customer user = userService.addCustomer( final User user = userService.addUser(
userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm()); userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
return "redirect:/login?created=" + user.getLogin(); return "redirect:/login?created=" + user.getLogin();
} catch (ValidationException e) { } catch (ValidationException e) {

View File

@ -14,12 +14,9 @@ public class Order {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@NotNull(message = "dateOfPurchase can't be null or empty")
@Temporal(TemporalType.DATE)
private Date dateOfPurchase;
@ManyToOne(fetch = FetchType.EAGER) @ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "customer_fk") @JoinColumn(name = "user_fk")
private Customer customer; private User user;
@OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade = @OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade =
{ {
CascadeType.REMOVE, CascadeType.REMOVE,
@ -31,10 +28,6 @@ public class Order {
public Order() { public Order() {
} }
public Order(Date dateOfPurchase) {
this.dateOfPurchase = dateOfPurchase;
}
public void addSession(OrderSession orderSession) { public void addSession(OrderSession orderSession) {
if (sessions == null) { if (sessions == null) {
sessions = new ArrayList<>(); sessions = new ArrayList<>();
@ -65,30 +58,21 @@ public class Order {
public String toString() { public String toString() {
return "Order {" + return "Order {" +
"id=" + id + "id=" + id +
", date='" + dateOfPurchase.toString() + '\'' + ", user='" + user.toString() + '\'';
", customer='" + customer.toString() + '\'';
} }
public Long getId() { public Long getId() {
return id; return id;
} }
public Date getDateOfPurchase() { public User getUser() {
return dateOfPurchase; return user;
} }
public void setDateOfPurchase(Date dateOfPurchase) { public void setUser(User user) {
this.dateOfPurchase = dateOfPurchase; this.user = user;
} if (!user.getOrders().contains(this)) {
user.setOrder(this);
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
if (!customer.getOrders().contains(this)) {
customer.setOrder(this);
} }
} }

View File

@ -17,13 +17,15 @@ public class Session {
protected Long id; protected Long id;
@NotNull(message = "price can't be null or empty") @NotNull(message = "price can't be null or empty")
protected Double price; protected Double price;
@NotNull(message = "timestamp can't be null or empty") @NotNull(message = "dateTime can't be null or empty")
@Column @Column
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm")
protected LocalDateTime timestamp; protected LocalDateTime dateTime;
@OneToMany(mappedBy = "session", fetch = FetchType.EAGER) @OneToMany(mappedBy = "session", fetch = FetchType.EAGER)
private List<OrderSession> orders; private List<OrderSession> orders;
@OneToMany(mappedBy = "session", fetch = FetchType.EAGER)
private List<UserSession> users;
@ManyToOne(fetch = FetchType.EAGER) @ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "cinema_fk") @JoinColumn(name = "cinema_fk")
protected Cinema cinema; protected Cinema cinema;
@ -38,17 +40,18 @@ public class Session {
return maxCount; return maxCount;
} }
public Session(Double price, LocalDateTime timestamp, Integer maxCount) { public Session(Double price, LocalDateTime dateTime, Integer maxCount) {
this.price = price; this.price = price;
this.timestamp = timestamp; this.dateTime = dateTime;
this.maxCount = maxCount; this.maxCount = maxCount;
} }
public Session(Session session) { public Session(Session session) {
this.id = session.getId(); this.id = session.getId();
this.price = session.getPrice(); this.price = session.getPrice();
this.timestamp = session.getTimestamp(); this.dateTime = session.getTimestamp();
this.orders = session.getOrders(); this.orders = session.getOrders();
this.users = session.getUsers();
this.cinema = session.getCinema(); this.cinema = session.getCinema();
this.maxCount = session.getMaxCount(); this.maxCount = session.getMaxCount();
} }
@ -76,6 +79,36 @@ public class Session {
this.orders.remove(orderSession); this.orders.remove(orderSession);
} }
public LocalDateTime getDateTime() {
return dateTime;
}
public void setUsers(List<UserSession> users) {
this.users = users;
}
public void setDateTime(LocalDateTime dateTime) {
this.dateTime = dateTime;
}
public List<UserSession> 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 @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
@ -94,7 +127,7 @@ public class Session {
return "Session {" + return "Session {" +
"id=" + id + "id=" + id +
", price='" + price + '\'' + ", price='" + price + '\'' +
", timestamp='" + timestamp.toString() + '\'' + ", dateTime='" + dateTime.toString() + '\'' +
", maxCount='" + maxCount.toString() + '\'' + ", maxCount='" + maxCount.toString() + '\'' +
", cinema='" + cinema.toString() + '\'' + ", cinema='" + cinema.toString() + '\'' +
'}'; '}';
@ -125,11 +158,11 @@ public class Session {
} }
public LocalDateTime getTimestamp() { public LocalDateTime getTimestamp() {
return timestamp; return dateTime;
} }
public void setTimestamp(LocalDateTime timestamp) { public void setTimestamp(LocalDateTime dateTime) {
this.timestamp = timestamp; this.dateTime = dateTime;
} }
public List<OrderSession> getOrders() { public List<OrderSession> getOrders() {

View File

@ -9,7 +9,8 @@ import java.util.List;
import java.util.Objects; import java.util.Objects;
@Entity @Entity
public class Customer { @Table(name = "tab_user")
public class User {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@ -21,38 +22,60 @@ public class Customer {
@NotBlank(message = "password can't be null or empty") @NotBlank(message = "password can't be null or empty")
@Size(min = 6, max = 64) @Size(min = 6, max = 64)
private String password; 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<Order> orders; private List<Order> orders;
@OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade =
{
CascadeType.REMOVE,
CascadeType.MERGE,
CascadeType.PERSIST
}, orphanRemoval = true)
private List<UserSession> sessions;
private UserRole role; private UserRole role;
public Customer() { public User() {
} }
public Customer(String login, String password) { public User(String login, String password) {
this.login = login; this.login = login;
this.password = password; this.password = password;
this.orders = new ArrayList<>(); this.orders = new ArrayList<>();
this.sessions = new ArrayList<>();
this.role = UserRole.USER; this.role = UserRole.USER;
} }
public Customer(String login, String password, UserRole role) { public User(String login, String password, UserRole role) {
this.login = login; this.login = login;
this.password = password; this.password = password;
this.orders = new ArrayList<>(); this.orders = new ArrayList<>();
this.sessions = new ArrayList<>();
this.role = role; this.role = role;
} }
public Customer(UserSignupDto userSignupDto) { public User(UserSignupDto userSignupDto) {
this.login = userSignupDto.getLogin(); this.login = userSignupDto.getLogin();
this.password = userSignupDto.getPassword(); this.password = userSignupDto.getPassword();
this.role = UserRole.USER; 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 @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
Customer customer = (Customer) o; User user = (User) o;
return Objects.equals(id, customer.id); return Objects.equals(id, user.id);
} }
@Override @Override
@ -62,7 +85,7 @@ public class Customer {
@Override @Override
public String toString() { public String toString() {
return "Customer {" + return "User {" +
"id=" + id + "id=" + id +
", login='" + login + '\'' + ", login='" + login + '\'' +
", password='" + password + '\'' + ", password='" + password + '\'' +
@ -93,12 +116,16 @@ public class Customer {
this.password = password; this.password = password;
} }
public List<UserSession> getSessions() {
return sessions;
}
public List<Order> getOrders() { public List<Order> getOrders() {
return orders; return orders;
} }
public void setOrder(Order order) { public void setOrder(Order order) {
if (order.getCustomer().equals(this)) { if (order.getUser().equals(this)) {
this.orders.add(order); this.orders.add(order);
} }
} }

View File

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

View File

@ -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());
}
}

View File

@ -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, Long> {
Customer findOneByLoginIgnoreCase(String login);
}

View File

@ -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, Long> {
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);
}

View File

@ -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));
}
}

View File

@ -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<Customer> 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> customer = customerRepository.findById(id);
return customer.orElseThrow(() -> new CustomerNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Customer> 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()));
}
}

View File

@ -14,22 +14,22 @@ import java.util.Optional;
@Service @Service
public class OrderService { public class OrderService {
private final OrderRepository orderRepository; private final OrderRepository orderRepository;
private final CustomerService customerService; private final UserService userService;
private final SessionService sessionService; private final SessionService sessionService;
private final ValidatorUtil validatorUtil; 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.orderRepository = orderRepository;
this.customerService = customerService; this.userService = userService;
this.sessionService = sessionService; this.sessionService = sessionService;
this.validatorUtil = validatorUtil; this.validatorUtil = validatorUtil;
} }
@Transactional @Transactional
public Order addOrder(Long customerId) { public Order addOrder(Long userId) {
final Order order = new Order(new Date(System.currentTimeMillis())); final Order order = new Order();
final Customer customer = customerService.findCustomer(customerId); final User user = userService.findUser(userId);
order.setCustomer(customer); order.setUser(user);
validatorUtil.validate(order); validatorUtil.validate(order);
return orderRepository.save(order); return orderRepository.save(order);
} }

View File

@ -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));
}
}

View File

@ -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<User> 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> user = userRepository.findById(id);
return user.orElseThrow(() -> new UserNotFoundException(id));
}
@Transactional(readOnly = true)
public List<User> 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()));
}
}

View File

@ -1,7 +1,7 @@
package com.labwork1.app.util.error; package com.labwork1.app.util.error;
import com.labwork1.app.student.service.CinemaNotFoundException; 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.OrderNotFoundException;
import com.labwork1.app.student.service.SessionNotFoundException; import com.labwork1.app.student.service.SessionNotFoundException;
import com.labwork1.app.util.validation.ValidationException; import com.labwork1.app.util.validation.ValidationException;
@ -17,7 +17,7 @@ import java.util.stream.Collectors;
@ControllerAdvice @ControllerAdvice
public class AdviceController { public class AdviceController {
@ExceptionHandler({ @ExceptionHandler({
CustomerNotFoundException.class, UserNotFoundException.class,
OrderNotFoundException.class, OrderNotFoundException.class,
SessionNotFoundException.class, SessionNotFoundException.class,
CinemaNotFoundException.class, CinemaNotFoundException.class,

View File

@ -8,21 +8,21 @@
<div layout:fragment="content_header">Пользователь</div> <div layout:fragment="content_header">Пользователь</div>
<div layout:fragment="content"> <div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div> <div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/customer/{id}(id=${id})}" th:object="${customerDto}" method="post"> <form action="#" th:action="@{/user/{id}(id=${id})}" th:object="${userDto}" method="post">
<div class="mb-3"> <div class="mb-3">
<label for="login" class="form-label">Логин</label> <label for="login" class="form-label">Логин</label>
<input type="text" class="form-control" id="login" th:field="${customerDto.login}" required="true"> <input type="text" class="form-control" id="login" th:field="${userDto.login}" required="true">
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="password" class="form-label">Пароль</label> <label for="password" class="form-label">Пароль</label>
<input type="text" class="form-control" id="password" th:field="${customerDto.password}" required="true"> <input type="text" class="form-control" id="password" th:field="${userDto.password}" required="true">
</div> </div>
<div class="mb-3"> <div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed"> <button type="submit" class="btn btn-primary button-fixed">
<span th:if="${id == null}">Добавить</span> <span th:if="${id == null}">Добавить</span>
<span th:if="${id != null}">Обновить</span> <span th:if="${id != null}">Обновить</span>
</button> </button>
<a class="btn btn-secondary button-fixed" th:href="@{/customer}"> <a class="btn btn-secondary button-fixed" th:href="@{/user}">
Назад Назад
</a> </a>
</div> </div>

View File

@ -17,23 +17,23 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr th:each="customer, iterator: ${customers}"> <tr th:each="user, iterator: ${users}">
<td th:text="${customer.id}"/> <td th:text="${user.id}"/>
<td th:text="${customer.login}"/> <td th:text="${user.login}"/>
<td th:text="${customer.password}"/> <td th:text="${user.password}"/>
<td th:text="${customer.role}"/> <td th:text="${user.role}"/>
<td> <td>
<div> <div>
<a type="button" class="m-1 btn btn-primary" th:href="@{/customer/edit/{id}(id=${customer.id})}"> <a type="button" class="m-1 btn btn-primary" th:href="@{/user/edit/{id}(id=${user.id})}">
<i class="fa fa-pencil"></i> <i class="fa fa-pencil"></i>
</a> </a>
<a type="button" class="m-1 btn btn-danger" <a type="button" class="m-1 btn btn-danger"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${customer.id}').click()|"> th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${user.id}').click()|">
<i class="fa fa-trash"></i> <i class="fa fa-trash"></i>
</a> </a>
</div> </div>
<form th:action="@{/customer/delete/{id}(id=${customer.id})}" method="post"> <form th:action="@{/user/delete/{id}(id=${user.id})}" method="post">
<button th:id="'remove-' + ${customer.id}" type="submit" style="display: none"> <button th:id="'remove-' + ${user.id}" type="submit" style="display: none">
Удалить Удалить
</button> </button>
</form> </form>
@ -44,9 +44,9 @@
<div th:if="${totalPages > 0}" class="pagination"> <div th:if="${totalPages > 0}" class="pagination">
<span style="float: left; padding: 5px 5px;">Страницы:</span> <span style="float: left; padding: 5px 5px;">Страницы:</span>
<a th:each="page : ${pages}" <a th:each="page : ${pages}"
th:href="@{/customer(page=${page}, size=${customers.size})}" th:href="@{/user(page=${page}, size=${users.size})}"
th:text="${page}" th:text="${page}"
th:class="${page == customers.number + 1} ? active"> th:class="${page == users.number + 1} ? active">
</a> </a>
</div> </div>
</div> </div>

View File

@ -32,7 +32,7 @@
<ul class="navbar-nav" sec:authorize="isAuthenticated()"> <ul class="navbar-nav" sec:authorize="isAuthenticated()">
<a class="nav-link" href="/">Главная</a> <a class="nav-link" href="/">Главная</a>
<a class="nav-link" href="/cinema">Фильмы</a> <a class="nav-link" href="/cinema">Фильмы</a>
<a sec:authorize="hasRole('ROLE_ADMIN')" class="nav-link" href="/customer">Пользователи</a> <a sec:authorize="hasRole('ROLE_ADMIN')" class="nav-link" href="/user">Пользователи</a>
<a class="nav-link" href="/order">Заказы</a> <a class="nav-link" href="/order">Заказы</a>
<a class="nav-link" href="/session">Сеансы</a> <a class="nav-link" href="/session">Сеансы</a>
<a class="nav-link" href="/h2-console/" target="_blank" sec:authorize="hasRole('ROLE_ADMIN')">Консоль H2</a> <a class="nav-link" href="/h2-console/" target="_blank" sec:authorize="hasRole('ROLE_ADMIN')">Консоль H2</a>

View File

@ -17,7 +17,7 @@
<thead> <thead>
<tr> <tr>
<th scope="col">ID</th> <th scope="col">ID</th>
<th scope="col">Customer</th> <th scope="col">User</th>
<th scope="col">DateOfPurchase</th> <th scope="col">DateOfPurchase</th>
<th scope="col"></th> <th scope="col"></th>
</tr> </tr>
@ -25,7 +25,7 @@
<tbody> <tbody>
<tr th:each="item, iterator: ${orders}"> <tr th:each="item, iterator: ${orders}">
<td th:text="${item.id}"/> <td th:text="${item.id}"/>
<td th:text="${item.customer}"/> <td th:text="${item.user}"/>
<td th:text="${item.dateOfPurchase}"/> <td th:text="${item.dateOfPurchase}"/>
<td> <td>
<div> <div>

View File

@ -13,7 +13,7 @@
<select id="session" class="form-select" th:name="session" required="true"> <select id="session" class="form-select" th:name="session" required="true">
<option th:each="value: ${sessions}" <option th:each="value: ${sessions}"
th:value="${value.id}" th:value="${value.id}"
th:text="${value.cinema.name} + ' ' + ${value.timestamp}"> th:text="${value.cinema.name} + ' ' + ${value.dateTime}">
</option> </option>
</select> </select>
</div> </div>
@ -47,7 +47,7 @@
<td th:text="${item.key.id}"/> <td th:text="${item.key.id}"/>
<td th:text="${item.key.price}"/> <td th:text="${item.key.price}"/>
<td th:text="${item.key.cinema.name}"/> <td th:text="${item.key.cinema.name}"/>
<td th:text="${item.key.timestamp}"/> <td th:text="${item.key.dateTime}"/>
<td th:text="${item.value}"/> <td th:text="${item.value}"/>
<td> <td>
<div> <div>

View File

@ -30,7 +30,7 @@
</div> </div>
<div class="mb-3" th:if="${id == null}"> <div class="mb-3" th:if="${id == null}">
<label for="date" class="form-label">Дата</label> <label for="date" class="form-label">Дата</label>
<input type="datetime-local" class="form-control" id="date" th:field="${sessionDto.timestamp}" <input type="datetime-local" class="form-control" id="date" th:field="${sessionDto.dateTime}"
required="true"> required="true">
</div> </div>
<div class="mb-3"> <div class="mb-3">

View File

@ -31,7 +31,7 @@
<td th:text="${item.id}"/> <td th:text="${item.id}"/>
<td th:text="${item.price}"/> <td th:text="${item.price}"/>
<td th:text="${item.cinema.name}"/> <td th:text="${item.cinema.name}"/>
<td th:text="${item.timestamp}"/> <td th:text="${item.dateTime}"/>
<td th:text="${item.capacity} == null ? ${item.maxCount} : ${item.maxCount}-${item.capacity}"/> <td th:text="${item.capacity} == null ? ${item.maxCount} : ${item.maxCount}-${item.capacity}"/>
<td th:text="${item.maxCount}"/> <td th:text="${item.maxCount}"/>
<td> <td>

View File

@ -13,10 +13,10 @@
//import java.util.List; //import java.util.List;
// //
//@SpringBootTest //@SpringBootTest
//public class JpaCustomerTests { //public class JpaUserTests {
// private static final Logger log = LoggerFactory.getLogger(JpaCustomerTests.class); // private static final Logger log = LoggerFactory.getLogger(JpaUserTests.class);
// @Autowired // @Autowired
// private CustomerService customerService; // private UserService userService;
// @Autowired // @Autowired
// private SessionService sessionService; // private SessionService sessionService;
// @Autowired // @Autowired
@ -29,7 +29,7 @@
// sessionService.deleteAllSessions(); // sessionService.deleteAllSessions();
// cinemaService.deleteAllCinemas(); // cinemaService.deleteAllCinemas();
// orderService.deleteAllOrders(); // orderService.deleteAllOrders();
// customerService.deleteAllCustomers(); // userService.deleteAllUsers();
// // 2 кино // // 2 кино
// final Cinema cinema1 = cinemaService.addCinema("Меню"); // final Cinema cinema1 = cinemaService.addCinema("Меню");
// final Cinema cinema2 = cinemaService.addCinema("Аватар"); // final Cinema cinema2 = cinemaService.addCinema("Аватар");
@ -44,26 +44,26 @@
// Assertions.assertEquals(cinemaService // Assertions.assertEquals(cinemaService
// .findCinema(cinema1.getId()).getSessions().size(), 2); // .findCinema(cinema1.getId()).getSessions().size(), 2);
// // 1 покупатель // // 1 покупатель
// final Customer customer1 = customerService.addCustomer("Родион", "Иванов"); // final User user1 = userService.addUser("Родион", "Иванов");
// customerService.updateCustomer(customer1.getId(), "Пчел", "Пчелов"); // userService.updateUser(user1.getId(), "Пчел", "Пчелов");
// Assertions.assertEquals(customerService.findCustomer(customer1.getId()).getLogin(), "Пчел"); // Assertions.assertEquals(userService.findUser(user1.getId()).getLogin(), "Пчел");
// // 1 заказ, 1 копия заказа // // 1 заказ, 1 копия заказа
// final Order order0 = orderService.addOrder(customerService.findCustomer(customer1.getId()).getId()); // final Order order0 = orderService.addOrder(userService.findUser(user1.getId()).getId());
// final Order order1 = orderService.findOrder(order0.getId()); // final Order order1 = orderService.findOrder(order0.getId());
// Assertions.assertEquals(order0, order1); // Assertions.assertEquals(order0, order1);
// //
// // у клиента точно есть заказ? // // у клиента точно есть заказ?
// Assertions.assertEquals(customerService // Assertions.assertEquals(userService
// .findCustomer(customer1.getId()).getOrders().size(), 1); // .findUser(user1.getId()).getOrders().size(), 1);
// // 0 заказов // // 0 заказов
// orderService.deleteAllOrders(); // orderService.deleteAllOrders();
// Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(-1L)); // Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(-1L));
// // 2 покупателя // // 2 покупателя
// final Customer customer2 = customerService.addCustomer("Иннокентий", "Иванов"); // final User user2 = userService.addUser("Иннокентий", "Иванов");
// //
// // 1 заказ // // 1 заказ
// final Order order2 = orderService // final Order order2 = orderService
// .addOrder(customerService.findCustomer(customer2.getId()).getId()); // .addOrder(userService.findUser(user2.getId()).getId());
// // у заказа 2 сеанса // // у заказа 2 сеанса
// orderService.addSession(order2.getId(), session1.getId(), 2); // orderService.addSession(order2.getId(), session1.getId(), 2);
// //
@ -104,16 +104,16 @@
// //
// // создали 3 заказ у 2 покупателя // // создали 3 заказ у 2 покупателя
// final Order order3 = orderService // final Order order3 = orderService
// .addOrder(customerService.findCustomer(customer2.getId()).getId()); // .addOrder(userService.findUser(user2.getId()).getId());
// orderService.addSession(order3.getId(), session2.getId(), 2); // orderService.addSession(order3.getId(), session2.getId(), 2);
// orderService.addSession(order3.getId(), session3.getId(), 8); // orderService.addSession(order3.getId(), session3.getId(), 8);
// orderService.addSession(order3.getId(), session1.getId(), 8); // orderService.addSession(order3.getId(), session1.getId(), 8);
// // 2-ой покупатель удален // // 2-ой покупатель удален
// // 0 заказов после его удаления // // 0 заказов после его удаления
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 2); // Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 2);
// customerService.deleteCustomer(customer2.getId()); // userService.deleteUser(user2.getId());
// //
// Assertions.assertThrows(CustomerNotFoundException.class, () -> customerService.findCustomer(customer2.getId())); // Assertions.assertThrows(UserNotFoundException.class, () -> userService.findUser(user2.getId()));
// Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(order3.getId())); // Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(order3.getId()));
// Assertions.assertEquals(orderService.findAllOrders().size(), 0); // Assertions.assertEquals(orderService.findAllOrders().size(), 0);
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0); // Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);