api was implemented
Some checks failed
Android Test / validate-and-test (pull_request) Has been cancelled

This commit is contained in:
lavatee
2025-12-11 23:37:20 +07:00
parent 83b3202ea2
commit 24acc3aa02
17 changed files with 324 additions and 4 deletions

View File

@@ -6,7 +6,12 @@ package com.example.nto;
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
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,43 @@
package com.example.nto.controller;
import com.example.nto.dto.BookRequest;
import com.example.nto.dto.BookingInfoDto;
import com.example.nto.dto.PlaceDto;
import com.example.nto.service.BookingService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class BookingController {
private final BookingService bookingService;
@GetMapping("/{code}/booking")
public Map<String, List<PlaceDto>> getAvailable(@PathVariable String code) {
return bookingService.getAvailablePlaces(code);
}
@PostMapping("/{code}/book")
public ResponseEntity<BookingInfoDto> book(@PathVariable String code, @RequestBody BookRequest request) {
System.out.println("place id: " + request.placeId());
BookingInfoDto booking = bookingService.createBooking(code, request.date(), request.placeId());
return ResponseEntity.status(201).body(booking);
}
}

View File

@@ -1,10 +1,37 @@
package com.example.nto.controller;
import com.example.nto.dto.EmployeeInfoResponse;
import com.example.nto.service.BookingService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class EmployeeController {
private final BookingService bookingService;
@GetMapping("/{code}/auth")
public ResponseEntity<Void> auth(@PathVariable String code) {
if (bookingService.isCodeValid(code)) {
return ResponseEntity.ok().build();
}
return ResponseEntity.status(401).build();
}
@GetMapping("/{code}/info")
public EmployeeInfoResponse getInfo(@PathVariable String code) {
return bookingService.getEmployeeInfo(code);
}
}

View File

@@ -0,0 +1,7 @@
package com.example.nto.dto;
import java.time.LocalDate;
public record BookRequest(LocalDate date, long placeId) {
}

View File

@@ -0,0 +1,5 @@
package com.example.nto.dto;
public record BookingInfoDto(long id, String place) {
}

View File

@@ -0,0 +1,7 @@
package com.example.nto.dto;
import java.util.Map;
public record EmployeeInfoResponse(String name, String photoUrl, Map<String, BookingInfoDto> booking) {
}

View File

@@ -0,0 +1,5 @@
package com.example.nto.dto;
public record PlaceDto(long id, String place) {
}

View File

@@ -1,8 +1,14 @@
package com.example.nto.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@@ -21,15 +27,22 @@ import java.time.LocalDate;
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "booking")
public class Booking {
@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")
private Place place;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "employee_id")
private Employee employee;
}

View File

@@ -1,6 +1,14 @@
package com.example.nto.entity;
import jakarta.persistence.*;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@@ -19,14 +27,20 @@ import java.util.List;
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
@Column(unique = true, nullable = false)
private String code;
@Column(name = "photo_url")
private String photoUrl;
@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, fetch = FetchType.LAZY)

View File

@@ -1,8 +1,11 @@
package com.example.nto.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@@ -19,11 +22,14 @@ import lombok.NoArgsConstructor;
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "place")
public class Place {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "place_name", nullable = false, unique = true)
private String place;
}

View File

