сейв
This commit is contained in:
parent
a41fcf5618
commit
76adccc186
@ -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 = (
|
||||
<>
|
||||
<select required className="form-select" name="customer" id="customer" value={customer.value} onChange={e => {
|
||||
setCustomerName(e.target.value)
|
||||
getCustomerOrders(e.target.value)
|
||||
<select required className="form-select" name="user" id="user" value={user.value} onChange={e => {
|
||||
setUserName(e.target.value)
|
||||
getUserOrders(e.target.value)
|
||||
}} >
|
||||
<option value='' defaultValue disabled>Выберите значение</option>
|
||||
{customer ? customer.map(elem =>
|
||||
{user ? user.map(elem =>
|
||||
<option key={elem.id} value={elem.id}>{elem.login}</option>
|
||||
) : null}
|
||||
</select>
|
||||
@ -176,7 +176,7 @@ export default function Orders() {
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">#</th>
|
||||
<th scope="col">Customer</th>
|
||||
<th scope="col">User</th>
|
||||
<th scope="col">DateOfPurchase</th>
|
||||
<th scope="col"></th>
|
||||
</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)} >
|
||||
<option value='' defaultValue disabled>Выберите значение</option>
|
||||
{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}
|
||||
</select>
|
||||
</div>
|
||||
|
@ -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")
|
||||
|
@ -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 ? <label className="fs-6 text-danger">Неправильный ввод цены</label> : null}
|
||||
<div>
|
||||
<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>
|
||||
{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>
|
||||
<button className="btn btn-success my-3" type="button" onClick={handleSubmit}>Сохранить</button>
|
||||
</div>
|
||||
|
@ -5,7 +5,7 @@ export default function OrderItem(props) {
|
||||
return (
|
||||
<tr>
|
||||
<td>{props.item.id}</td>
|
||||
<td>{props.item.customer}</td>
|
||||
<td>{props.item.user}</td>
|
||||
<td>{props.item.dateOfPurchase}</td>
|
||||
<td><MyButton value={props} /></td>
|
||||
</tr>
|
||||
|
@ -8,7 +8,7 @@ export default function OrderSessionItem(props) {
|
||||
<td>{props.item.session.id}</td>
|
||||
<td>{props.item.session.price}</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><MyButton value={props} /></td>
|
||||
</tr>
|
||||
|
@ -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 (
|
||||
<tr>
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
|
@ -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));
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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";
|
||||
}
|
||||
}
|
@ -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}")
|
||||
|
@ -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<OrderSessionDto> 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<OrderSessionDto> 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<OrderSessionDto> getSessions() {
|
||||
|
@ -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<OrderSessionDto> 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";
|
||||
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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";
|
||||
}
|
||||
|
@ -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));
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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";
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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) {
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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<OrderSession> orders;
|
||||
@OneToMany(mappedBy = "session", fetch = FetchType.EAGER)
|
||||
private List<UserSession> 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<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
|
||||
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<OrderSession> getOrders() {
|
||||
|
@ -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<Order> orders;
|
||||
@OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade =
|
||||
{
|
||||
CascadeType.REMOVE,
|
||||
CascadeType.MERGE,
|
||||
CascadeType.PERSIST
|
||||
}, orphanRemoval = true)
|
||||
private List<UserSession> 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<UserSession> getSessions() {
|
||||
return sessions;
|
||||
}
|
||||
|
||||
public List<Order> getOrders() {
|
||||
return orders;
|
||||
}
|
||||
|
||||
public void setOrder(Order order) {
|
||||
if (order.getCustomer().equals(this)) {
|
||||
if (order.getUser().equals(this)) {
|
||||
this.orders.add(order);
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
@ -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);
|
||||
}
|
@ -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));
|
||||
}
|
||||
}
|
@ -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()));
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
|
@ -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));
|
||||
}
|
||||
}
|
160
src/main/java/com/labwork1/app/student/service/UserService.java
Normal file
160
src/main/java/com/labwork1/app/student/service/UserService.java
Normal 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()));
|
||||
}
|
||||
}
|
@ -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,
|
||||
|
@ -8,21 +8,21 @@
|
||||
<div layout:fragment="content_header">Пользователь</div>
|
||||
<div layout:fragment="content">
|
||||
<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">
|
||||
<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 class="mb-3">
|
||||
<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 class="mb-3">
|
||||
<button type="submit" class="btn btn-primary button-fixed">
|
||||
<span th:if="${id == null}">Добавить</span>
|
||||
<span th:if="${id != null}">Обновить</span>
|
||||
</button>
|
||||
<a class="btn btn-secondary button-fixed" th:href="@{/customer}">
|
||||
<a class="btn btn-secondary button-fixed" th:href="@{/user}">
|
||||
Назад
|
||||
</a>
|
||||
</div>
|
||||
|
@ -17,23 +17,23 @@
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr th:each="customer, iterator: ${customers}">
|
||||
<td th:text="${customer.id}"/>
|
||||
<td th:text="${customer.login}"/>
|
||||
<td th:text="${customer.password}"/>
|
||||
<td th:text="${customer.role}"/>
|
||||
<tr th:each="user, iterator: ${users}">
|
||||
<td th:text="${user.id}"/>
|
||||
<td th:text="${user.login}"/>
|
||||
<td th:text="${user.password}"/>
|
||||
<td th:text="${user.role}"/>
|
||||
<td>
|
||||
<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>
|
||||
</a>
|
||||
<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>
|
||||
</a>
|
||||
</div>
|
||||
<form th:action="@{/customer/delete/{id}(id=${customer.id})}" method="post">
|
||||
<button th:id="'remove-' + ${customer.id}" type="submit" style="display: none">
|
||||
<form th:action="@{/user/delete/{id}(id=${user.id})}" method="post">
|
||||
<button th:id="'remove-' + ${user.id}" type="submit" style="display: none">
|
||||
Удалить
|
||||
</button>
|
||||
</form>
|
||||
@ -44,9 +44,9 @@
|
||||
<div th:if="${totalPages > 0}" class="pagination">
|
||||
<span style="float: left; padding: 5px 5px;">Страницы:</span>
|
||||
<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:class="${page == customers.number + 1} ? active">
|
||||
th:class="${page == users.number + 1} ? active">
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -32,7 +32,7 @@
|
||||
<ul class="navbar-nav" sec:authorize="isAuthenticated()">
|
||||
<a class="nav-link" href="/">Главная</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="/session">Сеансы</a>
|
||||
<a class="nav-link" href="/h2-console/" target="_blank" sec:authorize="hasRole('ROLE_ADMIN')">Консоль H2</a>
|
||||
|
@ -17,7 +17,7 @@
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">ID</th>
|
||||
<th scope="col">Customer</th>
|
||||
<th scope="col">User</th>
|
||||
<th scope="col">DateOfPurchase</th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
@ -25,7 +25,7 @@
|
||||
<tbody>
|
||||
<tr th:each="item, iterator: ${orders}">
|
||||
<td th:text="${item.id}"/>
|
||||
<td th:text="${item.customer}"/>
|
||||
<td th:text="${item.user}"/>
|
||||
<td th:text="${item.dateOfPurchase}"/>
|
||||
<td>
|
||||
<div>
|
||||
|
@ -13,7 +13,7 @@
|
||||
<select id="session" class="form-select" th:name="session" required="true">
|
||||
<option th:each="value: ${sessions}"
|
||||
th:value="${value.id}"
|
||||
th:text="${value.cinema.name} + ' ' + ${value.timestamp}">
|
||||
th:text="${value.cinema.name} + ' ' + ${value.dateTime}">
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
@ -47,7 +47,7 @@
|
||||
<td th:text="${item.key.id}"/>
|
||||
<td th:text="${item.key.price}"/>
|
||||
<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>
|
||||
<div>
|
||||
|
@ -30,7 +30,7 @@
|
||||
</div>
|
||||
<div class="mb-3" th:if="${id == null}">
|
||||
<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">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
|
@ -31,7 +31,7 @@
|
||||
<td th:text="${item.id}"/>
|
||||
<td th:text="${item.price}"/>
|
||||
<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.maxCount}"/>
|
||||
<td>
|
||||
|
@ -13,10 +13,10 @@
|
||||
//import java.util.List;
|
||||
//
|
||||
//@SpringBootTest
|
||||
//public class JpaCustomerTests {
|
||||
// private static final Logger log = LoggerFactory.getLogger(JpaCustomerTests.class);
|
||||
//public class JpaUserTests {
|
||||
// private static final Logger log = LoggerFactory.getLogger(JpaUserTests.class);
|
||||
// @Autowired
|
||||
// private CustomerService customerService;
|
||||
// private UserService userService;
|
||||
// @Autowired
|
||||
// private SessionService sessionService;
|
||||
// @Autowired
|
||||
@ -29,7 +29,7 @@
|
||||
// sessionService.deleteAllSessions();
|
||||
// cinemaService.deleteAllCinemas();
|
||||
// orderService.deleteAllOrders();
|
||||
// customerService.deleteAllCustomers();
|
||||
// userService.deleteAllUsers();
|
||||
// // 2 кино
|
||||
// final Cinema cinema1 = cinemaService.addCinema("Меню");
|
||||
// final Cinema cinema2 = cinemaService.addCinema("Аватар");
|
||||
@ -44,26 +44,26 @@
|
||||
// Assertions.assertEquals(cinemaService
|
||||
// .findCinema(cinema1.getId()).getSessions().size(), 2);
|
||||
// // 1 покупатель
|
||||
// final Customer customer1 = customerService.addCustomer("Родион", "Иванов");
|
||||
// customerService.updateCustomer(customer1.getId(), "Пчел", "Пчелов");
|
||||
// Assertions.assertEquals(customerService.findCustomer(customer1.getId()).getLogin(), "Пчел");
|
||||
// final User user1 = userService.addUser("Родион", "Иванов");
|
||||
// userService.updateUser(user1.getId(), "Пчел", "Пчелов");
|
||||
// Assertions.assertEquals(userService.findUser(user1.getId()).getLogin(), "Пчел");
|
||||
// // 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());
|
||||
// Assertions.assertEquals(order0, order1);
|
||||
//
|
||||
// // у клиента точно есть заказ?
|
||||
// Assertions.assertEquals(customerService
|
||||
// .findCustomer(customer1.getId()).getOrders().size(), 1);
|
||||
// Assertions.assertEquals(userService
|
||||
// .findUser(user1.getId()).getOrders().size(), 1);
|
||||
// // 0 заказов
|
||||
// orderService.deleteAllOrders();
|
||||
// Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(-1L));
|
||||
// // 2 покупателя
|
||||
// final Customer customer2 = customerService.addCustomer("Иннокентий", "Иванов");
|
||||
// final User user2 = userService.addUser("Иннокентий", "Иванов");
|
||||
//
|
||||
// // 1 заказ
|
||||
// final Order order2 = orderService
|
||||
// .addOrder(customerService.findCustomer(customer2.getId()).getId());
|
||||
// .addOrder(userService.findUser(user2.getId()).getId());
|
||||
// // у заказа 2 сеанса
|
||||
// orderService.addSession(order2.getId(), session1.getId(), 2);
|
||||
//
|
||||
@ -104,16 +104,16 @@
|
||||
//
|
||||
// // создали 3 заказ у 2 покупателя
|
||||
// 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(), session3.getId(), 8);
|
||||
// orderService.addSession(order3.getId(), session1.getId(), 8);
|
||||
// // 2-ой покупатель удален
|
||||
// // 0 заказов после его удаления
|
||||
// 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.assertEquals(orderService.findAllOrders().size(), 0);
|
||||
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
|
||||
|
Loading…
Reference in New Issue
Block a user