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

Issue #222: Add pagination results for payments #223

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
6 changes: 5 additions & 1 deletion api/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ dependencies {
implementation "io.springfox:springfox-swagger-ui:${springFoxVersion}"
implementation "io.springfox:springfox-spring-web:${springFoxVersion}"
implementation "org.springframework.data:spring-data-commons:${springBootVersion}"

compileOnly "org.projectlombok:lombok:${lombokVersion}"
annotationProcessor "org.projectlombok:lombok:${lombokVersion}"
}

task generateOpenApiSpec(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask) {
Expand All @@ -52,7 +55,8 @@ task generateOpenApiSpec(type: org.openapitools.generator.gradle.plugin.tasks.Ge
"booleanGetterPrefix" : "is"
]
importMappings = [
'Pageable': 'org.springframework.data.domain.Pageable'
'Pageable': 'org.springframework.data.domain.Pageable',
'PageInfo': 'com.myhome.utils.PageInfo'
]
}
compileJava.dependsOn(generateOpenApiSpec)
Expand Down
27 changes: 27 additions & 0 deletions api/src/main/java/com/myhome/utils/PageInfo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.myhome.utils;

import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

@EqualsAndHashCode
@ToString
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class PageInfo {
private final int currentPage;
private final int pageLimit;
private final int totalPages;
private final long totalElements;

public static PageInfo of(Pageable pageable, Page<?> page) {
return new PageInfo(
pageable.getPageNumber(),
pageable.getPageSize(),
page.getTotalPages(),
page.getTotalElements()
);
}
}
23 changes: 22 additions & 1 deletion api/src/main/resources/public/swagger/api.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,11 @@ paths:
type: string
required: true
description: "adminId for getting all admin scheduled"
- in: query
name: pageable
required: false
schema:
$ref: '#/components/schemas/Pageable'
responses:
'200':
description: "If communityId and adminId are valid. Response body has the details"
Expand Down Expand Up @@ -1022,6 +1027,20 @@ components:
type: integer
size:
type: integer
PageInfo:
description: Page info
type: object
properties:
currentPage:
type: integer
pageLimit:
type: integer
totalPages:
type: integer
totalElements:
type: integer
format: int64

CreateCommunityRequest:
type: object
required:
Expand Down Expand Up @@ -1265,4 +1284,6 @@ components:
type: array
items:
$ref: '#/components/schemas/AdminPayment'
uniqueItems: true
uniqueItems: true
pageInfo:
$ref: '#/components/schemas/PageInfo'
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ ext {
set('fasterXmlJacksonAnnotationsVersion', "2.11.2")
set('jacksonDatabindNullableVersion', "0.2.1")
set('springFoxVersion', "2.8.0")
set('lombokVersion', "1.18.18")
}

