Search in sources :

Example 1 with InvoiceCollection

use of org.folio.rest.jaxrs.model.InvoiceCollection in project mod-invoice by folio-org.

the class InvoiceHelper method getInvoices.

/**
 * Gets list of invoice
 *
 * @param limit Limit the number of elements returned in the response
 * @param offset Skip over a number of elements by specifying an offset value for the query
 * @param query A query expressed as a CQL string using valid searchable fields
 * @return completable future with {@link InvoiceCollection} on success or an exception if processing fails
 */
public CompletableFuture<InvoiceCollection> getInvoices(int limit, int offset, String query) {
    CompletableFuture<InvoiceCollection> future = new FolioVertxCompletableFuture<>(ctx);
    RequestContext requestContext = new RequestContext(ctx, okapiHeaders);
    try {
        buildGetInvoicesQuery(query).thenCompose(getInvoicesQuery -> invoiceService.getInvoices(getInvoicesQuery, offset, limit, requestContext)).thenCompose(invoiceCollection -> invoiceService.updateInvoicesTotals(invoiceCollection, requestContext).thenAccept(v -> {
            logger.info("Successfully retrieved invoices: {}", invoiceCollection);
            future.complete(invoiceCollection);
        })).exceptionally(t -> {
            logger.error("Error getting invoices", t);
            future.completeExceptionally(t);
            return null;
        });
    } catch (Exception e) {
        future.completeExceptionally(e);
    }
    return future;
}
Also used : INVOICES(org.folio.invoices.utils.ResourcePathResolver.INVOICES) FolioVertxCompletableFuture.completedFuture(org.folio.completablefuture.FolioVertxCompletableFuture.completedFuture) ORG_IS_NOT_VENDOR(org.folio.invoices.utils.ErrorCodes.ORG_IS_NOT_VENDOR) Date(java.util.Date) Autowired(org.springframework.beans.factory.annotation.Autowired) InvoiceWorkflowDataHolder(org.folio.models.InvoiceWorkflowDataHolder) StringUtils(org.apache.commons.lang3.StringUtils) Context(io.vertx.core.Context) ExchangeRateProviderResolver(org.folio.services.exchange.ExchangeRateProviderResolver) HttpException(org.folio.invoices.rest.exceptions.HttpException) InvoiceService(org.folio.services.invoice.InvoiceService) ExpenseClass(org.folio.rest.acq.model.finance.ExpenseClass) Voucher(org.folio.rest.jaxrs.model.Voucher) AdjustmentsService(org.folio.services.adjusment.AdjustmentsService) VoucherCommandService(org.folio.services.voucher.VoucherCommandService) Collectors.toMap(java.util.stream.Collectors.toMap) Pair(org.apache.commons.lang3.tuple.Pair) InvoicePaymentService(org.folio.services.invoice.InvoicePaymentService) HelperUtils.isPostApproval(org.folio.invoices.utils.HelperUtils.isPostApproval) Map(java.util.Map) ListUtils(org.apache.commons.collections4.ListUtils) InvoiceWorkflowDataHolderBuilder(org.folio.InvoiceWorkflowDataHolderBuilder) CurrentFiscalYearService(org.folio.services.finance.fiscalyear.CurrentFiscalYearService) JsonObject(io.vertx.core.json.JsonObject) StringUtils.isEmpty(org.apache.commons.lang3.StringUtils.isEmpty) UserPermissionsUtil.verifyUserHasManagePermission(org.folio.utils.UserPermissionsUtil.verifyUserHasManagePermission) InvoiceCollection(org.folio.rest.jaxrs.model.InvoiceCollection) InvoiceLine(org.folio.rest.jaxrs.model.InvoiceLine) ExpenseClassRetrieveService(org.folio.services.finance.expence.ExpenseClassRetrieveService) BudgetExpenseClassService(org.folio.services.finance.budget.BudgetExpenseClassService) CompositePoLine(org.folio.rest.acq.model.orders.CompositePoLine) VendorRetrieveService(org.folio.services.VendorRetrieveService) Collection(java.util.Collection) InvoiceValidator(org.folio.services.validator.InvoiceValidator) Money(org.javamoney.moneta.Money) VOUCHER_NUMBER_PREFIX_CONFIG_QUERY(org.folio.services.voucher.VoucherCommandService.VOUCHER_NUMBER_PREFIX_CONFIG_QUERY) ConversionQuery(javax.money.convert.ConversionQuery) FOLIO_INVOICE_NUMBER(org.folio.invoices.utils.ResourcePathResolver.FOLIO_INVOICE_NUMBER) InvoiceRestrictionsUtil(org.folio.invoices.utils.InvoiceRestrictionsUtil) HelperUtils.getHttpClient(org.folio.invoices.utils.HelperUtils.getHttpClient) Fund(org.folio.rest.acq.model.finance.Fund) FundDistribution(org.folio.rest.jaxrs.model.FundDistribution) SequenceNumber(org.folio.rest.jaxrs.model.SequenceNumber) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) UPDATE(org.folio.invoices.utils.ProtectedOperationType.UPDATE) UserPermissionsUtil.verifyUserHasAssignPermission(org.folio.utils.UserPermissionsUtil.verifyUserHasAssignPermission) HelperUtils.getFundDistributionAmount(org.folio.invoices.utils.HelperUtils.getFundDistributionAmount) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) ExchangeRateProvider(javax.money.convert.ExchangeRateProvider) PendingPaymentWorkflowService(org.folio.services.finance.transaction.PendingPaymentWorkflowService) InvoiceCancelService(org.folio.services.invoice.InvoiceCancelService) Organization(org.folio.rest.acq.model.Organization) Adjustment(org.folio.rest.jaxrs.model.Adjustment) Monetary.getDefaultRounding(javax.money.Monetary.getDefaultRounding) Optional(java.util.Optional) FundExtNoExpenseClassExtNoPair(org.folio.models.FundExtNoExpenseClassExtNoPair) Parameter(org.folio.rest.jaxrs.model.Parameter) Objects.nonNull(java.util.Objects.nonNull) MonetaryAmount(javax.money.MonetaryAmount) Invoice(org.folio.rest.jaxrs.model.Invoice) HelperUtils(org.folio.invoices.utils.HelperUtils) EncumbranceService(org.folio.services.finance.transaction.EncumbranceService) CurrencyConversion(javax.money.convert.CurrencyConversion) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) HelperUtils.combineCqlExpressions(org.folio.invoices.utils.HelperUtils.combineCqlExpressions) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) FolioVertxCompletableFuture(org.folio.completablefuture.FolioVertxCompletableFuture) Transaction(org.folio.rest.acq.model.finance.Transaction) Function(java.util.function.Function) CollectionUtils(org.apache.commons.collections4.CollectionUtils) FundService(org.folio.services.finance.FundService) SpringContextUtil(org.folio.spring.SpringContextUtil) HelperUtils.getAdjustmentFundDistributionAmount(org.folio.invoices.utils.HelperUtils.getAdjustmentFundDistributionAmount) CompletableFuture.allOf(java.util.concurrent.CompletableFuture.allOf) RequestContext(org.folio.rest.core.models.RequestContext) EMPTY(org.apache.commons.lang3.StringUtils.EMPTY) ORG_NOT_FOUND(org.folio.invoices.utils.ErrorCodes.ORG_NOT_FOUND) InvoiceLineService(org.folio.services.invoice.InvoiceLineService) ResourcePathResolver.resourcesPath(org.folio.invoices.utils.ResourcePathResolver.resourcesPath) VoucherRetrieveService(org.folio.services.voucher.VoucherRetrieveService) Vertx(io.vertx.core.Vertx) VoucherLine(org.folio.rest.jaxrs.model.VoucherLine) Error(org.folio.rest.jaxrs.model.Error) UUID.randomUUID(java.util.UUID.randomUUID) Collectors.toList(java.util.stream.Collectors.toList) INVALID_INVOICE_TRANSITION_ON_PAID_STATUS(org.folio.invoices.utils.ErrorCodes.INVALID_INVOICE_TRANSITION_ON_PAID_STATUS) HelperUtils.calculateVoucherLineAmount(org.folio.invoices.utils.HelperUtils.calculateVoucherLineAmount) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) ConfigurationService(org.folio.services.configuration.ConfigurationService) ProtectedOperationType(org.folio.invoices.utils.ProtectedOperationType) InvoiceCollection(org.folio.rest.jaxrs.model.InvoiceCollection) RequestContext(org.folio.rest.core.models.RequestContext) HttpException(org.folio.invoices.rest.exceptions.HttpException) FolioVertxCompletableFuture(org.folio.completablefuture.FolioVertxCompletableFuture)

