Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

task completed #46

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
Expand Down Expand Up @@ -47,7 +49,9 @@ public AccommodationDto addAccommodation(
description = "Retrieves a list of all accommodations available in the system."
)
@GetMapping
public List<AccommodationDto> getAllAccommodations(Pageable pageable) {
public List<AccommodationDto> getAllAccommodations(
@ParameterObject @PageableDefault(size = 20, sort = "id") Pageable pageable
) {
return accommodationService.getAccommodations(pageable);
}

Expand All @@ -57,7 +61,9 @@ public List<AccommodationDto> getAllAccommodations(Pageable pageable) {
)
@GetMapping("/{id}")
@PreAuthorize("hasRole('USER')")
public AccommodationDto getAccommodationById(@PathVariable Long id) {
public AccommodationDto getAccommodationById(
@PathVariable Long id
) {
return accommodationService.getAccommodation(id);
}

Expand All @@ -69,7 +75,8 @@ public AccommodationDto getAccommodationById(@PathVariable Long id) {
@PreAuthorize("hasRole('ADMIN')")
public AccommodationDto updateAccommodation(
@PathVariable Long id,
@RequestBody @Valid CreateAccommodationRequestDto updatedAccommodation) {
@RequestBody @Valid CreateAccommodationRequestDto updatedAccommodation
) {
return accommodationService.updateAccommodation(id, updatedAccommodation);
}

Expand All @@ -82,7 +89,8 @@ public AccommodationDto updateAccommodation(
@PreAuthorize("hasRole('ADMIN')")
public AccommodationDto partiallyUpdateAccommodation(
@PathVariable Long id,
@RequestBody @Valid CreateAccommodationRequestDto updatedAccommodation) {
@RequestBody @Valid CreateAccommodationRequestDto updatedAccommodation
) {
return accommodationService.patchAccommodation(id, updatedAccommodation);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
Expand Down Expand Up @@ -39,7 +41,8 @@ public class BookingController {
)
public BookingResponseDto createBooking(
@AuthenticationPrincipal User user,
@RequestBody @Valid BookingRequestDto requestDto) {
@RequestBody @Valid BookingRequestDto requestDto
) {
return bookingService.createBooking(user.getId(), requestDto);
}

Expand All @@ -50,9 +53,10 @@ public BookingResponseDto createBooking(
description = "Get list of bookings based on status"
)
public List<BookingResponseDto> getUsersBookingsByStatus(
Pageable pageable,
@ParameterObject @PageableDefault(size = 20, sort = "id") Pageable pageable,
@RequestParam(name = "user_id") Long userId,
@RequestParam Status status) {
@RequestParam Status status
) {
return bookingService.getUsersBookingsByStatus(pageable, userId, status);
}

Expand All @@ -63,8 +67,9 @@ public List<BookingResponseDto> getUsersBookingsByStatus(
description = "Get list of bookings for current user"
)
public List<BookingResponseDto> getUsersBookings(
Pageable pageable,
@AuthenticationPrincipal User user) {
@ParameterObject @PageableDefault(size = 20, sort = "id") Pageable pageable,
@AuthenticationPrincipal User user
) {
return bookingService.getBookingsByUserId(pageable, user.getId());
}

Expand All @@ -76,7 +81,8 @@ public List<BookingResponseDto> getUsersBookings(
)
public BookingResponseDto getBookingById(
@AuthenticationPrincipal User user,
@PathVariable Long bookingId) {
@PathVariable Long bookingId
) {
return bookingService.getBookingById(
user.getId(),
user.getRoles(),
Expand All @@ -93,7 +99,8 @@ public BookingResponseDto getBookingById(
public BookingResponseDto updateBooking(
@AuthenticationPrincipal User user,
@PathVariable Long bookingId,
@RequestBody @Valid BookingUpdateDto updateDtoDto) {
@RequestBody @Valid BookingUpdateDto updateDtoDto
) {
return bookingService.updateBookingById(
user.getId(),
user.getRoles(),
Expand All @@ -109,7 +116,8 @@ public BookingResponseDto updateBooking(
)
public BookingResponseDto deleteBooking(
@AuthenticationPrincipal User user,
@PathVariable Long bookingId) {
@PathVariable Long bookingId
) {
return bookingService.deleteBookingById(
user.getId(),
user.getRoles(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,16 @@
import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.Authentication;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RequiredArgsConstructor
Expand All @@ -27,7 +28,6 @@ public class PaymentController {
private final StripeService stripeService;

@PostMapping("/payments")
@ResponseBody
@Operation(
summary = "Create session",
description = "You can create new session. You need to give bookingId, "
Expand All @@ -40,12 +40,13 @@ public PaymentResponseDto createSession(
}

@GetMapping("/payments/{id}")
@ResponseBody
@Operation(
summary = "Retrieve session",
description = "You can retrieve session by sessionId. "
+ "Returns status for this session")
public PaymentResponseDto retrieveSession(@PathVariable String id) {
public PaymentResponseDto retrieveSession(
@PathVariable String id
) {
return stripeService.retrieveSession(id);
}

Expand All @@ -55,8 +56,9 @@ public PaymentResponseDto retrieveSession(@PathVariable String id) {
+ "will be redirected to this endpoint."
)
@GetMapping("/payments/cancel")
@ResponseBody
public PaymentResponseDto handleCancel(@RequestParam("session_id") String sessionId) {
public PaymentResponseDto handleCancel(
@RequestParam("session_id") String sessionId
) {
return stripeService.retrieveSession(sessionId);
}

Expand All @@ -65,8 +67,9 @@ public PaymentResponseDto handleCancel(@RequestParam("session_id") String sessio
description = "When you confirm the payment you will be redirected to this endpoint."
)
@GetMapping("/payments/success")
@ResponseBody
public PaymentResponseDto handleSuccess(@RequestParam("session_id") String sessionId) {
public PaymentResponseDto handleSuccess(
@RequestParam("session_id") String sessionId
) {
return stripeService.retrieveSession(sessionId);
}

Expand All @@ -75,9 +78,9 @@ public PaymentResponseDto handleSuccess(@RequestParam("session_id") String sessi
description = "Get all payment operations by users id."
)
@GetMapping("/payments")
@ResponseBody
public List<PaymentResponseDto> findPayments(
@RequestParam Long userId, Pageable pageable
@RequestParam Long userId,
@ParameterObject @PageableDefault(size = 20, sort = "id") Pageable pageable
) {
return stripeService.findPaymentsByUserId(userId, pageable);
}
Expand Down
22 changes: 15 additions & 7 deletions src/main/java/com/ua/accommodation/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,11 @@ public class UserController {
@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
@Operation(
summary = "Get information about user",
description = "Get information about current authenticate user")
public UserResponseDto getUser(@AuthenticationPrincipal User user) {
description = "Get information about current authenticate user"
)
public UserResponseDto getUser(
@AuthenticationPrincipal User user
) {
return userService.getUser(user.getEmail());
}

Expand All @@ -41,10 +44,12 @@ public UserResponseDto getUser(@AuthenticationPrincipal User user) {
@Operation(
summary = "Update roles",
description = "Update roles for user by user id. Available only for admins. "
+ "You need make request with Set roles. Don't forget about id")
+ "You need make request with Set roles. Don't forget about id"
)
public UserResponseDto updateRoles(
@PathVariable Long id,
@RequestBody @Valid UserUpdateRoleDto updateRoleDto) {
@RequestBody @Valid UserUpdateRoleDto updateRoleDto
) {
return userService.updateRoles(id, updateRoleDto);
}

Expand All @@ -54,10 +59,12 @@ public UserResponseDto updateRoles(
summary = "Update profile",
description = "You can update personal info about user. "
+ "You need give all fields in request. "
+ "If you don't wanna change something just give old value")
+ "If you don't wanna change something just give old value"
)
public UserResponseDto updateProfile(
@AuthenticationPrincipal User user,
@RequestBody @Valid UserUpdateProfileDto updateProfileDto) {
@RequestBody @Valid UserUpdateProfileDto updateProfileDto
) {
return userService.updateProfile(user.getId(), updateProfileDto);
}

Expand All @@ -70,7 +77,8 @@ public UserResponseDto updateProfile(
)
public UserResponseDto updateEmail(
@AuthenticationPrincipal User user,
@RequestBody @Valid UserUpdateEmailDto updateDto) {
@RequestBody @Valid UserUpdateEmailDto updateDto
) {
return userService.updateEmail(user.getEmail(), updateDto);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,21 @@ public PaymentResponseDto createPaymentSession(
var duration = java.time.temporal.ChronoUnit.DAYS.between(
booking.getCheckInDate(),
booking.getCheckOutDate());
var amountTopay = accommodation.dailyRate().multiply(BigDecimal.valueOf(duration));
var amountToPay = accommodation.dailyRate().multiply(BigDecimal.valueOf(duration));
User user = (User) authentication.getPrincipal();
return getPaymentResponseDto(sessionDto, user, amountToPay);
}

private PaymentResponseDto getPaymentResponseDto(
PaymentRequestDto sessionDto,
User user,
BigDecimal amountToPay
) {
try {
Customer customer = findOrCreateCustomer(
user.getEmail(), user.getFirstName());
SessionCreateParams.Builder sessionCreateParamsBuilder = getParamsBuilder(
sessionDto, customer, amountTopay);
sessionDto, customer, amountToPay);

SessionCreateParams.PaymentIntentData paymentIntentData =
SessionCreateParams.PaymentIntentData.builder()
Expand Down Expand Up @@ -98,19 +106,24 @@ public PaymentResponseDto retrieveSession(String id) {
);
PaymentResponseDto responseDto = paymentMapper.toDto(payment);
if (session.getPaymentStatus().equals("paid")) {
payment.setStatus(Payment.Status.PAID);
paymentRepository.save(payment);
responseDto = paymentMapper.toDto(payment);
Booking booking = bookingService.getBooking(payment.getBookingId());
booking.setStatus(Booking.Status.CONFIRMED);
bookingService.saveBooking(booking);
responseDto.setMessage("Payment successful.");
return responseDto;
return getPaymentResponseDtoFromPayment(payment);
}
responseDto.setMessage("Payment paused, you can complete it later.");
return responseDto;
}

private PaymentResponseDto getPaymentResponseDtoFromPayment(Payment payment) {
PaymentResponseDto responseDto;
payment.setStatus(Payment.Status.PAID);
paymentRepository.save(payment);
responseDto = paymentMapper.toDto(payment);
Booking booking = bookingService.getBooking(payment.getBookingId());
booking.setStatus(Booking.Status.CONFIRMED);
bookingService.saveBooking(booking);
responseDto.setMessage("Payment successful.");
return responseDto;
}

@Scheduled(cron = "0 0 */1 * * *", zone = "Europe/Kiev")
public void checkExpiredSessions() {
List<Payment> expiredPayments =
Expand All @@ -128,7 +141,7 @@ public List<PaymentResponseDto> findPaymentsByUserId(Long userId, Pageable pagea

public SessionCreateParams.Builder getParamsBuilder(
PaymentRequestDto sessionDto, Customer customer,
BigDecimal amountTopay) {
BigDecimal amountToPay) {
SessionCreateParams.Builder sessionCreateParamsBuilder = SessionCreateParams.builder()
.setMode(SessionCreateParams.Mode.PAYMENT)
.setCustomer(customer.getId())
Expand All @@ -149,7 +162,7 @@ public SessionCreateParams.Builder getParamsBuilder(
.build()
)
.setCurrency("USD")
.setUnitAmountDecimal(amountTopay
.setUnitAmountDecimal(amountToPay
.multiply(BigDecimal.valueOf(100L))
)
.build())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
Expand Down Expand Up @@ -79,12 +80,13 @@ void addAccommodation_ValidRequest_ReturnsCreatedAccommodation() throws Exceptio
@WithMockUser(username = "testUser", roles = {"USER"})
void getAllAccommodations_ValidRequest_ReturnsListOfAccommodations() throws Exception {
List<AccommodationDto> accommodations = Collections.singletonList(createResponseDto());
Pageable pageable = PageRequest.of(0, 10);
Pageable pageable = PageRequest.of(0, 20, Sort.by("id"));
given(accommodationService.getAccommodations(pageable)).willReturn(accommodations);

mockMvc.perform(get("/accommodations")
.param("page", "0")
.param("size", "10")
.param("size", "20")
.param("sort", "id")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(objectMapper.writeValueAsString(accommodations)));
Expand Down
Loading
Loading