@@ -1,10 +1,26 @@
package com.example.nto.repository;
import com.example.nto.entity.Booking;
import com.example.nto.entity.Employee;
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;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
public interface BookingRepository {
public interface BookingRepository extends JpaRepository<Booking, Long> {
List<Booking> findAllByEmployee(Employee employee);
List<Booking> findAllByDate(LocalDate date);
Optional<Booking> findByDateAndPlace(LocalDate date, Place place);
Optional<Booking> findByEmployeeAndDate(Employee employee, LocalDate date);
}

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,7 @@
package com.example.nto.service;
import com.example.nto.entity.Employee;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
* =================================
@@ -7,4 +9,8 @@ package com.example.nto.service;
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
public interface EmployeeService {
boolean existsByCode(String code);
Employee getByCode(String code);
}

View File

@@ -1,6 +1,31 @@
package com.example.nto.service.impl;
import com.example.nto.dto.BookingInfoDto;
import com.example.nto.dto.EmployeeInfoResponse;
import com.example.nto.dto.PlaceDto;
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 lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
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;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.CONFLICT;
import static org.springframework.http.HttpStatus.UNAUTHORIZED;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
@@ -8,5 +33,108 @@ import com.example.nto.service.BookingService;
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
@Service
@RequiredArgsConstructor
public class BookingServiceImpl implements BookingService {
private final EmployeeRepository employeeRepository;
private final BookingRepository bookingRepository;
private final PlaceRepository placeRepository;
@Value("${booking.days-ahead:3}")
private int daysAhead;
@Override
public boolean isCodeValid(String code) {
return employeeRepository.existsByCode(code);
}
@Override
public EmployeeInfoResponse getEmployeeInfo(String code) {
Employee employee = employeeRepository.findByCode(code)
.orElseThrow(() -> new ResponseStatusException(UNAUTHORIZED));
Map<String, BookingInfoDto> bookingMap = bookingRepository.findAllByEmployee(employee)
.stream()
.collect(Collectors.toMap(
b -> b.getDate().toString(),
b -> new BookingInfoDto(b.getId(), b.getPlace().getPlace()),
(first, second) -> first
));
return new EmployeeInfoResponse(employee.getName(), employee.getPhotoUrl(), bookingMap);
}
@Override
public Map<String, List<PlaceDto>> getAvailablePlaces(String code) {
ensureCodeValid(code);
List<Place> allPlaces = placeRepository.findAll();
Map<String, List<PlaceDto>> result = new HashMap<>();
for (int i = 0; i <= daysAhead; i++) {
LocalDate date = LocalDate.now().plusDays(i);
Set<Long> bookedPlaceIds = bookingRepository.findAllByDate(date)
.stream()
.map(booking -> booking.getPlace().getId())
.collect(Collectors.toSet());
List<PlaceDto> available = allPlaces.stream()
.filter(place -> !bookedPlaceIds.contains(place.getId()))
.map(place -> new PlaceDto(place.getId(), place.getPlace()))
.toList();
result.put(date.toString(), available);
}
return result;
}
@Override
@Transactional
public BookingInfoDto createBooking(String code, LocalDate date, long placeId) {
Employee employee = employeeRepository.findByCode(code)
.orElseThrow(() -> new ResponseStatusException(UNAUTHORIZED));
validateDate(date);
Place place = placeRepository.findById(placeId)
.orElseThrow(() -> new ResponseStatusException(BAD_REQUEST));
bookingRepository.findByEmployeeAndDate(employee, date)
.ifPresent(existing -> {
throw new ResponseStatusException(CONFLICT);
});
bookingRepository.findByDateAndPlace(date, place)
.ifPresent(existing -> {
throw new ResponseStatusException(CONFLICT);
});
Booking booking = Booking.builder()
.date(date)
.place(place)
.employee(employee)
.build();
Booking saved = bookingRepository.save(booking);
return new BookingInfoDto(saved.getId(), saved.getPlace().getPlace());
}
private void ensureCodeValid(String code) {
if (!employeeRepository.existsByCode(code)) {
throw new ResponseStatusException(UNAUTHORIZED);
}
}
private void validateDate(LocalDate date) {
if (date == null) {
throw new ResponseStatusException(BAD_REQUEST);
}
LocalDate today = LocalDate.now();
LocalDate lastAvailable = today.plusDays(daysAhead);
if (date.isBefore(today) || date.isAfter(lastAvailable)) {
throw new ResponseStatusException(BAD_REQUEST);
}
}
}

View File

@@ -1,6 +1,13 @@
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 lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import static org.springframework.http.HttpStatus.UNAUTHORIZED;
/**
* TODO: ДОРАБОТАТЬ в рамках задания
@@ -8,5 +15,20 @@ import com.example.nto.service.EmployeeService;
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/
@Service
@RequiredArgsConstructor
public class EmployeeServiceImpl implements EmployeeService {
private final EmployeeRepository employeeRepository;
@Override
public boolean existsByCode(String code) {
return employeeRepository.existsByCode(code);
}
@Override
public Employee getByCode(String code) {
return employeeRepository.findByCode(code)
.orElseThrow(() -> new ResponseStatusException(UNAUTHORIZED));
}
}