Compare commits

1 Commits
main ... main

Author SHA1 Message Date
83b3202ea2 Update .gitea/workflows/workflow.yml 2025-12-01 13:23:00 +03:00
18 changed files with 25 additions and 326 deletions

View File

@@ -51,7 +51,7 @@
| **GET** | `api/<CODE>/auth` | Проверка авторизации | `<CODE>` - код для входа | `400` - что-то пошло не так<br>`401` - кода не существует<br>`200` - данный код существует - можно пользоваться приложением |
| **GET** | `api/<CODE>/info` | Получение информации о пользователе | `<CODE>` - код для входа | `400` - что-то пошло не так<br>`401` - кода не существует<br>`200` - ОК<br><pre>{<br> "name":"Иванов Петр Федорович",<br> "photoUrl":"<https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg>",<br> "booking":{<br> "2025-01-05": {"id":1,"place":"102"},<br> "2025-01-06": {"id":2,"place":"209.13"},<br> "2025-01-09": {"id":3,"place":"Зона 51. 50"}<br> }<br>}</pre> |
| **GET** | `api/<CODE>/booking` | Получение доступных для бронирования мест | `<CODE>` - код для входа | `400` - что-то пошло не так<br>`401` - кода не существует<br>`200` - ОК<br><pre>{<br> "2025-01-05": [{"id": 1, "place": "102"},{"id": 2, "place": "209.13"}],<br> "2025-01-06": [{"id": 3, "place": "Зона 51. 50"}],<br> "2025-01-07": [{"id": 1, "place": "102"},{"id": 2, "place": "209.13"}],<br> "2025-01-08": [{"id": 2, "place": "209.13"}]<br>}</pre> **Список дат ограничен текущим + 3 днями** (ответ от сервера содержит 4 дня со свободными местами для каждого)
| **POST** | `api/<CODE>/book` | Создание нового бронирования | `<CODE>` - код для входа<br>Тело: <br> <pre>{<br> “date”: “2025-01-05”,<br> “placeID”: 1 <br>}</pre> |`400` - что-то пошло не так<br>`401` - кода не существует<br>`409` - уже забронировано<br>`201` - бронирование успешно создано
| **POST** | `api/<CODE>/book` | Создание нового бронирования | `<CODE>` - код для входа<br>Тело: <br> <pre>{<br> “date”: “2025-01-05”,<br> “placeId”: 1 <br>}</pre> |`400` - что-то пошло не так<br>`401` - кода не существует<br>`409` - уже забронировано<br>`201` - бронирование успешно создано
## 📊 Пример данных

View File

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

View File

@@ -1,7 +0,0 @@
package com.example.nto.Exception;
public class BookingConflictException extends RuntimeException {
public BookingConflictException(String message) {
super(message);
}
}

View File

@@ -1,7 +0,0 @@
package com.example.nto.Exception;
public class EmployeeNotFoundException extends RuntimeException {
public EmployeeNotFoundException(String message) {
super(message);
}
}

View File

@@ -1,30 +0,0 @@
package com.example.nto.Exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(EmployeeNotFoundException.class)
public ResponseEntity<String> EmployeeNotFoundException(EmployeeNotFoundException ex) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ex.getMessage());
}
@ExceptionHandler(PlaceNotFoundException.class)
public ResponseEntity<String> PlaceNotFoundException(PlaceNotFoundException ex) {
return ResponseEntity.badRequest().body("Что-то пошло не так");
}
@ExceptionHandler(BookingConflictException.class)
public ResponseEntity<String> BookingConflictException(BookingConflictException ex) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> Exception(Exception ex) {
return ResponseEntity.badRequest().body("Что-то пошло не так");
}
}

View File

@@ -1,7 +0,0 @@
package com.example.nto.Exception;
public class PlaceNotFoundException extends RuntimeException {
public PlaceNotFoundException(String message) {
super(message);
}
}

View File

