Compare commits

3 Commits
main ... main

Author SHA1 Message Date
Yurchik-gitter
2c2a8981ff 2 2025-12-11 23:30:05 +03:00
Yurchik-gitter
d703db0388 1 2025-12-11 21:50:03 +03:00
Yurchik-gitter
df140765cd 1 2025-12-11 21:49:48 +03:00
18 changed files with 504 additions and 121 deletions

View File

@@ -1,12 +1,11 @@
package com.example.nto;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

View File

@@ -1,10 +1,77 @@
package com.example.nto.controller;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
import com.example.nto.dto.BookingRequestDto;
import com.example.nto.dto.FreePlaceDto;
import com.example.nto.entity.Place;
import com.example.nto.repository.EmployeeRepository;
import com.example.nto.service.BookingService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api/{code}")
public class BookingController {
private final BookingService service;
private final EmployeeRepository employeeRepository;
public BookingController(BookingService service, EmployeeRepository employeeRepository) {
this.service = service;
this.employeeRepository = employeeRepository;
}
private boolean isValidCode(String code) {
return code != null && code.matches("\\d+");
}
@GetMapping("/booking")
public ResponseEntity<?> getFree(@PathVariable String code) {
if (!isValidCode(code)) {
return ResponseEntity.status(400).build(); // Статус 400
}
if (employeeRepository.findByCode(code).isEmpty()) {
return ResponseEntity.status(401).build(); // Статус 401
}
Map<LocalDate, List<Place>> free = service.getAvailablePlacesForRange(LocalDate.now(), 4);
Map<String, List<FreePlaceDto>> dto = free.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey().toString(),
e -> e.getValue().stream()
.map(p -> new FreePlaceDto(p.getId(), p.getPlace()))
.collect(Collectors.toList())
));
return ResponseEntity.ok(dto); // Статус 200
}
@PostMapping("/book")
public ResponseEntity<?> book(@PathVariable String code,
@RequestBody BookingRequestDto dto) {
if (!isValidCode(code)) {
return ResponseEntity.status(400).build(); // Статус 400
}
if (employeeRepository.findByCode(code).isEmpty()) {
return ResponseEntity.status(401).build(); // Статус 401
}
try {
service.createBooking(code, LocalDate.parse(dto.getDate()), dto.getPlaceId());
return ResponseEntity.status(201).build(); // Статус 201 для успешного бронирования
} catch (IllegalArgumentException ex) {
return ResponseEntity.status(400).build(); // Ошибка для неверных данных (400)
} catch (IllegalStateException ex) {
return ResponseEntity.status(409).build(); // Ошибка, если место уже забронировано (409)
} catch (Exception ex) {
return ResponseEntity.status(400).build(); // Общая ошибка для других случаев (400)
}
}
}

View File

@@ -1,10 +1,69 @@
package com.example.nto.controller;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
import com.example.nto.dto.BookingInfoDto;
import com.example.nto.dto.EmployeeInfoDto;
import com.example.nto.entity.Booking;
import com.example.nto.entity.Employee;
import com.example.nto.repository.EmployeeRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.LinkedHashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/{code}")
public class EmployeeController {
private final EmployeeRepository employeeRepository;
public EmployeeController(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
private boolean isCodeFormatValid(String code) {
return code != null && code.matches("\\d+");
}
@GetMapping("/auth")
public ResponseEntity<?> auth(@PathVariable String code) {
if (!isCodeFormatValid(code)) {
return ResponseEntity.status(400).build(); // Статус 400
}
boolean exists = employeeRepository.findByCode(code).isPresent();
if (!exists) {
return ResponseEntity.status(401).build(); // Статус 401 для несуществующего сотрудника
}
return ResponseEntity.ok().build(); // Статус 200 для успешной авторизации
}
@GetMapping("/info")
public ResponseEntity<?> info(@PathVariable String code) {
if (!isCodeFormatValid(code)) {
return ResponseEntity.status(400).build(); // Статус 400
}
Employee employee = employeeRepository.findByCode(code).orElse(null);
if (employee == null) {
return ResponseEntity.status(401).build(); // Статус 401 для несуществующего сотрудника
}
Map<String, BookingInfoDto> bookingMap = new LinkedHashMap<>();
for (Booking b : employee.getBookingList()) {
bookingMap.put(
b.getDate().toString(),
new BookingInfoDto(b.getId(), b.getPlace().getPlace())
);
}
EmployeeInfoDto dto = new EmployeeInfoDto(
employee.getName(),
employee.getPhotoUrl(),
bookingMap
);
return ResponseEntity.ok(dto); // Статус 200 для успешной обработки
}
}

View File

@@ -0,0 +1,14 @@
package com.example.nto.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RootController {
@GetMapping("/")
public String home() {
return "Application is running";
}
}

View File

@@ -0,0 +1,37 @@
package com.example.nto.dto;
import com.example.nto.entity.Booking;
public class BookingInfoDto {
private Long id;
private String place;
public BookingInfoDto() {}
public BookingInfoDto(Booking booking) {
this.id = booking.getId();
this.place = booking.getPlace().getPlace();
}
public BookingInfoDto(Long id, String place) {
this.id = id;
this.place = place;
}
public Long getId() {
return id;
}
public String getPlace() {
return place;
}
public void setId(Long id) {
this.id = id;
}
public void setPlace(String place) {
this.place = place;
}
}

View File

@@ -0,0 +1,25 @@
package com.example.nto.dto;
public class BookingRequestDto {
private String date;
private Long placeId;
public BookingRequestDto() {}
public String getDate() {
return date;
}
public Long getPlaceId() {
return placeId;
}
public void setDate(String date) {
this.date = date;
}
public void setPlaceId(Long placeId) {
this.placeId = placeId;
}
}

View File

@@ -0,0 +1,42 @@
package com.example.nto.dto;
import java.util.Map;
public class EmployeeInfoDto {
private String name;
private String photoUrl;
private Map<String, BookingInfoDto> booking;
public EmployeeInfoDto() {}
public EmployeeInfoDto(String name, String photoUrl, Map<String, BookingInfoDto> booking) {
this.name = name;
this.photoUrl = photoUrl;
this.booking = booking;
}
public String getName() {
return name;
}
public String getPhotoUrl() {
return photoUrl;
}
public Map<String, BookingInfoDto> getBooking() {
return booking;
}
public void setName(String name) {
this.name = name;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public void setBooking(Map<String, BookingInfoDto> booking) {
this.booking = booking;
}
}

View File

@@ -0,0 +1,30 @@
package com.example.nto.dto;
public class FreePlaceDto {
private Long id;
private String place;
public FreePlaceDto() {}
public FreePlaceDto(Long id, String place) {
this.id = id;
this.place = place;
}
public Long getId() {
return id;
}
public String getPlace() {
return place;
}
public void setId(Long id) {
this.id = id;
}
public void setPlace(String place) {
this.place = place;
}
}

View File

@@ -1,35 +1,65 @@
package com.example.nto.entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import jakarta.persistence.*;
import java.time.LocalDate;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "booking")
public class Booking {
private long id;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private LocalDate date;
@ManyToOne(targetEntity = Place.class, fetch = FetchType.LAZY)
@JoinColumn(name = "place_id")
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "place_id", nullable = false)
private Place place;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "employee_id", nullable = false)
private Employee employee;
public Booking() {
}
public Booking(LocalDate date, Place place, Employee employee) {
this.date = date;
this.place = place;
this.employee = employee;
}
public Long getId() {
return id;
}
public LocalDate getDate() {
return date;
}
public Place getPlace() {
return place;
}
public Employee getEmployee() {
return employee;
}
public void setId(Long id) {
this.id = id;
}
public void setDate(LocalDate date) {
this.date = date;
}
public void setPlace(Place place) {
this.place = place;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}