Example 2 with InvoiceCollection

use of org.folio.rest.jaxrs.model.InvoiceCollection in project mod-invoice by folio-org.

the class InvoicesApiTest method testGetInvoicingInvoices.

@Test
void testGetInvoicingInvoices() {
    logger.info("=== Test Get Invoices by without query - get 200 by successful retrieval of invoices ===");
    final InvoiceCollection resp = verifySuccessGet(INVOICE_PATH, InvoiceCollection.class, X_OKAPI_PROTECTED_READ_TENANT);
    assertThat(resp.getTotalRecords(), is(3));
    assertThat(getInvoiceSearches(), hasSize(1));
    assertThat(getInvoiceLineSearches(), empty());
    assertThat(getAcqUnitsSearches(), hasSize(1));
    assertThat(getAcqMembershipsSearches(), hasSize(1));
    verifyInvoiceUpdateCalls(0);
    List<String> queryParams = getQueryParams(INVOICES);
    assertThat(queryParams, hasSize(1));
    assertThat(queryParams.get(0), Matchers.equalTo(getNoAcqUnitCQL(INVOICES)));
}
Also used : InvoiceCollection(org.folio.rest.jaxrs.model.InvoiceCollection) Matchers.containsString(org.hamcrest.Matchers.containsString) Test(org.junit.jupiter.api.Test)