@@ -1,59 +1,10 @@
package com.example.nto.controller;
import com.example.nto.entity.Place;
import com.example.nto.service.BookingService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
@RestController
@RequestMapping("/api/{code}")
@RequiredArgsConstructor
public class BookingController {
private final BookingService bookingService;
@GetMapping("/booking")
public ResponseEntity<?> getAvailableBooking(@PathVariable String code) {
Map<LocalDate, List<Place>> places = bookingService.getAvailablePlaces(code);
Map<String, List<Map<String, Object>>> result = new TreeMap<>();
for (Map.Entry<LocalDate, List<Place>> e : places.entrySet()) {
List<Map<String, Object>> placeList = e.getValue().stream().map(p -> {
Map<String, Object> m = new HashMap<>();
m.put("id", p.getId());
m.put("place", p.getPlaceName());
return m;
}).toList();
result.put(e.getKey().toString(), placeList);
}
return ResponseEntity.ok(result);
}
@PostMapping("/book")
public ResponseEntity<?> createBooking(@PathVariable String code, @RequestBody Map<String, Object> request) {
// try {
String dateStr = (String) request.get("date");
Long placeID = Long.valueOf(String.valueOf(request.get("placeID")));
LocalDate date = LocalDate.parse(dateStr);
bookingService.createBooking(code, date, placeID);
return ResponseEntity.status(201).build();
// }
// catch (Exception ex) {
// return ResponseEntity.badRequest().body("Что-то пошло не так");
// }
}
}

View File

@@ -1,60 +1,10 @@
package com.example.nto.controller;
import com.example.nto.entity.Booking;
import com.example.nto.entity.Employee;
import com.example.nto.entity.Place;
import com.example.nto.service.BookingService;
import com.example.nto.service.EmployeeService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
@RestController
@RequestMapping("/api/{code}")
@RequiredArgsConstructor
public class EmployeeController {
private final EmployeeService employeeService;
@GetMapping("/auth")
public ResponseEntity<Void> auth(@PathVariable String code) {
employeeService.findByCode(code);
return ResponseEntity.ok().build();
}
@GetMapping("/info")
public ResponseEntity<?> getInfo(@PathVariable String code) {
Employee employee = employeeService.findByCode(code);
// Формирование booking map (дата -> booking details)
Map<String, Object> response = new HashMap<>();
response.put("name", employee.getName());
response.put("photoUrl", employee.getPhotoUrl());
Map<String, Map<String, Object>> bookingMap = new HashMap<>();
if (employee.getBookingList() != null) {
for (Booking bk : employee.getBookingList()) {
Map<String, Object> bookingDetails = new HashMap<>();
bookingDetails.put("id", bk.getId());
bookingDetails.put("place", bk.getPlaceId()); // можно заменить на placeName, если нужно join
bookingMap.put(bk.getDate().toString(), bookingDetails);
}
}
response.put("booking", bookingMap);
return ResponseEntity.ok(response);
}
}

View File

@@ -1,6 +1,8 @@
package com.example.nto.entity;
import jakarta.persistence.*;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@@ -19,20 +21,15 @@ import java.time.LocalDate;
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "booking")
public class Booking {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "date")
private long id;
private LocalDate date;
@Column(name = "place_id")
private Long placeId;
@ManyToOne(targetEntity = Place.class, fetch = FetchType.LAZY)
@JoinColumn(name = "place_id")
private Place place;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "employee_id")
private Employee employee;
}
}

View File

@@ -19,21 +19,14 @@ import java.util.List;
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private long id;
@Column(name = "name")
private String name;
@Column(name = "code")
private String code;
@Column(name = "photo_url")
private String photoUrl;
@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, fetch = FetchType.LAZY)

View File

@@ -1,6 +1,8 @@
package com.example.nto.entity;
import jakarta.persistence.*;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@@ -17,13 +19,11 @@ import lombok.NoArgsConstructor;
@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")
private String placeName;
}
private String place;
}

