Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 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
43 changes: 43 additions & 0 deletions src/main/java/org/folio/orders/utils/FundDistributionUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,30 @@
import static java.math.RoundingMode.HALF_EVEN;
import static org.folio.rest.core.exceptions.ErrorCodes.CANNOT_MIX_TYPES_FOR_ZERO_PRICE;
import static org.folio.rest.core.exceptions.ErrorCodes.INCORRECT_FUND_DISTRIBUTION_TOTAL;
import static org.folio.rest.core.exceptions.ErrorCodes.FISCAL_YEAR_DISTRIBUTION_COUNT_MISMATCH;
import static org.folio.rest.jaxrs.model.FundDistribution.DistributionType.AMOUNT;
import static org.folio.rest.jaxrs.model.FundDistribution.DistributionType.PERCENTAGE;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

import org.apache.commons.collections4.CollectionUtils;
import org.folio.rest.core.exceptions.HttpException;
import org.folio.rest.jaxrs.model.PoLine;
import org.folio.rest.jaxrs.model.Cost;
import org.folio.rest.jaxrs.model.Error;
import org.folio.rest.jaxrs.model.FundDistribution;
import org.folio.rest.jaxrs.model.Parameter;
import org.folio.rest.jaxrs.model.PaymentTerms;

import com.google.common.collect.Lists;

