Search in sources :

Example 1 with RequestContext

use of org.folio.rest.core.models.RequestContext in project mod-invoice by folio-org.

the class InvoiceHelper method handleInvoiceStatusTransition.

private CompletionStage<Void> handleInvoiceStatusTransition(Invoice invoice, Invoice invoiceFromStorage, List<InvoiceLine> invoiceLines) {
    if (isTransitionToApproved(invoiceFromStorage, invoice)) {
        return approveInvoice(invoice, invoiceLines);
    } else if (isAfterApprove(invoice, invoiceFromStorage) && isExchangeRateChanged(invoice, invoiceFromStorage)) {
        return handleExchangeRateChange(invoice, invoiceLines);
    } else if (isTransitionToPaid(invoiceFromStorage, invoice)) {
        RequestContext requestContext = new RequestContext(ctx, okapiHeaders);
        if (isExchangeRateChanged(invoice, invoiceFromStorage)) {
            return handleExchangeRateChange(invoice, invoiceLines).thenCompose(aVoid1 -> invoicePaymentService.payInvoice(invoice, invoiceLines, requestContext));
        }
        invoice.setExchangeRate(invoiceFromStorage.getExchangeRate());
        return invoicePaymentService.payInvoice(invoice, invoiceLines, requestContext);
    } else if (isTransitionToCancelled(invoiceFromStorage, invoice)) {
        RequestContext requestContext = new RequestContext(ctx, okapiHeaders);
        return invoiceCancelService.cancelInvoice(invoiceFromStorage, invoiceLines, requestContext);
    }
    return CompletableFuture.completedFuture(null);
}
Also used : RequestContext(org.folio.rest.core.models.RequestContext)

Example 2 with RequestContext

use of org.folio.rest.core.models.RequestContext 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 3 with RequestContext

use of org.folio.rest.core.models.RequestContext in project mod-invoice by folio-org.

the class VouchersImpl method postVoucherVoucherNumberStartByValue.

@Validate
@Override
public void postVoucherVoucherNumberStartByValue(String value, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
    logger.info("== Re(set) the current start value of the voucher number sequence ==");
    voucherNumberService.setStartValue(value, new RequestContext(vertxContext, okapiHeaders)).thenAccept(ok -> asyncResultHandler.handle(succeededFuture(buildNoContentResponse()))).exceptionally(fail -> handleErrorResponse(asyncResultHandler, fail));
}
Also used : Future.succeededFuture(io.vertx.core.Future.succeededFuture) Vertx(io.vertx.core.Vertx) Autowired(org.springframework.beans.factory.annotation.Autowired) StringUtils(org.apache.commons.lang3.StringUtils) Validate(org.folio.rest.annotations.Validate) Context(io.vertx.core.Context) SpringContextUtil(org.folio.spring.SpringContextUtil) VoucherLine(org.folio.rest.jaxrs.model.VoucherLine) Voucher(org.folio.rest.jaxrs.model.Voucher) Logger(org.apache.logging.log4j.Logger) Response(javax.ws.rs.core.Response) Map(java.util.Map) RequestContext(org.folio.rest.core.models.RequestContext) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) LogManager(org.apache.logging.log4j.LogManager) VoucherNumberService(org.folio.services.voucher.VoucherNumberService) RequestContext(org.folio.rest.core.models.RequestContext) Validate(org.folio.rest.annotations.Validate)

Example 4 with RequestContext

use of org.folio.rest.core.models.RequestContext in project mod-invoice by folio-org.

the class RestClient method post.

public <T> CompletableFuture<T> post(RequestEntry requestEntry, T entity, RequestContext requestContext, Class<T> responseType) {
    CompletableFuture<T> future = new CompletableFuture<>();
    String endpoint = requestEntry.buildEndpoint();
    JsonObject recordData = JsonObject.mapFrom(entity);
    if (logger.isDebugEnabled()) {
        logger.debug("Sending 'POST {}' with body: {}", endpoint, Optional.ofNullable(recordData).map(JsonObject::encodePrettily).orElse(null));
    }
    HttpClientInterface client = getHttpClient(requestContext.getHeaders());
    try {
        client.request(HttpMethod.POST, Optional.ofNullable(recordData).map(JsonObject::toBuffer).orElse(null), endpoint, requestContext.getHeaders()).thenApply(HelperUtils::verifyAndExtractBody).thenAccept(body -> {
            client.closeClient();
            T responseEntity = Optional.ofNullable(body).map(json -> json.mapTo(responseType)).orElse(null);
            if (logger.isDebugEnabled()) {
                logger.debug("'POST {}' request successfully processed. Record with '{}' id has been created", endpoint, body);
            }
            future.complete(responseEntity);
        }).exceptionally(t -> {
            client.closeClient();
            logger.error("'POST {}' request failed. Request body: {}", endpoint, Optional.ofNullable(recordData).map(JsonObject::encodePrettily).orElse(null), t.getCause());
            future.completeExceptionally(t.getCause());
            return null;
        });
    } catch (Exception e) {
        logger.error("'POST {}' request failed. Request body: {}", endpoint, Optional.ofNullable(recordData).map(JsonObject::encodePrettily).orElse(null), e);
        client.closeClient();
        future.completeExceptionally(e);
    }
    return future;
}
Also used : HelperUtils(org.folio.invoices.utils.HelperUtils) RequestEntry(org.folio.rest.core.models.RequestEntry) OKAPI_HEADER_TENANT(org.folio.rest.RestVerticle.OKAPI_HEADER_TENANT) CompletableFuture(java.util.concurrent.CompletableFuture) TenantTool(org.folio.rest.tools.utils.TenantTool) HttpClientFactory(org.folio.rest.tools.client.HttpClientFactory) Logger(org.apache.logging.log4j.Logger) HttpClientInterface(org.folio.rest.tools.client.interfaces.HttpClientInterface) HttpMethod(io.vertx.core.http.HttpMethod) Map(java.util.Map) RequestContext(org.folio.rest.core.models.RequestContext) Optional(java.util.Optional) HelperUtils.verifyAndExtractBody(org.folio.invoices.utils.HelperUtils.verifyAndExtractBody) JsonObject(io.vertx.core.json.JsonObject) Objects.nonNull(java.util.Objects.nonNull) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) RestConstants(org.folio.rest.RestConstants) TEXT_PLAIN(javax.ws.rs.core.MediaType.TEXT_PLAIN) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) CompletableFuture(java.util.concurrent.CompletableFuture) HttpClientInterface(org.folio.rest.tools.client.interfaces.HttpClientInterface) HelperUtils(org.folio.invoices.utils.HelperUtils) OKAPI_HEADER_TENANT(org.folio.rest.RestVerticle.OKAPI_HEADER_TENANT) JsonObject(io.vertx.core.json.JsonObject)

