Mini 프로젝트 - reservation

박경희·2023년 8월 4일
0

프로젝트

목록 보기
3/16
post-thumbnail

reservation

Entity

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Builder
public class Reservation {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long reservationId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "room_id")
    private Room room;

    private String guestName;
    private LocalDate checkInDate;
    private LocalDate checkOutDate;
    private Double totalPrice;

    @Column(nullable = false)
    private Integer people;
    private String poneNumber;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;
}

Repository

public interface ReservationRepository extends JpaRepository<Reservation, Long> {

    Page<Reservation> findAllByGuestName(String name, Pageable pageable);

    Page<Reservation> findAllBy(Pageable pageable);
}

Service

@Service
@RequiredArgsConstructor
@Transactional
public class ReservationService {

    private final ReservationRepository reservationRepository;
    private final RoomRepository roomRepository;
    private final UserRepository userRepository;

    //예약 저장
    public void save(ReservationRequest request) {
        //roomId 가져와서 연결
        Room room = roomRepository.findById(request.getRoomId())
                .orElseThrow(()-> new RuntimeException("Room not found"));
        //userId 가져와서 연결
        User user = userRepository.findById(request.getUserId())
                .orElseThrow(()-> new RuntimeException("User not found"));
        //totalPrice
        double totalPrice = ChronoUnit.DAYS.between(request.getCheckInDate(), request.getCheckOutDate()) * room.getPrice();
        
        Reservation reservation = Reservation.builder()
                .room(room)
                .guestName(request.getGuestName())
                .checkInDate(request.getCheckInDate())
                .checkOutDate(request.getCheckOutDate())
                .totalPrice(totalPrice)
                .people(request.getPeople())
                .poneNumber(request.getPoneNumber())
                .user(user)
                .build();

        reservationRepository.save(reservation);
    }
    
    //아이디로 단건 예약 찾아오기
    public Reservation findById(Long id) {
        Optional<Reservation> byId = reservationRepository.findById(id);
        return byId.orElseThrow(()->
                new RuntimeException("없는 예약입니다."));
    }

    //이름으로 예약 찾기
    public Page<ReservationResponse> findByName(String name, PageRequest request) {
        Page<Reservation> all = reservationRepository.findAllByGuestName(name, request);
        return all.map(r-> new ReservationResponse(r));
    }

    //전체 예약 찾기
    public Page<ReservationResponse> findAll(Pageable pageable) {
        Page<Reservation> allBy = reservationRepository.findAllBy(pageable);
        return allBy.map(m-> new ReservationResponse(m));
    }

    //예약 변경(업데이트)
    public ReservationResponse changeDate(Long id,ReservationRequest request) {
        Optional<Reservation> byId = reservationRepository.findById(id);
        if (byId.isEmpty()) throw new RuntimeException("예약이 없습니다.");

        Room room = roomRepository.findById(request.getRoomId()).orElseThrow();
        User user = userRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found"));

        Reservation reservation = new Reservation(id, room, request.getGuestName(), request.getCheckInDate(), request.getCheckOutDate(),
                byId.get().getTotalPrice(), request.getPeople(), request.getPoneNumber(), user);
        Reservation save = reservationRepository.save(reservation);
        return new ReservationResponse(save);

    }

    // 아이디로 예약 지우기
    public void deleteById(Long id) {
        reservationRepository.deleteById(id);
    }
}

Controller

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/reservation")
public class ReservationController {
    private final ReservationService reservationService;

    @PostMapping
    public void insert(@RequestBody ReservationRequest request) {
        reservationService.save(request);
    }
    
    @GetMapping("{id}")
    public Reservation getById(@PathVariable("id") Long id) {
        return reservationService.findById(id);
    }

    /*@GetMapping
    public Page<ReservationResponse> findName(
            @RequestParam(name = "name", required = false, defaultValue = "") String name,
            @RequestParam(name = "size", required = false, defaultValue = "5") Integer size,
            @RequestParam(name = "page", required = false, defaultValue = "0") Integer page) {
        PageRequest request = PageRequest.of(page, size);
        return reservationService.findByName(name, request);
    }*/
    
    @GetMapping
    public Page<ReservationResponse> findAll(
            @RequestParam(name = "size", required = false, defaultValue = "10") Integer size,
            @RequestParam(name = "page", required = false, defaultValue = "0") Integer page) {
        PageRequest request = PageRequest.of(page, size);
        return reservationService.findAll(request);
    }

    @PutMapping("{id}")
    public void changeData(@PathVariable("id") Long id,
                           @RequestBody ReservationRequest request) {
        reservationService.changeDate(id, request);
    }

    @DeleteMapping("{id}")
    public void deleteById(@PathVariable("id") Long id) {
        reservationService.deleteById(id);
    }

    //totalPrice test
    @GetMapping("/price")
    public void price() {
        Reservation byId = reservationService.findById(1L);
        System.out.println(ChronoUnit.DAYS.between(byId.getCheckInDate(), byId.getCheckOutDate()));
    }
}

Response

@AllArgsConstructor
@NoArgsConstructor
@Getter
public class ReservationResponse {
    private Long reservationId;
    private String guestName;
    private LocalDate checkInDate;
    private LocalDate checkOutDate;
    private Double totalPrice;
    private User userId;
    private Integer people;
    private String poneNumber;

    public ReservationResponse(Reservation reservation) {
        this.reservationId = reservation.getReservationId();
        this.guestName = reservation.getGuestName();
        this.checkInDate = reservation.getCheckInDate();
        this.checkOutDate = reservation.getCheckOutDate();
        this.totalPrice = reservation.getTotalPrice();
        this.userId = reservation.getUser();
        this.people = reservation.getPeople();
        this.poneNumber = reservation.getPoneNumber();
    }
}

Request

@Getter
@AllArgsConstructor
public class ReservationRequest {
    private Long roomId;
    private String guestName;
    private LocalDate checkInDate;
    private LocalDate checkOutDate;
    private Long userId;
    private Integer people;
    private String poneNumber;
}

0개의 댓글

관련 채용 정보