public final class FundDistributionUtils {

public static final String REMAINING_AMOUNT_FIELD = "remainingAmount";
public static final String PREPAYMENT_TERM_PARAM = "prepaymentTerm";
public static final String FISCAL_YEAR_DISTRIBUTION_COUNT_PARAM = "fiscalYearDistributionCount";

private static final BigDecimal ZERO_REMAINING_AMOUNT = BigDecimal.ZERO.setScale(2, HALF_EVEN);
private static final BigDecimal ONE_HUNDRED_PERCENT = BigDecimal.valueOf(100);
Expand Down Expand Up @@ -83,6 +89,43 @@ public static boolean isFundDistributionsPresent(List<PoLine> poLines) {
return poLines.stream().mapToLong(poLine -> poLine.getFundDistribution().size()).sum() >= 1;
}

public static void validateFundDistributionForMultiYear(List<PoLine> poLines) {
for (PoLine poLine : poLines) {
List<Error> errors = validatePrepaymentTerm(poLine);
if (!errors.isEmpty()) {
throw new HttpException(422, errors.getFirst());
}
}
}

public static List<Error> validatePrepaymentTerm(PoLine poLine) {
if (!Boolean.TRUE.equals(poLine.getMultiYearPayment())) {
Comment thread
ykashtalian marked this conversation as resolved.
Outdated
return List.of();
}
PaymentTerms paymentTerms = poLine.getPaymentTerms();
if (paymentTerms == null) {
return List.of();
}
Integer prepaymentTerm = paymentTerms.getPrepaymentTerm();
if (prepaymentTerm == null || prepaymentTerm <= 0) {
return List.of();
}
long fiscalYearDistributionCount = CollectionUtils.emptyIfNull(paymentTerms.getFiscalYearDistributions()).stream()
.filter(Objects::nonNull)
Comment thread
ykashtalian marked this conversation as resolved.
Outdated
.count();
if (fiscalYearDistributionCount != prepaymentTerm) {
return List.of(buildPrepaymentTermMismatchError(prepaymentTerm, fiscalYearDistributionCount));
}
return List.of();
}

private static Error buildPrepaymentTermMismatchError(int prepaymentTerm, long fiscalYearDistributionCount) {
return FISCAL_YEAR_DISTRIBUTION_COUNT_MISMATCH.toError().withParameters(Lists.newArrayList(
new Parameter().withKey(PREPAYMENT_TERM_PARAM).withValue(String.valueOf(prepaymentTerm)),
new Parameter().withKey(FISCAL_YEAR_DISTRIBUTION_COUNT_PARAM).withValue(String.valueOf(fiscalYearDistributionCount))
));
}

private static void checkRemainingPercentMatchesToZero(BigDecimal remainingPercent, Double poLineEstimatedPrice) {
BigDecimal epsilon = BigDecimal.valueOf(1e-10);
if (remainingPercent.abs().compareTo(epsilon) > 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,8 @@ public enum ErrorCodes {
UNABLE_TO_GENERATE_CLAIMS_FOR_ORG_NO_INTEGRATION_DETAILS("unableToGenerateClaimsForOrgNoIntegrationDetails", "Unable to generate claims for %s because no claim integrations exist"),
ALL_PIECES_MUST_HAVE_THE_SAME_POLINE_ID_AND_TITLE_ID("allPiecesMustHaveTheSamePoLineIdAndTitleId", "All pieces in the batch should have the same titleId and poLineId"),
EXISTING_HOLDINGS_FOR_DELETE_CONFIRMATION("existingHoldingsForDeleteConfirmation", "There are existing holdings to delete, Try again with 'deleteHoldings' param"),
EXISTING_RECEIVED_PIECES_TITLE_REMOVAL("existingReceivedPiecesTitleRemoval", "Unable to remove the title as there are pieces with a 'Received' status associated with it");
EXISTING_RECEIVED_PIECES_TITLE_REMOVAL("existingReceivedPiecesTitleRemoval", "Unable to remove the title as there are pieces with a 'Received' status associated with it"),
FISCAL_YEAR_DISTRIBUTION_COUNT_MISMATCH("fiscalYearDistributionCountMismatch", "The number of fiscal year distributions must exactly match the prepayment term");

private final String code;
private final String description;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.folio.orders.utils.FundDistributionUtils.validatePrepaymentTerm;
import static org.folio.orders.utils.HelperUtils.calculateEstimatedPrice;
import static org.folio.orders.utils.PoLineCommonUtil.extractUnaffiliatedLocations;
import static org.folio.orders.utils.PoLineCommonUtil.getElectronicCostQuantity;
Expand Down Expand Up @@ -75,8 +76,9 @@ public Future<List<Error>> validatePoLine(PoLine poLine, RequestContext requestC
.map(v -> errors.addAll(validateReceivingWorkflowForReceiptNotRequired(poLine)))
.map(v -> errors.addAll(validateForBinadryActive(poLine)))
.map(b -> errors.addAll(validateLocations(poLine)))
.map(b -> errors.addAll(validateCostPrices(poLine)))
.map(b -> {
errors.addAll(validateCostPrices(poLine));
errors.addAll(validatePrepaymentTerm(poLine));
return errors;
});
Comment thread
ykashtalian marked this conversation as resolved.
Outdated
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,18 @@ public Future<Void> validate(CompositePurchaseOrder compPO, CompositePurchaseOrd
.mapEmpty()
);

Future<Void> validateMultiYearPrepaymentFuture = Future.succeededFuture().map(v -> {
FundDistributionUtils.validateFundDistributionForMultiYear(compPO.getPoLines());
return null;
});

futures.add(expenseClassValidationService.validateExpenseClasses(compPO.getPoLines(), true, requestContext));
futures.add(checkLocationsAndPiecesConsistency(compPO.getPoLines(), requestContext));
futures.add(validateFundDistributionTotal(compPO.getPoLines()));
futures.add(validateFundsAndPopulateCodes(compPO.getPoLines(), requestContext));
futures.add(validateMaterialTypesFuture);
futures.add(validateEncumbrancesFuture);
futures.add(validateMultiYearPrepaymentFuture);

return Future.join(futures).mapEmpty();
}
Expand Down
115 changes: 115 additions & 0 deletions src/test/java/org/folio/orders/utils/FundDistributionUtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,138 @@

import static java.util.Collections.singletonList;
import static org.folio.rest.core.exceptions.ErrorCodes.INCORRECT_FUND_DISTRIBUTION_TOTAL;
import static org.folio.rest.core.exceptions.ErrorCodes.FISCAL_YEAR_DISTRIBUTION_COUNT_MISMATCH;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;

import org.folio.rest.core.exceptions.HttpException;
import org.folio.rest.jaxrs.model.Error;
import org.folio.rest.jaxrs.model.FiscalYearDistribution;
import org.folio.rest.jaxrs.model.PoLine;
import org.folio.rest.jaxrs.model.Cost;
import org.folio.rest.jaxrs.model.FundDistribution;
import org.folio.rest.jaxrs.model.FundDistribution.DistributionType;
import org.folio.rest.jaxrs.model.PaymentTerms;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;

public class FundDistributionUtilsTest {

@ParameterizedTest(name = "{0}")
@MethodSource("noThrowCases")
void shouldReturnNoErrors_whenValidatePrepaymentTermConditionBypassed(String scenario, PoLine poLine) {
List<Error> errors = FundDistributionUtils.validatePrepaymentTerm(poLine);

assertTrue(errors.isEmpty());
}

static Stream<Arguments> noThrowCases() {
return Stream.of(
Arguments.of("multiYearPayment is false",
new PoLine()
.withMultiYearPayment(false)
.withPaymentTerms(new PaymentTerms()
.withTotalPrice(100.0)
.withPrepaymentTerm(3)
.withStartingFiscalYearId(UUID.randomUUID().toString())
.withFiscalYearDistributions(List.of(
new FiscalYearDistribution().withFiscalYearId(UUID.randomUUID().toString())
)))),
Arguments.of("paymentTerms is null",
new PoLine()
.withMultiYearPayment(true)
.withPaymentTerms(null)),
Arguments.of("prepaymentTerm is null",
new PoLine()
.withMultiYearPayment(true)
.withPaymentTerms(new PaymentTerms()
.withTotalPrice(100.0)
.withPrepaymentTerm(null)
.withStartingFiscalYearId(UUID.randomUUID().toString()))),
Arguments.of("prepaymentTerm is zero",
new PoLine()
.withMultiYearPayment(true)
.withPaymentTerms(new PaymentTerms()
.withTotalPrice(100.0)
.withPrepaymentTerm(0)
.withStartingFiscalYearId(UUID.randomUUID().toString()))),
Arguments.of("prepaymentTerm is negative",
new PoLine()
.withMultiYearPayment(true)
.withPaymentTerms(new PaymentTerms()
.withTotalPrice(100.0)
.withPrepaymentTerm(-1)
.withStartingFiscalYearId(UUID.randomUUID().toString()))),
Arguments.of("fiscalYearDistributions count equals prepaymentTerm",
new PoLine()
.withMultiYearPayment(true)
.withPaymentTerms(new PaymentTerms()
.withTotalPrice(100.0)
.withPrepaymentTerm(2)
.withStartingFiscalYearId(UUID.randomUUID().toString())
.withFiscalYearDistributions(List.of(
new FiscalYearDistribution().withFiscalYearId(UUID.randomUUID().toString()),
new FiscalYearDistribution().withFiscalYearId(UUID.randomUUID().toString())
))))
);
}

@ParameterizedTest(name = "{0}")
@MethodSource("errorCases")
void shouldReturnError_whenFiscalYearDistributionCountMismatch(
String scenario, int prepaymentTerm, Integer distributionCount,
String expectedTermParam, String expectedCountParam) {

PaymentTerms paymentTerms = new PaymentTerms()
.withTotalPrice(100.0)
.withPrepaymentTerm(prepaymentTerm)
.withStartingFiscalYearId(UUID.randomUUID().toString());

if (distributionCount != null) {
List<FiscalYearDistribution> distributions = new ArrayList<>();
for (int i = 0; i < distributionCount; i++) {
distributions.add(new FiscalYearDistribution().withFiscalYearId(UUID.randomUUID().toString()));
}
paymentTerms.withFiscalYearDistributions(distributions);
}

PoLine poLine = new PoLine()
.withMultiYearPayment(true)
.withPaymentTerms(paymentTerms);

List<Error> errors = FundDistributionUtils.validatePrepaymentTerm(poLine);

assertEquals(1, errors.size());
Error error = errors.get(0);
assertEquals(FISCAL_YEAR_DISTRIBUTION_COUNT_MISMATCH.getCode(), error.getCode());
var parameters = error.getParameters();
assertEquals(2, parameters.size());
assertEquals(FundDistributionUtils.PREPAYMENT_TERM_PARAM, parameters.get(0).getKey());
assertEquals(expectedTermParam, parameters.get(0).getValue());
assertEquals(FundDistributionUtils.FISCAL_YEAR_DISTRIBUTION_COUNT_PARAM, parameters.get(1).getKey());
assertEquals(expectedCountParam, parameters.get(1).getValue());
}

static Stream<Arguments> errorCases() {
return Stream.of(
Arguments.of("more distributions than prepaymentTerm", 2, 3, "2", "3"),
Arguments.of("fewer distributions than prepaymentTerm", 3, 2, "3", "2"),
Arguments.of("empty distributions list", 2, 0, "2", "0"),
Arguments.of("no distributions (null list)", 1, null, "1", "0"),
Arguments.of("prepaymentTerm=3 distributions=1", 3, 1, "3", "1")
);
}


@ParameterizedTest
@CsvSource(value = {
"90:percentage:93:percentage:3:incorrectFundDistributionTotal:3.60",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
import static org.folio.rest.core.exceptions.ErrorCodes.*;
import static org.folio.rest.jaxrs.model.PoLine.OrderFormat.OTHER;
import static org.folio.rest.jaxrs.model.PoLine.OrderFormat.P_E_MIX;
import static org.folio.rest.jaxrs.model.FundDistribution.DistributionType.PERCENTAGE;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertTrue;
Expand Down Expand Up @@ -38,6 +40,9 @@
import org.folio.rest.jaxrs.model.Cost;
import org.folio.rest.jaxrs.model.Details;
import org.folio.rest.jaxrs.model.Error;
import org.folio.rest.jaxrs.model.FiscalYearDistribution;
import org.folio.rest.jaxrs.model.FundDistribution;
import org.folio.rest.jaxrs.model.PaymentTerms;
import org.folio.rest.jaxrs.model.Physical;
import org.folio.rest.jaxrs.model.acq.Location;
import org.folio.service.consortium.ConsortiumConfigurationService;
Expand Down Expand Up @@ -412,6 +417,83 @@ void testValidatePoLineWithCheckinItemsFalseAndReceiptNotRequired() {
assertThat(errors.getFirst().getCode(), is(RECEIVING_WORKFLOW_INCORRECT_FOR_RECEIPT_NOT_REQUIRED.getCode()));
}

@Test
void shouldNotReturnErrorWhenMultiYearPaymentFalse() {
PoLine poLine = new PoLine()
.withMultiYearPayment(false)
.withPaymentTerms(new PaymentTerms()
.withTotalPrice(100.0)
.withPrepaymentTerm(3)
.withStartingFiscalYearId(UUID.randomUUID().toString()))
.withOrderFormat(PoLine.OrderFormat.PHYSICAL_RESOURCE)
.withCost(new Cost().withQuantityPhysical(1).withListUnitPrice(10.0))
.withLocations(List.of(new Location().withLocationId(UUID.randomUUID().toString()).withQuantityPhysical(1)));

doReturn(succeededFuture(null))
.when(expenseClassValidationService).validateExpenseClasses(eq(List.of(poLine)), eq(false), eq(requestContext));

Future<List<Error>> future = poLineValidationService.validatePoLine(poLine, requestContext);

if (future.failed()) fail(future.cause());
boolean hasPrepaymentError = future.result().stream()
.anyMatch(e -> FISCAL_YEAR_DISTRIBUTION_COUNT_MISMATCH.getCode().equals(e.getCode()));
assertFalse(hasPrepaymentError);
}

@Test
void shouldNotReturnErrorWhenMultiYearPaymentTrueAndPrepaymentTermMet() {
PoLine poLine = new PoLine()
.withMultiYearPayment(true)
.withPaymentTerms(new PaymentTerms()
.withTotalPrice(100.0)
.withPrepaymentTerm(2)
.withStartingFiscalYearId(UUID.randomUUID().toString())
.withFiscalYearDistributions(List.of(
new FiscalYearDistribution().withFiscalYearId(UUID.randomUUID().toString()),
new FiscalYearDistribution().withFiscalYearId(UUID.randomUUID().toString())
)))
.withOrderFormat(PoLine.OrderFormat.PHYSICAL_RESOURCE)
.withCost(new Cost().withQuantityPhysical(1).withListUnitPrice(10.0))
.withLocations(List.of(new Location().withLocationId(UUID.randomUUID().toString()).withQuantityPhysical(1)));

doReturn(succeededFuture(null))
.when(expenseClassValidationService).validateExpenseClasses(eq(List.of(poLine)), eq(false), eq(requestContext));

Future<List<Error>> future = poLineValidationService.validatePoLine(poLine, requestContext);

if (future.failed()) fail(future.cause());
boolean hasPrepaymentError = future.result().stream()
.anyMatch(e -> FISCAL_YEAR_DISTRIBUTION_COUNT_MISMATCH.getCode().equals(e.getCode()));
assertFalse(hasPrepaymentError);
}

@Test
void shouldReturnErrorWhenPrepaymentTermExceedsFiscalYears() {
PoLine poLine = new PoLine()
.withMultiYearPayment(true)
.withPaymentTerms(new PaymentTerms()
.withTotalPrice(100.0)
.withPrepaymentTerm(3)
.withStartingFiscalYearId(UUID.randomUUID().toString())
.withFiscalYearDistributions(List.of(
new FiscalYearDistribution().withFiscalYearId(UUID.randomUUID().toString()),
new FiscalYearDistribution().withFiscalYearId(UUID.randomUUID().toString())
)))
.withOrderFormat(PoLine.OrderFormat.PHYSICAL_RESOURCE)
.withCost(new Cost().withQuantityPhysical(1).withListUnitPrice(10.0))
.withLocations(List.of(new Location().withLocationId(UUID.randomUUID().toString()).withQuantityPhysical(1)));

doReturn(succeededFuture(null))
.when(expenseClassValidationService).validateExpenseClasses(eq(List.of(poLine)), eq(false), eq(requestContext));

Future<List<Error>> future = poLineValidationService.validatePoLine(poLine, requestContext);

if (future.failed()) fail(future.cause());
boolean hasPrepaymentError = future.result().stream()
.anyMatch(e -> FISCAL_YEAR_DISTRIBUTION_COUNT_MISMATCH.getCode().equals(e.getCode()));
assertTrue(hasPrepaymentError);
}

private Set<String> errorsToCodes(List<Error> errors) {
return errors
.stream()
Expand Down
Loading
Loading