jar {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import com.myhome.model.AddCommunityAdminResponse;
import com.myhome.model.AddCommunityHouseRequest;
import com.myhome.model.AddCommunityHouseResponse;
import com.myhome.model.AdminPayment;
import com.myhome.model.CommunityHouseName;
import com.myhome.model.CreateCommunityRequest;
import com.myhome.model.CreateCommunityResponse;
Expand All @@ -41,17 +42,20 @@
import com.myhome.model.GetHouseDetailsResponse;
import com.myhome.model.ListAdminPaymentsResponse;
import com.myhome.model.ListCommunityAdminsResponse;
import com.myhome.utils.PageInfo;
import com.myhome.services.AmenityService;
import com.myhome.services.CommunityService;
import com.myhome.services.PaymentService;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
Expand Down Expand Up @@ -240,37 +244,32 @@ public ResponseEntity<AddAmenityResponse> addAmenityToCommunity(

@Override
public ResponseEntity<ListAdminPaymentsResponse> listAllAdminScheduledPayments(
String communityId, String adminId) {
String communityId, String adminId, Pageable pageable) {
log.trace("Received request to list all the payments scheduled by the admin with id[{}]",
adminId);

Set<Payment> payments = paymentService.getPaymentsByAdmin(adminId);
final boolean isAdminInGivenCommunity = isAdminInGivenCommunity(communityId, adminId);

return communityService.getCommunityDetailsByIdWithAdmins(communityId)
.map(community -> isAdminMatchingId(community.getAdmins(), adminId))
.map(paymentsMatch -> isAdminMatchingPayment(payments, adminId))
.map(matched -> schedulePaymentApiMapper.adminPaymentSetToRestApiResponseAdminPaymentSet(
payments))
.map(adminPayments -> new ListAdminPaymentsResponse().payments(adminPayments))
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}

private Boolean isAdminMatchingId(Set<User> list, String adminId) {
if (list.stream()
.anyMatch(communityAdmin -> communityAdmin.getUserId().equals(adminId))) {
return true;
if (isAdminInGivenCommunity) {
final Page<Payment> paymentsForAdmin = paymentService.getPaymentsByAdmin(adminId, pageable);
final List<Payment> payments = paymentsForAdmin.getContent();
final Set<AdminPayment> adminPayments =
schedulePaymentApiMapper.adminPaymentSetToRestApiResponseAdminPaymentSet(
new HashSet<>(payments));
final ListAdminPaymentsResponse response = new ListAdminPaymentsResponse()
.payments(adminPayments)
.pageInfo(PageInfo.of(pageable, paymentsForAdmin));
return ResponseEntity.ok().body(response);
}

return null;
return ResponseEntity.notFound().build();
}

private Boolean isAdminMatchingPayment(Set<Payment> payments, String adminId) {
if (payments.stream()
.anyMatch(payment -> payment.getAdmin().getUserId().equals(adminId))) {
return true;
}

return null;
private Boolean isAdminInGivenCommunity(String communityId, String adminId) {
return communityService.getCommunityDetailsByIdWithAdmins(communityId)
.map(community -> community.getAdmins())
.map(admins -> admins.stream().anyMatch(admin -> admin.getUserId().equals(adminId)))
.orElseThrow(
() -> new RuntimeException("Community with given id not exists: " + communityId));
}
}
33 changes: 21 additions & 12 deletions service/src/main/java/com/myhome/controllers/PaymentController.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
package com.myhome.controllers;

import com.myhome.api.PaymentsApi;
import com.myhome.controllers.dto.PaymentDto;
import com.myhome.controllers.mapper.SchedulePaymentApiMapper;
import com.myhome.controllers.request.EnrichedSchedulePaymentRequest;
import com.myhome.domain.CommunityHouse;
import com.myhome.domain.HouseMember;
import com.myhome.domain.User;
Expand All @@ -27,6 +29,7 @@
import com.myhome.services.PaymentService;
import java.util.Optional;
import javax.validation.Valid;
import javax.xml.ws.Response;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
Expand All @@ -49,18 +52,25 @@ public ResponseEntity<SchedulePaymentResponse> schedulePayment(@Valid
SchedulePaymentRequest request) {
log.trace("Received schedule payment request");

Optional<HouseMember> houseMember = paymentService.getHouseMember(request.getMemberId());
Optional<User> adminOptional = communityService.findCommunityAdminById(request.getAdminId());
HouseMember houseMember = paymentService.getHouseMember(request.getMemberId())
.orElseThrow(() -> new RuntimeException(
"House member with given id not exists: " + request.getMemberId()));
User admin = communityService.findCommunityAdminById(request.getAdminId())
.orElseThrow(
() -> new RuntimeException("Admin with given id not exists: " + request.getAdminId()));

return houseMember.flatMap(member -> adminOptional.filter(
admin -> isUserAdminOfCommunityHouse(member.getCommunityHouse(), admin)))
.map(admin -> schedulePaymentApiMapper.enrichedSchedulePaymentRequestToPaymentDto(
schedulePaymentApiMapper.enrichSchedulePaymentRequest(request, admin,
houseMember.get())))
.map(paymentService::schedulePayment)
.map(schedulePaymentApiMapper::paymentToSchedulePaymentResponse)
.map(response -> ResponseEntity.status(HttpStatus.CREATED).body(response))
.orElseGet(() -> ResponseEntity.notFound().build());
if (isUserAdminOfCommunityHouse(houseMember.getCommunityHouse(), admin)) {
final EnrichedSchedulePaymentRequest paymentRequest =
schedulePaymentApiMapper.enrichSchedulePaymentRequest(request, admin, houseMember);
final PaymentDto paymentDto =
schedulePaymentApiMapper.enrichedSchedulePaymentRequestToPaymentDto(paymentRequest);
final PaymentDto processedPayment = paymentService.schedulePayment(paymentDto);
final SchedulePaymentResponse paymentResponse =
schedulePaymentApiMapper.paymentToSchedulePaymentResponse(processedPayment);
return ResponseEntity.status(HttpStatus.CREATED).body(paymentResponse);
}

return ResponseEntity.notFound().build();
}

private Boolean isUserAdminOfCommunityHouse(CommunityHouse communityHouse, User admin) {
Expand All @@ -78,5 +88,4 @@ public ResponseEntity<SchedulePaymentResponse> listPaymentDetails(String payment
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import com.myhome.domain.Payment;
import java.util.Optional;
import java.util.Set;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

/**
* Interface for service layer
Expand All @@ -32,7 +34,7 @@ public interface PaymentService {

Set<Payment> getPaymentsByMember(String memberId);

Set<Payment> getPaymentsByAdmin(String adminId);
Page<Payment> getPaymentsByAdmin(String adminId, Pageable pageable);

Optional<HouseMember> getHouseMember(String memberId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
Expand Down Expand Up @@ -82,7 +84,7 @@ public Set<Payment> getPaymentsByMember(String memberId) {
}

@Override
public Set<Payment> getPaymentsByAdmin(String adminId) {
public Page<Payment> getPaymentsByAdmin(String adminId, Pageable pageable) {
ExampleMatcher ignoringMatcher = ExampleMatcher.matchingAll()
.withMatcher("adminId",
ExampleMatcher.GenericPropertyMatchers.startsWith().ignoreCase())
Expand All @@ -94,7 +96,7 @@ public Set<Payment> getPaymentsByAdmin(String adminId) {
new Payment(null, null, null, null, false, null, new User().withUserId(adminId), null),
ignoringMatcher);

return new HashSet<>(paymentRepository.findAll(paymentExample));
return paymentRepository.findAll(paymentExample, pageable);
}

private PaymentDto createPaymentInRepository(PaymentDto request) {
Expand Down
Loading