Example 3 with InvoiceCollection

use of org.folio.rest.jaxrs.model.InvoiceCollection in project mod-invoice by folio-org.

the class InvoicesApiTest method testGetInvoicingInvoicesWithQueryParam.

@Test
void testGetInvoicingInvoicesWithQueryParam() {
    logger.info("=== Test Get Invoices with query - get 200 by successful retrieval of invoices by query ===");
    String sortBy = " sortBy folioInvoiceNo";
    String queryValue = VENDOR_INVOICE_NUMBER_FIELD + "==" + EXISTING_VENDOR_INV_NO;
    String endpointQuery = String.format("%s?query=%s%s", INVOICE_PATH, queryValue, sortBy);
    final InvoiceCollection resp = verifySuccessGet(endpointQuery, InvoiceCollection.class, X_OKAPI_PROTECTED_READ_TENANT);
    assertThat(resp.getTotalRecords(), is(1));
    assertThat(getInvoiceSearches(), hasSize(1));
    assertThat(getAcqUnitsSearches(), hasSize(1));
    assertThat(getAcqMembershipsSearches(), hasSize(1));
    assertThat(getInvoiceLineSearches(), empty());
    verifyInvoiceUpdateCalls(0);
    List<String> queryParams = getQueryParams(INVOICES);
    assertThat(queryParams, hasSize(1));
    String queryToStorage = queryParams.get(0);
    assertThat(queryToStorage, containsString("(" + queryValue + ")"));
    assertThat(queryToStorage, Matchers.not(containsString(ACQUISITIONS_UNIT_IDS + "=")));
    assertThat(queryToStorage, containsString(getNoAcqUnitCQL(INVOICE)));
    assertThat(queryToStorage, endsWith(sortBy));
}
Also used : InvoiceCollection(org.folio.rest.jaxrs.model.InvoiceCollection) Matchers.containsString(org.hamcrest.Matchers.containsString) Test(org.junit.jupiter.api.Test)

Example 4 with InvoiceCollection

use of org.folio.rest.jaxrs.model.InvoiceCollection in project mod-invoice by folio-org.

the class MockServer method handleGetInvoices.

