Update src/main/java/com/example/nto/service/impl/BookingServiceImpl.java

This commit is contained in:
2025-12-08 12:05:39 +00:00
parent 2e2dc5cd1f
commit 4cd71ec9ad

View File

@@ -1,12 +1,85 @@
package com.example.nto.service.impl;
import com.example.nto.entity.Booking;
import com.example.nto.entity.Employee;
import com.example.nto.entity.Place;
import com.example.nto.repository.BookingRepository;
import com.example.nto.repository.PlaceRepository;
import com.example.nto.service.BookingService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class BookingServiceImpl implements BookingService {
private final BookingRepository bookingRepository;
private final PlaceRepository placeRepository;
@Value("${booking.days-ahead}")
private int daysAhead;
@Override
public Map<LocalDate, Booking> getBookingsByEmployee(Employee employee) {
List<Booking> bookings = bookingRepository.findAllByEmployee(employee);
return bookings.stream()
.collect(Collectors.toMap(
Booking::getDate,
b -> b,
(b1, b2) -> b1,
TreeMap::new
));
}
@Override
public Map<LocalDate, List<Place>> getAvailablePlaces() {
LocalDate start = LocalDate.now();
List<Place> allPlaces = placeRepository.findAll();
Map<LocalDate, List<Place>> result = new LinkedHashMap<>();
for (int i = 0; i <= daysAhead; i++) {
LocalDate date = start.plusDays(i);
List<Booking> bookingsForDate = bookingRepository.findAllByDate(date);
Set<Long> busyPlaceIds = bookingsForDate.stream()
.map(b -> b.getPlace().getId())
.collect(Collectors.toSet());
List<Place> available = allPlaces.stream()
.filter(p -> !busyPlaceIds.contains(p.getId()))
.collect(Collectors.toList());
result.put(date, available);
}
return result;
}
@Override
public boolean existsBookingForEmployeeOnDate(Employee employee, LocalDate date) {
return bookingRepository.findAllByDate(date).stream()
.anyMatch(b -> b.getEmployee() != null && b.getEmployee().getId() == employee.getId());
}
@Override
public boolean isPlaceBookedOnDate(Place place, LocalDate date) {
return bookingRepository.existsByDateAndPlace(date, place);
}
@Override
public Booking createBooking(Employee employee, LocalDate date, Place place) {
Booking booking = Booking.builder()
.date(date)
.employee(employee)
.place(place)
.build();
return bookingRepository.save(booking);
}
}