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

View File

@@ -1,10 +1,86 @@
package com.example.nto.controller; package com.example.nto.controller;
/** import com.example.nto.dto.BookingRequestDto;
* TODO: ДОРАБОТАТЬ в рамках задания 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 { 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).body("Bad request");
}
if (employeeRepository.findByCode(code).isEmpty()) {
return ResponseEntity.status(401).body("Unauthorized");
}
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);
}
@PostMapping("/book")
public ResponseEntity<?> book(@PathVariable String code,
@RequestBody BookingRequestDto dto) {
if (!isValidCode(code)) {
return ResponseEntity.status(400).body("Bad request");
}
if (employeeRepository.findByCode(code).isEmpty()) {
return ResponseEntity.status(401).body("Unauthorized");
}
try {
service.createBooking(code, LocalDate.parse(dto.getDate()), dto.getPlaceId());
return ResponseEntity.status(201).body("Booking created");
} catch (IllegalArgumentException ex) {
String msg = ex.getMessage();
if ("Place not found".equals(msg)) {
return ResponseEntity.status(400).body("Bad request");
}
return ResponseEntity.status(400).body("Bad request");
} catch (IllegalStateException ex) {
return ResponseEntity.status(409).body("Conflict");
} catch (Exception ex) {
return ResponseEntity.status(400).body("Bad request");
}
}
@ExceptionHandler({org.springframework.http.converter.HttpMessageNotReadableException.class})
public ResponseEntity<String> handleBadRequest() {
return ResponseEntity.status(400).body("Bad request");
}
} }

View File

@@ -1,10 +1,75 @@
package com.example.nto.controller; package com.example.nto.controller;
/** import com.example.nto.dto.BookingInfoDto;
* TODO: ДОРАБОТАТЬ в рамках задания 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 org.springframework.http.converter.HttpMessageNotReadableException;
import java.util.LinkedHashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/{code}")
public class EmployeeController { 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).body("Bad request");
}
boolean exists = employeeRepository.findByCode(code).isPresent();
if (!exists) {
return ResponseEntity.status(401).body("Unauthorized");
}
return ResponseEntity.ok().build();
}
@GetMapping("/info")
public ResponseEntity<?> info(@PathVariable String code) {
if (!isCodeFormatValid(code)) {
return ResponseEntity.status(400).body("Bad request");
}
Employee employee = employeeRepository.findByCode(code).orElse(null);
if (employee == null) {
return ResponseEntity.status(401).body("Unauthorized");
}
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);
}
@ExceptionHandler({IllegalArgumentException.class, HttpMessageNotReadableException.class})
public ResponseEntity<String> handleBadRequest() {
return ResponseEntity.status(400).body("Bad request");
}
} }

View File

@@ -1,35 +1,65 @@
package com.example.nto.entity; package com.example.nto.entity;
import jakarta.persistence.FetchType; import jakarta.persistence.*;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate; import java.time.LocalDate;
@Entity
/** @Table(name = "booking")
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Booking { public class Booking {
private long id; @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private LocalDate date; private LocalDate date;
@ManyToOne(targetEntity = Place.class, fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "place_id") @JoinColumn(name = "place_id", nullable = false)
private Place place; private Place place;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "employee_id", nullable = false)
private Employee employee; 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; package com.example.nto.entity;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List; import java.util.List;
@Entity
/** @Table(name = "employee")
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Employee { public class Employee {
private long id; @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name; private String name;
@Column(nullable = false, unique = true)
private String code; private String code;
@Column(name = "photo_url")
private String photoUrl; private String photoUrl;
@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Booking> bookingList; 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; package com.example.nto.entity;
import jakarta.persistence.GeneratedValue; import jakarta.persistence.*;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
/** @Table(name = "place")
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Place { public class Place {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private long id; private Long id;
@Column(name = "place_name", nullable = false)
private String place; 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; package com.example.nto.repository;
/** import com.example.nto.entity.Booking;
* TODO: ДОРАБОТАТЬ в рамках задания import com.example.nto.entity.Place;
* ================================= import org.springframework.data.jpa.repository.JpaRepository;
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета import java.time.LocalDate;
*/ import java.util.List;
public interface BookingRepository { 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; package com.example.nto.repository;
/** import com.example.nto.entity.Employee;
* TODO: ДОРАБОТАТЬ в рамках задания import org.springframework.data.jpa.repository.JpaRepository;
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости import java.util.Optional;
* НЕЛЬЗЯ: Изменять название класса и пакета
*/ public interface EmployeeRepository extends JpaRepository<Employee, Long> {
public interface EmployeeRepository {
Optional<Employee> findByCode(String code);
} }

View File

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

View File

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

View File

@@ -1,12 +1,74 @@
package com.example.nto.service.impl; 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 com.example.nto.service.BookingService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/** import java.time.LocalDate;
* TODO: ДОРАБОТАТЬ в рамках задания import java.util.*;
* ================================= import java.util.stream.Collectors;
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета @Service
*/
public class BookingServiceImpl implements BookingService { 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; 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 com.example.nto.service.EmployeeService;
import org.springframework.stereotype.Service;
/** import java.util.Optional;
* TODO: ДОРАБОТАТЬ в рамках задания
* ================================= @Service
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
public class EmployeeServiceImpl implements EmployeeService { 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);
}
} }