This commit is contained in:
Yurchik-gitter
2025-12-11 21:49:48 +03:00
parent 83b3202ea2
commit df140765cd
13 changed files with 371 additions and 121 deletions

View File

@@ -1,12 +1,74 @@
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.EmployeeRepository;
import com.example.nto.repository.PlaceRepository;
import com.example.nto.service.BookingService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class BookingServiceImpl implements BookingService {
private final BookingRepository bookingRepository;
private final PlaceRepository placeRepository;
private final EmployeeRepository employeeRepository;
public BookingServiceImpl(BookingRepository bookingRepository,
PlaceRepository placeRepository,
EmployeeRepository employeeRepository) {
this.bookingRepository = bookingRepository;
this.placeRepository = placeRepository;
this.employeeRepository = employeeRepository;
}
@Override
public Map<LocalDate, List<Place>> getAvailablePlacesForRange(LocalDate start, int days) {
Map<LocalDate, List<Place>> result = new LinkedHashMap<>();
List<Place> allPlaces = placeRepository.findAll();
for (int i = 0; i < days; i++) {
LocalDate date = start.plusDays(i);
List<Booking> booked = bookingRepository.findByDate(date);
Set<Long> bookedIds = booked.stream()
.map(b -> b.getPlace().getId())
.collect(Collectors.toSet());
List<Place> free = allPlaces.stream()
.filter(p -> !bookedIds.contains(p.getId()))
.collect(Collectors.toList());
result.put(date, free);
}
return result;
}
@Override
@Transactional
public void createBooking(String code, LocalDate date, Long placeId) {
// Проверка существования сотрудника
Employee employee = employeeRepository.findByCode(code)
.orElseThrow(() -> new IllegalArgumentException("Employee not found"));
// Проверка существования места
Place place = placeRepository.findById(placeId)
.orElseThrow(() -> new IllegalArgumentException("Place not found"));
// Проверка, что место уже не забронировано на эту дату
boolean alreadyBooked = bookingRepository.findByPlaceAndDate(place, date).isPresent();
if (alreadyBooked) {
throw new IllegalStateException("Place already booked");
}
// Создание и сохранение нового бронирования
Booking booking = new Booking(date, place, employee);
bookingRepository.save(booking);
}
}