package com.breakwater.kycservice.common.repository;
import com.breakwater.common.cockroach.repository.support.QuerydslRepositorySupport;
import com.breakwater.kycservice.common.dto.DocumentResultDTO;
import com.breakwater.kycservice.common.model.DocumentResult;
import com.breakwater.kycservice.common.model.QDocumentResult;
import com.breakwater.kycservice.external.hooyu.dto.query.DocumentResultCollectionQuery;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.r2dbc.core.R2dbcEntityOperations;
import reactor.core.publisher.Mono;
import java.util.UUID;
import static com.breakwater.kycservice.common.model.QDocumentResult.document_result;
import static com.breakwater.kycservice.request.model.QKycRequest.kyc_request;
import static com.querydsl.sql.SQLExpressions.*;
public class DocumentResultRepositoryImpl extends QuerydslRepositorySupport<DocumentResult, UUID>
implements DocumentResultRepositoryCustom {
public DocumentResultRepositoryImpl(R2dbcEntityOperations r2dbcEntityOperations) {
super(r2dbcEntityOperations, DocumentResult.class);
}
@Override
public Mono<Page<DocumentResultDTO>> findByCollectionQuery(DocumentResultCollectionQuery query, Pageable pageable) {
var sqlQuery = createQuery();
var documentResults = new QDocumentResult("document_result");
if (query.onlyLatest()) {
sqlQuery.with(documentResults, select(all, rowNumber().over()
.partitionBy(document_result.type)
.orderBy(document_result.dateRequested.desc()).as("rn"))
.from(document_result));
}
sqlQuery.select(ExpressionUtils.template(Object[].class, documentResults + ".*"),
kyc_request.playerId,
kyc_request.businessUnitId,
kyc_request.createdByUsername.as("requested_by"),
kyc_request.updatedByUsername.as("updated_by"))
.from(documentResults)
.leftJoin(kyc_request).on(documentResults.requestId.eq(kyc_request.id))
.where(predicate(query, documentResults));
return findBy(sqlQuery, pageable, DocumentResultDTO.class);
}
private Predicate predicate(DocumentResultCollectionQuery query, QDocumentResult documentResult) {
var predicate = new BooleanBuilder();
predicate.and(kyc_request.playerId.eq(query.playerId()));
predicate.and(kyc_request.businessUnitId.eq(query.businessUnitId()));
if (query.providerType() != null) {
predicate.and(kyc_request.provider.eq(query.providerType()));
}
if (query.status() != null) {
predicate.and(documentResult.status.eq(query.status()));
}
if (query.documentType() != null) {
predicate.and(documentResult.type.eq(query.documentType()));
}
return predicate;
}
}