76 lines
2.6 KiB
Java
76 lines
2.6 KiB
Java
package SuMoC.backend.trip;
|
|
|
|
|
|
import SuMoC.backend.trip.dtos.NewTripDTO;
|
|
import SuMoC.backend.trip.dtos.TripDTO;
|
|
import SuMoC.backend.trip.models.Trip;
|
|
import SuMoC.backend.user.models.User;
|
|
import jakarta.transaction.Transactional;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.http.HttpStatus;
|
|
import org.springframework.stereotype.Service;
|
|
import org.springframework.web.server.ResponseStatusException;
|
|
|
|
import java.util.List;
|
|
|
|
@Service
|
|
@Transactional
|
|
public class TripService {
|
|
private final TripRepository tripRepository;
|
|
private final TripMapper tripMapper;
|
|
|
|
@Autowired
|
|
public TripService(TripRepository tripRepository,
|
|
TripMapper tripMapper
|
|
) {
|
|
this.tripRepository = tripRepository;
|
|
this.tripMapper = tripMapper;
|
|
}
|
|
|
|
public void invalidateTrip(User user, Long tripId) {
|
|
Trip trip = tripRepository.findById(tripId)
|
|
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Trip not found"));
|
|
if (!trip.getUser().equals(user)) {
|
|
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Trip does not belong to user");
|
|
}
|
|
trip.setInvalidated(true);
|
|
tripRepository.save(trip);
|
|
}
|
|
|
|
public void validateTrip(User user, Long tripId) {
|
|
Trip trip = tripRepository.findById(tripId)
|
|
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Trip not found"));
|
|
if (!trip.getUser().equals(user)) {
|
|
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Trip does not belong to user");
|
|
}
|
|
trip.setInvalidated(false);
|
|
tripRepository.save(trip);
|
|
}
|
|
|
|
public Trip addTrip(User user, NewTripDTO newTripDTO) {
|
|
Trip trip = tripMapper.toTrip(newTripDTO);
|
|
trip.setUser(user);
|
|
trip.getTripSegments().forEach(tripSegment -> tripSegment.setTrip(trip));
|
|
tripRepository.save(trip);
|
|
return trip;
|
|
}
|
|
|
|
public List<TripDTO> getAllTripsOfUser(User user) {
|
|
List<Trip> trips = tripRepository.findAllByUser(user).orElseThrow();
|
|
return tripMapper.toTripDTOs(trips);
|
|
}
|
|
|
|
public void deleteTrip(User user, Long tripId) {
|
|
Trip trip = tripRepository.findById(tripId)
|
|
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Trip not found"));
|
|
if (!trip.getUser().equals(user)) {
|
|
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Trip does not belong to user");
|
|
}
|
|
tripRepository.delete(trip);
|
|
}
|
|
|
|
public void deleteAllTripsOfUser(User user) {
|
|
tripRepository.deleteAllByUser(user);
|
|
}
|
|
}
|