private void handleGetInvoices(RoutingContext ctx) {
    String queryParam = StringUtils.trimToEmpty(ctx.request().getParam(QUERY));
    addServerRqQuery(INVOICES, queryParam);
    if (queryParam.contains(BAD_QUERY)) {
        serverResponse(ctx, 400, APPLICATION_JSON, Response.Status.BAD_REQUEST.getReasonPhrase());
    } else if (queryParam.contains(ID_DOES_NOT_EXIST)) {
        serverResponse(ctx, 404, APPLICATION_JSON, Response.Status.NOT_FOUND.getReasonPhrase());
    } else if (queryParam.contains(ID_FOR_INTERNAL_SERVER_ERROR)) {
        serverResponse(ctx, 500, APPLICATION_JSON, Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase());
    } else if (queryParam.startsWith(QUERY_PARAM_START_WITH)) {
        Matcher lineIdMatcher = Pattern.compile(".*invoiceLines.id==(\\S+).*").matcher(queryParam);
        final String lineId = lineIdMatcher.find() ? lineIdMatcher.group(1) : EMPTY;
        List<Invoice> invoices;
        InvoiceCollection invoiceCollection = new InvoiceCollection();
        if (lineId.equals(SEARCH_INVOICE_BY_LINE_ID_NOT_FOUND)) {
            invoiceCollection.setInvoices(new ArrayList<>());
            invoiceCollection.setTotalRecords(invoiceCollection.getInvoices().size());
            JsonObject invoicesJson = JsonObject.mapFrom(invoiceCollection);
            addServerRqRsData(HttpMethod.GET, INVOICES, JsonObject.mapFrom(invoiceCollection));
            serverResponse(ctx, 200, APPLICATION_JSON, invoicesJson.encode());
        } else {
            try {
                invoices = new JsonObject(ApiTestBase.getMockData(MOCK_DATA_INVOICES)).mapTo(InvoiceCollection.class).getInvoices();
            } catch (IOException e) {
                invoices = new ArrayList<>();
            }
            Optional<List<Invoice>> invoiceOptional = getMockEntries(INVOICES, Invoice.class);
            Invoice invoice0 = invoiceOptional.get().get(0);
            invoices.set(0, invoice0);
            invoiceCollection.setInvoices(invoices);
            invoiceCollection.setTotalRecords(invoiceCollection.getInvoices().size());
            JsonObject invoicesJson = JsonObject.mapFrom(invoiceCollection);
            addServerRqRsData(HttpMethod.GET, INVOICES, JsonObject.mapFrom(invoiceCollection));
            serverResponse(ctx, 200, APPLICATION_JSON, invoicesJson.encode());
        }
    } else if (queryParam.contains("id==")) {
        List<Invoice> invoices;
        InvoiceCollection invoiceCollection = new InvoiceCollection();
        try {
            invoices = new JsonObject(ApiTestBase.getMockData(MOCK_DATA_INVOICES)).mapTo(InvoiceCollection.class).getInvoices();
        } catch (IOException e) {
            invoices = new ArrayList<>();
        }
        invoiceCollection.setInvoices(invoices);
        invoiceCollection.setTotalRecords(invoiceCollection.getInvoices().size());
        JsonObject invoicesJson = JsonObject.mapFrom(invoiceCollection);
        addServerRqRsData(HttpMethod.GET, INVOICES, JsonObject.mapFrom(invoiceCollection));
        serverResponse(ctx, 200, APPLICATION_JSON, invoicesJson.encode());
    } else {
        JsonObject invoice = new JsonObject();
        Matcher matcher = Pattern.compile(".*vendorInvoiceNo==(\\S[^)]+).*").matcher(queryParam);
        final String vendorNumber = matcher.find() ? matcher.group(1) : EMPTY;
        switch(vendorNumber) {
            case EXISTING_VENDOR_INV_NO:
                invoice.put(TOTAL_RECORDS, 1);
                break;
            case EMPTY:
                invoice.put(TOTAL_RECORDS, 3);
                break;
            default:
                invoice.put(TOTAL_RECORDS, 0);
        }
        addServerRqRsData(HttpMethod.GET, INVOICES, invoice);
        serverResponse(ctx, 200, APPLICATION_JSON, invoice.encodePrettily());
    }
}
Also used : Invoice(org.folio.rest.jaxrs.model.Invoice) Optional(java.util.Optional) Matcher(java.util.regex.Matcher) InvoiceCollection(org.folio.rest.jaxrs.model.InvoiceCollection) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) ArrayList(java.util.ArrayList) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) IOException(java.io.IOException)