Example 5 with RequestContext

use of org.folio.rest.core.models.RequestContext in project mod-invoice by folio-org.

the class RestClient method delete.

public CompletableFuture<Void> delete(RequestEntry requestEntry, RequestContext requestContext) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    String endpoint = requestEntry.buildEndpoint();
    if (logger.isDebugEnabled()) {
        logger.debug(CALLING_ENDPOINT_MSG, HttpMethod.DELETE, endpoint);
    }
    HttpClientInterface client = getHttpClient(requestContext.getHeaders());
    setDefaultHeaders(client);
    try {
        client.request(HttpMethod.DELETE, endpoint, requestContext.getHeaders()).thenAccept(HelperUtils::verifyResponse).thenAccept(aVoid -> {
            client.closeClient();
            future.complete(null);
        }).exceptionally(t -> {
            client.closeClient();
            logger.error(String.format(EXCEPTION_CALLING_ENDPOINT_MSG, HttpMethod.DELETE, endpoint, requestContext), t);
            future.completeExceptionally(t.getCause());
            return null;
        });
    } catch (Exception e) {
        client.closeClient();
        logger.error(String.format(EXCEPTION_CALLING_ENDPOINT_MSG, HttpMethod.DELETE, endpoint, requestContext), e);
        future.completeExceptionally(e);
    }
    return future;
}
Also used : HelperUtils(org.folio.invoices.utils.HelperUtils) RequestEntry(org.folio.rest.core.models.RequestEntry) OKAPI_HEADER_TENANT(org.folio.rest.RestVerticle.OKAPI_HEADER_TENANT) CompletableFuture(java.util.concurrent.CompletableFuture) TenantTool(org.folio.rest.tools.utils.TenantTool) HttpClientFactory(org.folio.rest.tools.client.HttpClientFactory) Logger(org.apache.logging.log4j.Logger) HttpClientInterface(org.folio.rest.tools.client.interfaces.HttpClientInterface) HttpMethod(io.vertx.core.http.HttpMethod) Map(java.util.Map) RequestContext(org.folio.rest.core.models.RequestContext) Optional(java.util.Optional) HelperUtils.verifyAndExtractBody(org.folio.invoices.utils.HelperUtils.verifyAndExtractBody) JsonObject(io.vertx.core.json.JsonObject) Objects.nonNull(java.util.Objects.nonNull) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) RestConstants(org.folio.rest.RestConstants) TEXT_PLAIN(javax.ws.rs.core.MediaType.TEXT_PLAIN) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) CompletableFuture(java.util.concurrent.CompletableFuture) HttpClientInterface(org.folio.rest.tools.client.interfaces.HttpClientInterface) HelperUtils(org.folio.invoices.utils.HelperUtils)

Aggregations

RequestContext (org.folio.rest.core.models.RequestContext)165 JsonObject (io.vertx.core.json.JsonObject)109 CompletableFuture (java.util.concurrent.CompletableFuture)105 Map (java.util.Map)100 List (java.util.List)92 Logger (org.apache.logging.log4j.Logger)85 LogManager (org.apache.logging.log4j.LogManager)83 Collections (java.util.Collections)73 ArrayList (java.util.ArrayList)72 Context (io.vertx.core.Context)71 CompletableFuture.completedFuture (java.util.concurrent.CompletableFuture.completedFuture)69 Collectors.toList (java.util.stream.Collectors.toList)68 BeforeEach (org.junit.jupiter.api.BeforeEach)63 CompositePoLine (org.folio.rest.jaxrs.model.CompositePoLine)56 Optional (java.util.Optional)53 StringUtils (org.apache.commons.lang3.StringUtils)53 Autowired (org.springframework.beans.factory.annotation.Autowired)51 Piece (org.folio.rest.jaxrs.model.Piece)49 Error (org.folio.rest.jaxrs.model.Error)46 RequestEntry (org.folio.rest.core.models.RequestEntry)45