first commit #7

Closed
yurchik-k0028 wants to merge 3 commits from (deleted):main into main
13 changed files with 297 additions and 81 deletions
Showing only changes of commit c9c12e2481 - Show all commits

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,82 @@
package com.example.nto.controller; package com.example.nto.controller;
/** import com.example.nto.entity.Booking;
* TODO: ДОРАБОТАТЬ в рамках задания import com.example.nto.entity.Place;
* ================================= import com.example.nto.entity.Employee;
* МОЖНО: Добавлять методы, аннотации, зависимости import com.example.nto.service.BookingService;
* НЕЛЬЗЯ: Изменять название класса и пакета import com.example.nto.service.EmployeeService;
*/ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
@RestController
public class BookingController { public class BookingController {
private final BookingService bookingService;
private final EmployeeService employeeService;
public BookingController(BookingService bookingService, EmployeeService employeeService) {
this.bookingService = bookingService;
this.employeeService = employeeService;
}
// GET /api/{code}/booking -> available places for current + 3 days (4 days total)
@GetMapping("/api/{code}/booking")
public ResponseEntity<?> getAvailable(@PathVariable("code") String code) {
try {
if (code == null) return ResponseEntity.badRequest().build();
Optional<Employee> e = employeeService.findByCode(code);
if (e.isEmpty()) return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
LocalDate today = LocalDate.now();
Map<LocalDate, List<Place>> map = bookingService.getAvailablePlacesForRange(today, 4);
// convert dates to string keys and places to required JSON objects {id, place}
Map<String, List<Map<String,Object>>> out = new LinkedHashMap<>();
map.forEach((date, places) -> {
List<Map<String,Object>> list = places.stream().map(p -> {
Map<String,Object> m = new LinkedHashMap<>();
m.put("id", p.getId());
m.put("place", p.getPlace());
return m;
}).collect(Collectors.toList());
out.put(date.toString(), list);
});
return ResponseEntity.ok(out);
} catch (Exception ex) {
return ResponseEntity.badRequest().build();
}
}
// POST /api/{code}/book
@PostMapping("/api/{code}/book")
public ResponseEntity<?> book(@PathVariable("code") String code, @RequestBody Map<String, Object> body) {
try {
if (code == null) return ResponseEntity.badRequest().build();
Optional<Employee> eOpt = employeeService.findByCode(code);
if (eOpt.isEmpty()) return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
Employee e = eOpt.get();
if (!body.containsKey("date") || !body.containsKey("placeId")) {
return ResponseEntity.badRequest().build();
}
String dateStr = body.get("date").toString();
LocalDate date = LocalDate.parse(dateStr);
long placeId = Long.parseLong(body.get("placeId").toString());
try {
Booking booking = bookingService.createBooking(e.getId(), placeId, date);
return ResponseEntity.status(HttpStatus.CREATED).build();
} catch (IllegalStateException ex) {
if (ex.getMessage() != null && ex.getMessage().toLowerCase().contains("already")) {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
return ResponseEntity.badRequest().build();
}
} catch (Exception ex) {
return ResponseEntity.badRequest().build();
}
}
} }

View File

@@ -1,10 +1,68 @@
package com.example.nto.controller; package com.example.nto.controller;
/** import com.example.nto.entity.Booking;
* TODO: ДОРАБОТАТЬ в рамках задания import com.example.nto.entity.Employee;
* ================================= import com.example.nto.service.BookingService;
* МОЖНО: Добавлять методы, аннотации, зависимости import com.example.nto.service.EmployeeService;
* НЕЛЬЗЯ: Изменять название класса и пакета import org.springframework.http.HttpStatus;
*/ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.stream.Collectors;
@RestController
public class EmployeeController { public class EmployeeController {
private final EmployeeService employeeService;
private final BookingService bookingService;
public EmployeeController(EmployeeService employeeService, BookingService bookingService) {
this.employeeService = employeeService;
this.bookingService = bookingService;
}
// GET /api/{code}/auth
@GetMapping("/api/{code}/auth")
public ResponseEntity<Void> auth(@PathVariable("code") String code) {
try {
if (code == null) return ResponseEntity.badRequest().build();
Optional<Employee> e = employeeService.findByCode(code);
return e.isPresent() ? ResponseEntity.ok().build() : ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
} catch (Exception ex) {
return ResponseEntity.badRequest().build();
}
}
// GET /api/{code}/info
@GetMapping("/api/{code}/info")
public ResponseEntity<?> info(@PathVariable("code") String code) {
try {
if (code == null) return ResponseEntity.badRequest().build();
Optional<Employee> opt = employeeService.findByCode(code);
if (opt.isEmpty()) return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
Employee e = opt.get();
Map<String, Object> body = new LinkedHashMap<>();
body.put("name", e.getName());
body.put("photoUrl", e.getPhotoUrl());
// bookings grouped by date
List<Booking> bookings = bookingService.getBookingsForEmployee(e.getId());
Map<String, Map<String, Object>> bookingMap = bookings.stream()
.collect(Collectors.toMap(
b -> b.getDate().toString(),
b -> {
Map<String,Object> m = new LinkedHashMap<>();
m.put("id", b.getId());
m.put("place", b.getPlace().getPlace());
return m;
},
(a,b)->a,
LinkedHashMap::new
));
body.put("booking", bookingMap);
return ResponseEntity.ok(body);
} catch (Exception ex) {
return ResponseEntity.badRequest().build();
}
}
} }

View File

@@ -1,8 +1,6 @@
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.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
import lombok.Data; import lombok.Data;
@@ -10,19 +8,19 @@ import lombok.NoArgsConstructor;
import java.time.LocalDate; import java.time.LocalDate;
/** /**
* TODO: ДОРАБОТАТЬ в рамках задания * Booking entity
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/ */
@Entity
@Table(name = "booking")
@Data @Data
@Builder @Builder
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class Booking { public class Booking {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id; private long id;
private LocalDate date; private LocalDate date;
@@ -31,5 +29,7 @@ public class Booking {
@JoinColumn(name = "place_id") @JoinColumn(name = "place_id")
private Place place; private Place place;
@ManyToOne(targetEntity = Employee.class, fetch = FetchType.LAZY)
@JoinColumn(name = "employee_id")
private Employee employee; private Employee employee;
} }

View File

@@ -8,23 +8,24 @@ import lombok.NoArgsConstructor;
import java.util.List; import java.util.List;
/** /**
* TODO: ДОРАБОТАТЬ в рамках задания * Employee entity
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/ */
@Entity
@Table(name = "employee")
@Data @Data
@Builder @Builder
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class Employee { public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id; private long id;
private String name; private String name;
@Column(unique = true, nullable = false)
private String code; private String code;
private String photoUrl; private String photoUrl;

View File

@@ -1,20 +1,20 @@
package com.example.nto.entity; package com.example.nto.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType; import jakarta.persistence.GenerationType;
import jakarta.persistence.Id; import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
/** /**
* TODO: ДОРАБОТАТЬ в рамках задания * Place entity
* =================================
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета
*/ */
@Entity
@Table(name = "place")
@Data @Data
@Builder @Builder
@NoArgsConstructor @NoArgsConstructor

View File

@@ -1,10 +1,16 @@
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 org.springframework.stereotype.Repository;
* НЕЛЬЗЯ: Изменять название класса и пакета
*/ import java.time.LocalDate;
public interface BookingRepository { import java.util.List;
@Repository
public interface BookingRepository extends JpaRepository<Booking, Long> {
List<Booking> findByDate(LocalDate date);
List<Booking> findByPlaceAndDate(Place place, LocalDate date);
List<Booking> findByEmployeeId(long employeeId);
} }

View File

@@ -1,10 +1,12 @@
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 org.springframework.stereotype.Repository;
* МОЖНО: Добавлять методы, аннотации, зависимости
* НЕЛЬЗЯ: Изменять название класса и пакета import java.util.Optional;
*/
public interface EmployeeRepository { @Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
Optional<Employee> findByCode(String code);
} }

View File

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

View File

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

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,76 @@
package com.example.nto.service.impl; package com.example.nto.service.impl;
import com.example.nto.entity.Booking;
import com.example.nto.entity.Place;
import com.example.nto.entity.Employee;
import com.example.nto.repository.BookingRepository;
import com.example.nto.repository.PlaceRepository;
import com.example.nto.repository.EmployeeRepository;
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 fromInclusive, int days) {
List<Place> allPlaces = placeRepository.findAll();
Map<LocalDate, List<Place>> result = new LinkedHashMap<>();
for (int i = 0; i < days; i++) {
LocalDate date = fromInclusive.plusDays(i);
List<Long> bookedPlaceIds = bookingRepository.findByDate(date).stream()
.map(b -> b.getPlace().getId()).collect(Collectors.toList());
List<Place> free = allPlaces.stream()
.filter(p -> !bookedPlaceIds.contains(p.getId()))
.collect(Collectors.toList());
result.put(date, free);
}
return result;
}
@Override
@Transactional
public Booking createBooking(long employeeId, long placeId, LocalDate date) throws IllegalStateException {
// check employee
Optional<Employee> employeeOpt = employeeRepository.findById(employeeId);
if (employeeOpt.isEmpty()) throw new IllegalStateException("Employee not found");
Optional<Place> placeOpt = placeRepository.findById(placeId);
if (placeOpt.isEmpty()) throw new IllegalStateException("Place not found");
// check if already booked
List<Booking> exists = bookingRepository.findByPlaceAndDate(placeOpt.get(), date);
if (!exists.isEmpty()) {
throw new IllegalStateException("Already booked");
}
Booking booking = Booking.builder()
.date(date)
.employee(employeeOpt.get())
.place(placeOpt.get())
.build();
return bookingRepository.save(booking);
}
@Override
public List<Booking> getBookingsForEmployee(long employeeId) {
return bookingRepository.findByEmployeeId(employeeId);
}
} }

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