Example 5 with InvoiceCollection

use of org.folio.rest.jaxrs.model.InvoiceCollection in project mod-invoice by folio-org.

the class InvoiceRetrieveServiceTest method positiveGetInvoicesByChunksTest.

@Test
public void positiveGetInvoicesByChunksTest() throws IOException, ExecutionException, InterruptedException {
    InvoiceService invoiceService = new BaseInvoiceService(new RestClient(), invoiceLineService, orderService);
    InvoiceRetrieveService service = new InvoiceRetrieveService(invoiceService);
    JsonObject vouchersList = new JsonObject(getMockData(VOUCHERS_LIST_PATH));
    List<Voucher> vouchers = vouchersList.getJsonArray("vouchers").stream().map(obj -> ((JsonObject) obj).mapTo(Voucher.class)).collect(toList());
    vouchers.remove(1);
    CompletableFuture<List<InvoiceCollection>> future = service.getInvoicesByChunks(vouchers, new RequestContext(context, okapiHeaders));
    List<InvoiceCollection> lineCollections = future.get();
    Assertions.assertEquals(3, lineCollections.get(0).getInvoices().size());
}
Also used : RestClient(org.folio.rest.core.RestClient) BeforeEach(org.junit.jupiter.api.BeforeEach) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) VoucherCollection(org.folio.rest.jaxrs.model.VoucherCollection) Context(io.vertx.core.Context) InvoiceService(org.folio.services.invoice.InvoiceService) Voucher(org.folio.rest.jaxrs.model.Voucher) Map(java.util.Map) RequestContext(org.folio.rest.core.models.RequestContext) InvoiceLineService(org.folio.services.invoice.InvoiceLineService) JsonObject(io.vertx.core.json.JsonObject) OKAPI_URL(org.folio.rest.RestConstants.OKAPI_URL) OrderService(org.folio.services.order.OrderService) InvoiceCollection(org.folio.rest.jaxrs.model.InvoiceCollection) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) ApiTestSuite.mockPort(org.folio.ApiTestSuite.mockPort) ApiTestBase(org.folio.rest.impl.ApiTestBase) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.jupiter.api.Test) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) BaseInvoiceService(org.folio.services.invoice.BaseInvoiceService) Assertions(org.junit.jupiter.api.Assertions) Invoice(org.folio.rest.jaxrs.model.Invoice) InvoiceService(org.folio.services.invoice.InvoiceService) BaseInvoiceService(org.folio.services.invoice.BaseInvoiceService) BaseInvoiceService(org.folio.services.invoice.BaseInvoiceService) RestClient(org.folio.rest.core.RestClient) JsonObject(io.vertx.core.json.JsonObject) Voucher(org.folio.rest.jaxrs.model.Voucher) InvoiceCollection(org.folio.rest.jaxrs.model.InvoiceCollection) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) RequestContext(org.folio.rest.core.models.RequestContext) Test(org.junit.jupiter.api.Test)

Aggregations

InvoiceCollection (org.folio.rest.jaxrs.model.InvoiceCollection)6 Test (org.junit.jupiter.api.Test)4 JsonObject (io.vertx.core.json.JsonObject)3 List (java.util.List)3 Collectors.toList (java.util.stream.Collectors.toList)3 Invoice (org.folio.rest.jaxrs.model.Invoice)3 Context (io.vertx.core.Context)2 Vertx (io.vertx.core.Vertx)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Optional (java.util.Optional)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 RequestContext (org.folio.rest.core.models.RequestContext)2 Voucher (org.folio.rest.jaxrs.model.Voucher)2 InvoiceLineService (org.folio.services.invoice.InvoiceLineService)2 InvoiceService (org.folio.services.invoice.InvoiceService)2 Matchers.containsString (org.hamcrest.Matchers.containsString)2 Autowired (org.springframework.beans.factory.annotation.Autowired)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1