View File

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

View File

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

View File

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

View File

@@ -1,12 +1,5 @@
package com.example.nto.service;
import com.example.nto.entity.Booking;
import com.example.nto.entity.Place;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
@@ -14,6 +7,4 @@ import java.util.Map;
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
public interface BookingService {
Map<LocalDate, List<Place>> getAvailablePlaces(String code);
Booking createBooking(String code, LocalDate date, Long placeId);
}

View File

@@ -1,10 +1,5 @@
package com.example.nto.service;
import com.example.nto.entity.Employee;
import com.example.nto.repository.EmployeeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
@@ -12,5 +7,4 @@ import org.springframework.stereotype.Service;
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
public interface EmployeeService {
public Employee findByCode(String code);
}
}

View File

@@ -1,26 +1,6 @@
package com.example.nto.service.impl;
import com.example.nto.Exception.BookingConflictException;
import com.example.nto.Exception.EmployeeNotFoundException;
import com.example.nto.Exception.PlaceNotFoundException;
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.EmployeeService;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
@@ -28,63 +8,5 @@ import java.util.stream.Collectors;
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
@RequiredArgsConstructor
@Service
public class BookingServiceImpl implements BookingService {
private final BookingRepository bookingRepository;
private final PlaceRepository placeRepository;
private final EmployeeService employeeService;
// Максимальное количество дней вперед для брони из конфигурации (например 3)
private static final int DAYS_AHEAD = 3;
private final EmployeeRepository employeeRepository;
public Map<LocalDate, List<Place>> getAvailablePlaces(String code) {
Employee employee = employeeService.findByCode(code);
LocalDate today = LocalDate.now();
LocalDate endDate = today.plusDays(DAYS_AHEAD);
List<Booking> allBookings = bookingRepository.findByDateBetween(today, endDate);
List<Place> allPlaces = placeRepository.findAll();
Map<LocalDate, List<Place>> availablePlacesByDate = new HashMap<>();
for (LocalDate date = today; !date.isAfter(endDate); date = date.plusDays(1)) {
LocalDate currentDate = date;
// Найти занятые места в этот день
Set<Long> bookedPlaceIds = allBookings.stream()
.filter(b -> b.getDate().equals(currentDate))
.map(Booking::getPlaceId)
.collect(Collectors.toSet());
// Оставшиеся места свободны
List<Place> freePlaces = allPlaces.stream()
.filter(p -> !bookedPlaceIds.contains(p.getId()))
.collect(Collectors.toList());
availablePlacesByDate.put(currentDate, freePlaces);
}
return availablePlacesByDate;
}
@Transactional
public Booking createBooking(String code, LocalDate date, Long placeId) {
if (employeeRepository.findByCode(code).isEmpty()) throw new EmployeeNotFoundException("Кода не существует");
if (!placeRepository.existsById(placeId)) {
throw new PlaceNotFoundException("Место не существует");
}
if (bookingRepository.existsByDateAndPlaceId(date, placeId)) {
throw new BookingConflictException("Уже забронировано");
}
Employee employee = employeeService.findByCode(code);
Booking booking = new Booking();
booking.setDate(date);
booking.setPlaceId(placeId);
booking.setEmployee(employee);
return bookingRepository.save(booking);
}
}

View File

@@ -1,11 +1,6 @@
package com.example.nto.service.impl;
import com.example.nto.Exception.EmployeeNotFoundException;
import com.example.nto.entity.Employee;
import com.example.nto.repository.EmployeeRepository;
import com.example.nto.service.EmployeeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
@@ -13,13 +8,5 @@ import org.springframework.stereotype.Service;
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
@Service
@RequiredArgsConstructor
public class EmployeeServiceImpl implements EmployeeService {
private final EmployeeRepository employeeRepository;
public Employee findByCode(String code) {
return employeeRepository.findByCode(code)
.orElseThrow(() -> new EmployeeNotFoundException("Кода не существует"));
}
}