надеюсь это все

This commit is contained in:
dasha 2023-04-15 13:25:42 +04:00
parent 0fafffd509
commit a794ee636f
18 changed files with 357 additions and 346 deletions

View File

@ -49,6 +49,7 @@ export default function Orders() {
const handleSubmitCreate = async (e) => {
e.preventDefault()
console.info('Try to add item');
const requestParams = {
method: "POST",
headers: {

View File

@ -16,7 +16,7 @@ public class Customer {
private String login;
@NotBlank(message = "password can't be null or empty")
private String password;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = CascadeType.REMOVE)
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = {CascadeType.MERGE,CascadeType.REMOVE})
private List<Order> orders;
public Customer() {

View File

@ -22,7 +22,12 @@ public class Order {
@JoinColumn(name = "customer_fk")
@JsonIgnore
private Customer customer;
@OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade =
{
CascadeType.REMOVE,
CascadeType.MERGE,
CascadeType.PERSIST
}, orphanRemoval = true)
private List<OrderSession> sessions;
public Order() {

View File

@ -26,11 +26,9 @@ public class OrderSession {
public OrderSession(Order order, Session session, Integer count) {
this.order = order;
this.id = new OrderSessionKey(session.getId(), order.getId());
this.id.setOrderId(order.getId());
this.id.setSessionId(session.getId());
this.session = session;
this.count = count;
this.id = new OrderSessionKey(session.getId(), order.getId());
}
public OrderSessionKey getId() {

View File

@ -19,7 +19,7 @@ public class Session {
@Column
@Temporal(TemporalType.TIMESTAMP)
private Timestamp timestamp;
@OneToMany(mappedBy = "session", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@OneToMany(mappedBy = "session", fetch = FetchType.EAGER)
private List<OrderSession> orders;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "cinema_fk")

View File

@ -8,8 +8,4 @@ import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
@Query("delete from Order p where p.customer.id = :id")
Optional<Customer> deleteCustomerOrders(@Param("id") Long id);
@Query()
void deleteAllCustomers();
}

View File

@ -1,10 +0,0 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Customer;
import java.util.Optional;
public interface CustomerRepositoryExtension {
Optional<Customer> deleteCustomerOrders(Long id);
void deleteAllCustomers();
}

View File

@ -1,24 +1,16 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Order;
import com.labwork1.app.student.model.OrderSession;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("insert into OrderSession values (orderId, sessionId, count) values (:sessionId, :orderId, :count)")
Order addSession(@Param("orderId") Long orderId, @Param("sessionId") Long sessionId,
@Param("count") Integer count);
@Query(value = "Select count from OrderSession where orderId = :orderId and sessionId = :sessionId",
nativeQuery = true)
Integer getCountOrderSession(@Param("orderId") Long orderId, @Param("sessionId") Long sessionId);
@Query(value = "delete from OrderSession where orderId = :orderId and sessionId = :sessionId",
nativeQuery = true)
@Query("Select os from OrderSession os where os.order.id = :orderId and os.session.id = :sessionId")
OrderSession getOrderSession(@Param("orderId") Long orderId, @Param("sessionId") Long sessionId);
@Modifying
@Query("delete from OrderSession os where os.order.id = :orderId and os.session.id = :sessionId")
void deleteSessionInOrder(@Param("orderId") Long orderId, @Param("sessionId") Long sessionId);
@Query(value = "update OrderSession set count = :count where orderId = :orderId and sessionId = :sessionId",
nativeQuery = true)
void updateSessionInOrder(@Param("orderId") Long orderId, @Param("sessionId") Long sessionId, @Param("count") Integer count);
}

View File

@ -1,11 +0,0 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Order;
import java.util.Optional;
public interface OrderRepositoryExtension {
Order addOrder(Order order, Long customerId);
Optional<Order> addSession(Long id, Long session, Integer count);
Optional<Order> deleteSessionInOrder(Long id, Long session, Integer count);
}

View File

@ -2,6 +2,11 @@ package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Session;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface SessionRepository extends JpaRepository<Session, Long>, SessionRepositoryExtension {
import java.util.List;
public interface SessionRepository extends JpaRepository<Session, Long> {
@Query("Select s from Session s where s.capacity > 0")
List<Session> findAllSessionsWithCapacity();
}

View File

@ -1,12 +0,0 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Session;
import java.util.List;
public interface SessionRepositoryExtension {
Session addSession(Session session, Long cinemaId);
Session deleteSession(Long id);
void deleteAllSessions();
List<Session> findAllSessionsWithCapacity();
}

View File

@ -1,67 +1,63 @@
package com.labwork1.app.student.repository.impl;
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.Session;
import com.labwork1.app.student.repository.CustomerRepository;
import com.labwork1.app.student.repository.CustomerRepositoryExtension;
import com.labwork1.app.student.repository.OrderRepository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import java.util.List;
import java.util.Optional;
public class CustomerRepositoryImpl implements CustomerRepositoryExtension {
@Autowired
@Lazy
private CustomerRepository customerRepository;
@Autowired
@Lazy
private OrderRepository orderRepository;
@PersistenceContext
private EntityManager em;
@Override
public Optional<Customer> deleteCustomerOrders(Long id) {
final Optional<Customer> currentCustomer = customerRepository.findById(id);
if (currentCustomer.isPresent()) {
final List<Order> currentCustomerOrders = currentCustomer.get().getOrders();
for (int i = 0; i < currentCustomerOrders.size(); i++) {
final Optional<Order> tempOrder = orderRepository.findById(currentCustomerOrders.get(i).getId());
if (tempOrder.isPresent()) {
final Order currentOrder = tempOrder.get();
List<OrderSession> orderSessionList = em
.createQuery("select p from OrderSession p where p.id.orderId = :id", OrderSession.class)
.setParameter("id", id)
.getResultList();
for (int j = 0; j < orderSessionList.size(); j++) {
final Session currentSession = orderSessionList.get(j).getSession();
currentOrder.getSessions().remove(orderSessionList.get(j));
currentSession.getOrders().remove(orderSessionList.get(j));
em.remove(orderSessionList.get(j));
em.merge(currentSession);
}
em.merge(currentOrder);
}
}
em.remove(currentCustomer.get());
}
return currentCustomer;
}
@Override
public void deleteAllCustomers() {
List<Customer> customers = em
.createQuery("select c from Customer c", Customer.class)
.getResultList();
for (var customer : customers) {
deleteCustomerOrders(customer.getId());
}
}
}
//package com.labwork1.app.student.repository.impl;
//
//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.Session;
//import com.labwork1.app.student.repository.CustomerRepository;
//import com.labwork1.app.student.repository.OrderRepository;
//import jakarta.persistence.EntityManager;
//import jakarta.persistence.PersistenceContext;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Lazy;
//
//import java.util.List;
//import java.util.Optional;
//
//public class CustomerRepositoryImpl {
// @Lazy
// private CustomerRepository customerRepository;
// @Lazy
// private OrderRepository orderRepository;
//
// @PersistenceContext
// private EntityManager em;
//
// public Optional<Customer> deleteCustomerOrders(Long id) {
// final Optional<Customer> currentCustomer = customerRepository.findById(id);
// if (currentCustomer.isPresent()) {
// final List<Order> currentCustomerOrders = currentCustomer.get().getOrders();
//
// for (int i = 0; i < currentCustomerOrders.size(); i++) {
// final Optional<Order> tempOrder = orderRepository.findById(currentCustomerOrders.get(i).getId());
// if (tempOrder.isPresent()) {
// final Order currentOrder = tempOrder.get();
// List<OrderSession> orderSessionList = em
// .createQuery("select p from OrderSession p where p.id.orderId = :id", OrderSession.class)
// .setParameter("id", id)
// .getResultList();
// for (int j = 0; j < orderSessionList.size(); j++) {
// final Session currentSession = orderSessionList.get(j).getSession();
// currentOrder.getSessions().remove(orderSessionList.get(j));
// currentSession.getOrders().remove(orderSessionList.get(j));
// em.remove(orderSessionList.get(j));
// em.merge(currentSession);
// }
// em.merge(currentOrder);
// }
// }
// em.remove(currentCustomer.get());
// }
// return currentCustomer;
// }
//
//
// public void deleteAllCustomers() {
// List<Customer> customers = em
// .createQuery("select c from Customer c", Customer.class)
// .getResultList();
// for (var customer : customers) {
// deleteCustomerOrders(customer.getId());
// }
// }
//}

View File

@ -1,105 +1,104 @@
package com.labwork1.app.student.repository.impl;
import com.labwork1.app.student.model.*;
import com.labwork1.app.student.repository.CustomerRepository;
import com.labwork1.app.student.repository.OrderRepository;
import com.labwork1.app.student.repository.OrderRepositoryExtension;
import com.labwork1.app.student.repository.SessionRepository;
import com.labwork1.app.student.service.CustomerNotFoundException;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
public class OrderRepositoryImpl implements OrderRepositoryExtension {
@Autowired
@Lazy
private CustomerRepository customerRepository;
@Autowired
@Lazy
private OrderRepository orderRepository;
@Autowired
@Lazy
private SessionRepository sessionRepository;
@PersistenceContext
private EntityManager em;
@Override
public Order addOrder(Order order, Long customerId) {
final Optional<Customer> customer = customerRepository.findById(customerId);
if (customer.isEmpty()) {
throw new CustomerNotFoundException(customerId);
}
order.setCustomer(customer.get());
em.persist(order);
em.merge(customer.get());
return order;
}
@Override
@Transactional
public Optional<Order> addSession(Long id, Long session, Integer count) {
if (session <= 0 || count <= 0) {
throw new IllegalArgumentException("addOrder empty fields");
}
Optional<Order> optionalOrder = orderRepository.findById(id);
Optional<Session> optionalSession = sessionRepository.findById(session);
if (optionalOrder.isEmpty() || optionalSession.isEmpty()) {
return optionalOrder;
}
final Session currentSession = optionalSession.get();
final Order currentOrder = optionalOrder.get();
OrderSession orderSession = em.find(OrderSession.class,
new OrderSessionKey(currentSession.getId(), currentOrder.getId()));
if (currentSession.getCapacity() < count ||
(orderSession != null && orderSession.getCount() + count > currentSession.getMaxCount())) {
throw new IllegalArgumentException(String.format("No more tickets in session. Capacity: %1$s. Count: %2$s",
currentSession.getCapacity(), count));
}
if (orderSession == null)
orderSession = new OrderSession(currentOrder, currentSession, count);
else if (orderSession.getCount() + count <= currentSession.getMaxCount()) {
orderSession.setCount(orderSession.getCount() + count);
}
currentOrder.addSession(orderSession);
currentSession.addOrder(orderSession);
currentSession.setCapacity(currentSession.getCapacity() - count);
em.merge(currentSession);
em.merge(currentOrder);
em.merge(orderSession);
return orderRepository.findById(id);
}
@Override
public Optional<Order> deleteSessionInOrder(Long id, Long session, Integer count) {
final Optional<Order> optionalOrder = orderRepository.findById(id);
final Optional<Session> optionalSession = sessionRepository.findById(session);
if (optionalOrder.isEmpty() || optionalSession.isEmpty()) {
return optionalOrder;
}
final Order currentOrder = optionalOrder.get();
final Session currentSession = optionalSession.get();
OrderSession orderSession = em.find(OrderSession.class, new OrderSessionKey(session, id));
if (orderSession == null)
return optionalOrder;
if (count >= orderSession.getCount()) {
currentOrder.getSessions().remove(orderSession);
currentSession.getOrders().remove(orderSession);
currentSession.setCapacity(currentSession.getCapacity() + orderSession.getCount());
em.remove(orderSession);
} else {
orderSession.setCount(orderSession.getCount() - count);
currentSession.setCapacity(currentSession.getMaxCount() - orderSession.getCount());
em.merge(orderSession);
em.merge(currentSession);
}
return orderRepository.findById(id);
}
}
//package com.labwork1.app.student.repository.impl;
//
//import com.labwork1.app.student.model.*;
//import com.labwork1.app.student.repository.CustomerRepository;
//import com.labwork1.app.student.repository.OrderRepository;
//import com.labwork1.app.student.repository.SessionRepository;
//import com.labwork1.app.student.service.CustomerNotFoundException;
//import jakarta.persistence.EntityManager;
//import jakarta.persistence.PersistenceContext;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Lazy;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.Optional;
//
//public class OrderRepositoryImpl {
//
// @Lazy
// private CustomerRepository customerRepository;
//
// @Lazy
// private OrderRepository orderRepository;
//
// @Lazy
// private SessionRepository sessionRepository;
// @PersistenceContext
// private EntityManager em;
//
// public Order addOrder(Order order, Long customerId) {
// final Optional<Customer> customer = customerRepository.findById(customerId);
// if (customer.isEmpty()) {
// throw new CustomerNotFoundException(customerId);
// }
// order.setCustomer(customer.get());
// em.persist(order);
// em.merge(customer.get());
// return order;
// }
//
//
// @Transactional
// public Optional<Order> addSession(Long id, Long session, Integer count) {
// if (session <= 0 || count <= 0) {
// throw new IllegalArgumentException("addOrder empty fields");
// }
// Optional<Order> optionalOrder = orderRepository.findById(id);
// Optional<Session> optionalSession = sessionRepository.findById(session);
// if (optionalOrder.isEmpty() || optionalSession.isEmpty()) {
// return optionalOrder;
// }
// final Session currentSession = optionalSession.get();
// final Order currentOrder = optionalOrder.get();
// OrderSession orderSession = em.find(OrderSession.class,
// new OrderSessionKey(currentSession.getId(), currentOrder.getId()));
//
// if (currentSession.getCapacity() < count ||
// (orderSession != null && orderSession.getCount() + count > currentSession.getMaxCount())) {
// throw new IllegalArgumentException(String.format("No more tickets in session. Capacity: %1$s. Count: %2$s",
// currentSession.getCapacity(), count));
// }
// if (orderSession == null)
// orderSession = new OrderSession(currentOrder, currentSession, count);
// else if (orderSession.getCount() + count <= currentSession.getMaxCount()) {
// orderSession.setCount(orderSession.getCount() + count);
// }
//
// currentOrder.addSession(orderSession);
// currentSession.addOrder(orderSession);
// currentSession.setCapacity(currentSession.getCapacity() - count);
// em.merge(currentSession);
// em.merge(currentOrder);
// em.merge(orderSession);
// return orderRepository.findById(id);
// }
//
// @Override
// public Optional<Order> deleteSessionInOrder(Long id, Long session, Integer count) {
// final Optional<Order> optionalOrder = orderRepository.findById(id);
// final Optional<Session> optionalSession = sessionRepository.findById(session);
// if (optionalOrder.isEmpty() || optionalSession.isEmpty()) {
// return optionalOrder;
// }
// final Order currentOrder = optionalOrder.get();
// final Session currentSession = optionalSession.get();
//
// OrderSession orderSession = em.find(OrderSession.class, new OrderSessionKey(session, id));
// if (orderSession == null)
// return optionalOrder;
//
// if (count >= orderSession.getCount()) {
// currentOrder.getSessions().remove(orderSession);
// currentSession.getOrders().remove(orderSession);
// currentSession.setCapacity(currentSession.getCapacity() + orderSession.getCount());
// em.remove(orderSession);
// } else {
// orderSession.setCount(orderSession.getCount() - count);
// currentSession.setCapacity(currentSession.getMaxCount() - orderSession.getCount());
// em.merge(orderSession);
// em.merge(currentSession);
// }
//
// return orderRepository.findById(id);
// }
//}

View File

@ -1,74 +1,73 @@
package com.labwork1.app.student.repository.impl;
import com.labwork1.app.student.model.Cinema;
import com.labwork1.app.student.model.OrderSession;
import com.labwork1.app.student.model.Session;
import com.labwork1.app.student.repository.CinemaRepository;
import com.labwork1.app.student.repository.SessionRepository;
import com.labwork1.app.student.repository.SessionRepositoryExtension;
import com.labwork1.app.student.service.CinemaNotFoundException;
import com.labwork1.app.student.service.SessionNotFoundException;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import java.util.List;
import java.util.Optional;
public class SessionRepositoryImpl implements SessionRepositoryExtension {
@Autowired
@Lazy
private SessionRepository sessionRepository;
@Autowired
@Lazy
private CinemaRepository cinemaRepository;
@PersistenceContext
private EntityManager em;
@Override
public Session addSession(Session session, Long cinemaId) {
if (session == null) return null;
final Optional<Cinema> cinema = cinemaRepository.findById(cinemaId);
if (cinema.isEmpty()) {
throw new CinemaNotFoundException(cinemaId);
}
session.setCinema(cinema.get());
em.persist(session);
em.merge(cinema.get());
return session;
}
@Override
public Session deleteSession(Long id) {
final Optional<Session> optionalSession = sessionRepository.findById(id);
if (optionalSession.isEmpty()) {
throw new SessionNotFoundException(id);
}
final Session currentSession = optionalSession.get();
int size = currentSession.getOrders().size();
for (int i = 0; i < size; i++) {
OrderSession temp = currentSession.getOrders().get(0);
temp.getSession().removeOrder(temp);
temp.getOrder().removeSession(temp);
em.remove(temp);
}
em.remove(currentSession);
return currentSession;
}
@Override
public void deleteAllSessions() {
List<Session> sessions = em
.createQuery("select s from Session s", Session.class)
.getResultList();
for (var session : sessions) {
deleteSession(session.getId());
}
}
@Override
public List<Session> findAllSessionsWithCapacity() {
return em.createQuery("select t from Session t where capacity > 0", Session.class)
.getResultList();
}
}
//package com.labwork1.app.student.repository.impl;
//
//import com.labwork1.app.student.model.Cinema;
//import com.labwork1.app.student.model.OrderSession;
//import com.labwork1.app.student.model.Session;
//import com.labwork1.app.student.repository.CinemaRepository;
//import com.labwork1.app.student.repository.SessionRepository;
//import com.labwork1.app.student.service.CinemaNotFoundException;
//import com.labwork1.app.student.service.SessionNotFoundException;
//import jakarta.persistence.EntityManager;
//import jakarta.persistence.PersistenceContext;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Lazy;
//
//import java.util.List;
//import java.util.Optional;
//
//public class SessionRepositoryImpl implements SessionRepositoryExtension {
// @Autowired
// @Lazy
// private SessionRepository sessionRepository;
// @Autowired
// @Lazy
// private CinemaRepository cinemaRepository;
// @PersistenceContext
// private EntityManager em;
// @Override
// public Session addSession(Session session, Long cinemaId) {
// if (session == null) return null;
// final Optional<Cinema> cinema = cinemaRepository.findById(cinemaId);
// if (cinema.isEmpty()) {
// throw new CinemaNotFoundException(cinemaId);
// }
// session.setCinema(cinema.get());
// em.persist(session);
// em.merge(cinema.get());
// return session;
// }
//
// @Override
// public Session deleteSession(Long id) {
// final Optional<Session> optionalSession = sessionRepository.findById(id);
// if (optionalSession.isEmpty()) {
// throw new SessionNotFoundException(id);
// }
// final Session currentSession = optionalSession.get();
// int size = currentSession.getOrders().size();
// for (int i = 0; i < size; i++) {
// OrderSession temp = currentSession.getOrders().get(0);
// temp.getSession().removeOrder(temp);
// temp.getOrder().removeSession(temp);
// em.remove(temp);
// }
// em.remove(currentSession);
// return currentSession;
// }
//
// @Override
// public void deleteAllSessions() {
// List<Session> sessions = em
// .createQuery("select s from Session s", Session.class)
// .getResultList();
// for (var session : sessions) {
// deleteSession(session.getId());
// }
// }
//
// @Override
// public List<Session> findAllSessionsWithCapacity() {
// return em.createQuery("select t from Session t where capacity > 0", Session.class)
// .getResultList();
// }
//}

View File

@ -1,6 +1,8 @@
package com.labwork1.app.student.service;
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.repository.CustomerRepository;
import com.labwork1.app.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
@ -12,11 +14,12 @@ import java.util.Optional;
@Service
public class CustomerService {
private final CustomerRepository customerRepository;
private final SessionService sessionService;
private final ValidatorUtil validatorUtil;
public CustomerService(CustomerRepository customerRepository,
ValidatorUtil validatorUtil) {
public CustomerService(CustomerRepository customerRepository, SessionService sessionService, ValidatorUtil validatorUtil) {
this.customerRepository = customerRepository;
this.sessionService = sessionService;
this.validatorUtil = validatorUtil;
}
@ -49,12 +52,25 @@ public class CustomerService {
@Transactional
public Customer deleteCustomer(Long id) {
final Optional<Customer> customer = customerRepository.deleteCustomerOrders(id);
return customer.orElseThrow(() -> new CustomerNotFoundException(id));
final Customer customer = findCustomer(id);
// заказы покупателя
final List<Order> orders = customer.getOrders();
for (Order order : orders) {
// сеансы в заказе
for (OrderSession orderSession : order.getSessions()) {
// освобождаем сеансы
sessionService.updateSession(orderSession.getSession().getId(),
orderSession.getSession().getPrice(), orderSession.getSession().getMaxCount());
}
}
customerRepository.deleteById(id);
return customer;
}
@Transactional
public void deleteAllCustomers() {
customerRepository.deleteAllCustomers();
customerRepository.deleteAll();
}
}

View File

@ -36,29 +36,28 @@ public class OrderService {
@Transactional
public Order addSession(Long id, Long sessionId, Integer count) {
Optional<Order> optionalOrder = orderRepository.findById(id);
final Session currentSession = sessionService.findSession(sessionId);
if (optionalOrder.isEmpty()) {
throw new OrderNotFoundException(id);
}
Order currentOrder = optionalOrder.get();
final Integer countOrderSession = orderRepository.getCountOrderSession(id, sessionId);
final Order currentOrder = findOrder(id);
final OrderSession currentOrderSession = orderRepository.getOrderSession(id, sessionId);
if (currentSession.getCapacity() < count ||
(countOrderSession != null && countOrderSession + count > currentSession.getMaxCount())) {
throw new IllegalArgumentException(String.format("No more tickets in sessionId. Capacity: %1$s. Count: %2$s",
(currentOrderSession != null && currentOrderSession.getCount() + count > currentSession.getMaxCount())) {
throw new IllegalArgumentException(String.format("No more tickets in session. Capacity: %1$s. Count: %2$s",
currentSession.getCapacity(), count));
}
if (countOrderSession == null) {
currentSession.setCapacity(currentSession.getCapacity() - count);
/*final Session updatedSession = sessionService.updateSession(currentSession.getId(),
currentSession.getPrice(), currentSession.getCapacity() - count);*/
if (currentOrderSession == null) {
currentOrder.addSession(new OrderSession(currentOrder, currentSession, count));
return orderRepository.save(currentOrder);
}
else if (countOrderSession + count <= currentSession.getMaxCount()) {
orderRepository.delete(currentOrder);
orderRepository.addSession(id, sessionId, countOrderSession + count);
else if (currentOrderSession.getCount() + count <= currentSession.getMaxCount()) {
currentOrder.removeSession(currentOrderSession);
currentOrder.addSession(new OrderSession(currentOrder, currentSession,
currentOrderSession.getCount() + count));
}
return optionalOrder.get();
return orderRepository.save(currentOrder);
}
@Transactional(readOnly = true)
@ -75,24 +74,38 @@ public class OrderService {
@Transactional
public Order deleteOrder(Long id) {
final Order currentOrder = findOrder(id);
// сеансы в заказе
for (OrderSession orderSession : currentOrder.getSessions()) {
// освобождаем сеансы
sessionService.updateSession(orderSession.getSession().getId(),
orderSession.getSession().getPrice(), orderSession.getSession().getMaxCount());
}
orderRepository.delete(currentOrder);
return currentOrder;
}
@Transactional
public void deleteSessionInOrder(Long id, Long session, Integer count) {
public Order deleteSessionInOrder(Long id, Long session, Integer count) {
final Order currentOrder = findOrder(id);
final Session currentSession = sessionService.findSession(session);
Integer countOrderSession = orderRepository.getCountOrderSession(id, session);
if (countOrderSession == null)
final OrderSession currentOrderSession = orderRepository.getOrderSession(id, session);
if (currentOrderSession == null)
throw new EntityNotFoundException();
if (count >= countOrderSession) {
orderRepository.deleteSessionInOrder(id, session);
if (count >= currentOrderSession.getCount()) {
currentOrder.removeSession(currentOrderSession);
sessionService.updateSession(session, currentSession.getPrice(),
currentSession.getCapacity() + countOrderSession);
currentSession.getCapacity() + currentOrderSession.getCount());
}
else
orderRepository.updateSessionInOrder(id, session, count);
else {
currentOrder.removeSession(currentOrderSession);
currentSession.setCapacity(currentSession.getCapacity() + count);
currentOrder.addSession(new OrderSession(currentOrder, currentSession,
currentOrderSession.getCount() - count));
}
return orderRepository.save(currentOrder);
}
@Transactional

View File

@ -1,5 +1,6 @@
package com.labwork1.app.student.service;
import com.labwork1.app.student.model.Cinema;
import com.labwork1.app.student.model.Session;
import com.labwork1.app.student.repository.SessionRepository;
import com.labwork1.app.util.validation.ValidatorUtil;
@ -7,24 +8,29 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
@Service
public class SessionService {
private final SessionRepository sessionRepository;
private final CinemaService cinemaService;
private final ValidatorUtil validatorUtil;
public SessionService(SessionRepository sessionRepository,
ValidatorUtil validatorUtil) {
CinemaService cinemaService, ValidatorUtil validatorUtil) {
this.sessionRepository = sessionRepository;
this.cinemaService = cinemaService;
this.validatorUtil = validatorUtil;
}
@Transactional
public Session addSession(Double price, Timestamp date, Long cinemaId, Integer capacity) {
final Session session = new Session(price, date, capacity);
final Cinema cinema = cinemaService.findCinema(cinemaId);
session.setCinema(cinema);
validatorUtil.validate(session);
return sessionRepository.addSession(session, cinemaId);
return sessionRepository.save(session);
}
@Transactional(readOnly = true)
@ -42,6 +48,7 @@ public class SessionService {
public Session updateSession(Long id, Double price, Integer capacity) {
final Session currentSession = findSession(id);
currentSession.setPrice(price);
// для обновления полей класса (цены)
if (capacity != -1)
currentSession.setCapacity(capacity);
validatorUtil.validate(currentSession);
@ -50,12 +57,18 @@ public class SessionService {
@Transactional
public Session deleteSession(Long id) {
return sessionRepository.deleteSession(id);
final Session currentSession = findSession(id);
// все равно сеанс не удалился бы, который участвует в заказах
// для отслеживания операции с ошибкой
if (currentSession.getOrders().size() > 0)
throw new IllegalArgumentException();
sessionRepository.delete(currentSession);
return currentSession;
}
@Transactional
public void deleteAllSessions() {
sessionRepository.deleteAllSessions();
sessionRepository.deleteAll();
}
@Transactional

View File

@ -11,9 +11,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import java.sql.Timestamp;
import java.util.List;
@SpringBootTest
public class JpaCustomerTests {
@ -73,7 +73,7 @@ public class JpaCustomerTests {
orderService.addSession(order2.getId(), session2.getId(), 5);
Assertions.assertEquals(sessionService.findSession(session2.getId()).getCapacity(), 5);
Assertions.assertThrows(InvalidDataAccessApiUsageException.class, () ->
Assertions.assertThrows(IllegalArgumentException.class, () ->
orderService.addSession(order2.getId(), session2.getId(), 6));
// у заказа 1 сеанс
@ -100,22 +100,33 @@ public class JpaCustomerTests {
// 3 сеанса всего
final Session session3 = sessionService.addSession(300.0,
new Timestamp(System.currentTimeMillis()), cinema2.getId(), 10);
// осталось 2 сеанса, у заказа2 0 сеансов
sessionService.deleteSession(session1.getId());
Assertions.assertEquals(sessionService.findAllSessions().size(), 2);
// удалили заказ2, у которого был сеанс1
orderService.deleteOrder(order2.getId());
Assertions.assertEquals(orderService.findAllOrders().size(), 0);
Assertions.assertEquals(sessionService.findAllSessions().size(), 3);
Assertions.assertEquals(orderService
.findOrder(order2.getId()).getSessions().size(), 0);
// создали 3 заказ у 2 покупателя
final Order order3 = orderService
.addOrder(customerService.findCustomer(customer2.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(orderService.findAllOrders().size(), 1);
Assertions.assertEquals(sessionService.findSession(session2.getId()).getCapacity(), 8);
customerService.deleteCustomer(customer2.getId());
Assertions.assertThrows(CustomerNotFoundException.class, () -> customerService.findCustomer(customer2.getId()));
Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(order2.getId()));
Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(order3.getId()));
Assertions.assertEquals(orderService.findAllOrders().size(), 0);
Assertions.assertEquals(sessionService.findSession(session2.getId()).getCapacity(), 10);
Assertions.assertEquals(sessionService.findSession(session3.getId()).getCapacity(), 10);
Assertions.assertEquals(sessionService.findSession(session3.getId()), session3);
Assertions.assertEquals(cinemaService.findAllCinemas().size(), 2);
Assertions.assertEquals(sessionService.findAllSessions().size(), 3);
// у синема1 1 и 2 сеанс, у синема2 3 сеанс. он удален
cinemaService.deleteCinema(cinema2.getId());
Assertions.assertEquals(cinemaService.findAllCinemas().size(), 1);
Assertions.assertEquals(sessionService.findAllSessions().size(), 2);
}
}