View File

@@ -1,34 +1,39 @@
package com.example.nto.entity;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "employee")
public class Employee {
private long id;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false, unique = true)
private String code;
@Column(name = "photo_url")
private String photoUrl;
@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Booking> bookingList;
public Employee() {}
public Long getId() { return id; }
public String getName() { return name; }
public String getCode() { return code; }
public String getPhotoUrl() { return photoUrl; }
public List<Booking> getBookingList() { return bookingList; }
public void setId(Long id) { this.id = id; }
public void setName(String name) { this.name = name; }
public void setCode(String code) { this.code = code; }
public void setPhotoUrl(String photoUrl) { this.photoUrl = photoUrl; }
public void setBookingList(List<Booking> bookingList) { this.bookingList = bookingList; }
}

View File

@@ -1,29 +1,23 @@
package com.example.nto.entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import jakarta.persistence.*;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "place")
public class Place {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private Long id;
@Column(name = "place_name", nullable = false)
private String place;
public Place() {}
public Long getId() { return id; }
public String getPlace() { return place; }
public void setId(Long id) { this.id = id; }
public void setPlace(String place) { this.place = place; }
}

View File

@@ -1,10 +1,18 @@
package com.example.nto.repository;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
public interface BookingRepository {
import com.example.nto.entity.Booking;
import com.example.nto.entity.Place;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
public interface BookingRepository extends JpaRepository<Booking, Long> {
List<Booking> findByDate(LocalDate date);
Optional<Booking> findByPlaceAndDate(Place place, LocalDate date);
List<Booking> findByEmployeeId(Long employeeId);
}

View File

@@ -1,10 +1,11 @@
package com.example.nto.repository;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
public interface EmployeeRepository {
import com.example.nto.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
Optional<Employee> findByCode(String code);
}

View File

@@ -1,10 +1,7 @@
package com.example.nto.repository;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
public interface PlaceRepository {
import com.example.nto.entity.Place;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PlaceRepository extends JpaRepository<Place, Long> {
}

View File

@@ -1,10 +1,12 @@
package com.example.nto.service;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
import com.example.nto.entity.Place;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
public interface BookingService {
Map<LocalDate, List<Place>> getAvailablePlacesForRange(LocalDate start, int days);
void createBooking(String code, LocalDate date, Long placeId);
}

View File

@@ -1,10 +1,9 @@
package com.example.nto.service;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
import com.example.nto.entity.Employee;
import java.util.Optional;
public interface EmployeeService {
Optional<Employee> findByCode(String code);
}

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);
}
}

View File

@@ -1,12 +1,24 @@
package com.example.nto.service.impl;
import com.example.nto.entity.Employee;
import com.example.nto.repository.EmployeeRepository;
import com.example.nto.service.EmployeeService;
import org.springframework.stereotype.Service;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
import java.util.Optional;
@Service
public class EmployeeServiceImpl implements EmployeeService {
private final EmployeeRepository employeeRepository;
public EmployeeServiceImpl(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
@Override
public Optional<Employee> findByCode(String code) {
if (code == null) return Optional.empty();
return employeeRepository.findByCode(code);
}
}