Search in sources :

Example 16 with InvoiceApiException

use of org.killbill.billing.invoice.api.InvoiceApiException in project killbill by killbill.

the class InvoiceResource method createFutureInvoice.

@TimedResource
@POST
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Trigger an invoice generation", response = InvoiceJson.class)
@ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid account id or target datetime supplied") })
public Response createFutureInvoice(@QueryParam(QUERY_ACCOUNT_ID) final String accountId, @QueryParam(QUERY_TARGET_DATE) final String targetDate, @HeaderParam(HDR_CREATED_BY) final String createdBy, @HeaderParam(HDR_REASON) final String reason, @HeaderParam(HDR_COMMENT) final String comment, @javax.ws.rs.core.Context final HttpServletRequest request, @javax.ws.rs.core.Context final UriInfo uriInfo) throws AccountApiException, InvoiceApiException {
    final CallContext callContext = context.createContext(createdBy, reason, comment, request);
    final LocalDate inputDate = toLocalDate(targetDate);
    try {
        final Invoice generatedInvoice = invoiceApi.triggerInvoiceGeneration(UUID.fromString(accountId), inputDate, null, callContext);
        return uriBuilder.buildResponse(uriInfo, InvoiceResource.class, "getInvoice", generatedInvoice.getId(), request);
    } catch (InvoiceApiException e) {
        if (e.getCode() == ErrorCode.INVOICE_NOTHING_TO_DO.getCode()) {
            return Response.status(Status.NOT_FOUND).build();
        }
        throw e;
    }
}
Also used : InvoiceApiException(org.killbill.billing.invoice.api.InvoiceApiException) Invoice(org.killbill.billing.invoice.api.Invoice) CallContext(org.killbill.billing.util.callcontext.CallContext) LocalDate(org.joda.time.LocalDate) TimedResource(org.killbill.commons.metrics.TimedResource) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 17 with InvoiceApiException

use of org.killbill.billing.invoice.api.InvoiceApiException in project killbill by killbill.

the class InvoiceDispatcher method processSubscriptionInternal.

private Invoice processSubscriptionInternal(final UUID subscriptionId, final LocalDate targetDate, final boolean dryRunForNotification, final InternalCallContext context) throws InvoiceApiException {
    try {
        if (subscriptionId == null) {
            log.warn("Failed handling SubscriptionBase change.", new InvoiceApiException(ErrorCode.INVOICE_INVALID_TRANSITION));
            return null;
        }
        final UUID accountId = subscriptionApi.getAccountIdFromSubscriptionId(subscriptionId, context);
        final DryRunArguments dryRunArguments = dryRunForNotification ? TARGET_DATE_DRY_RUN_ARGUMENTS : null;
        return processAccountFromNotificationOrBusEvent(accountId, targetDate, dryRunArguments, context);
    } catch (final SubscriptionBaseApiException e) {
        log.warn("Failed handling SubscriptionBase change.", new InvoiceApiException(ErrorCode.INVOICE_NO_ACCOUNT_ID_FOR_SUBSCRIPTION_ID, subscriptionId.toString()));
        return null;
    }
}
Also used : InvoiceApiException(org.killbill.billing.invoice.api.InvoiceApiException) DryRunArguments(org.killbill.billing.invoice.api.DryRunArguments) UUID(java.util.UUID) SubscriptionBaseApiException(org.killbill.billing.subscription.api.user.SubscriptionBaseApiException)

Example 18 with InvoiceApiException

use of org.killbill.billing.invoice.api.InvoiceApiException in project killbill by killbill.

the class InvoiceDispatcher method processAccountWithLock.

private Invoice processAccountWithLock(final boolean parkedAccount, final UUID accountId, @Nullable final LocalDate inputTargetDateMaybeNull, @Nullable final DryRunArguments dryRunArguments, final InternalCallContext context) throws InvoiceApiException {
    final boolean isDryRun = dryRunArguments != null;
    final boolean upcomingInvoiceDryRun = isDryRun && DryRunType.UPCOMING_INVOICE.equals(dryRunArguments.getDryRunType());
    LocalDate inputTargetDate = inputTargetDateMaybeNull;
    // A null inputTargetDate is only allowed in dryRun mode to have the system compute it
    if (inputTargetDate == null && !upcomingInvoiceDryRun) {
        inputTargetDate = clock.getUTCToday();
    }
    Preconditions.checkArgument(inputTargetDate != null || upcomingInvoiceDryRun, "inputTargetDate is required in non dryRun mode");
    try {
        // Make sure to first set the BCD if needed then get the account object (to have the BCD set)
        final BillingEventSet billingEvents = billingApi.getBillingEventsForAccountAndUpdateAccountBCD(accountId, dryRunArguments, context);
        if (billingEvents.isEmpty()) {
            return null;
        }
        final Iterable<UUID> filteredSubscriptionIdsForDryRun = getFilteredSubscriptionIdsForDryRun(dryRunArguments, billingEvents);
        final List<LocalDate> candidateTargetDates = (inputTargetDate != null) ? ImmutableList.<LocalDate>of(inputTargetDate) : getUpcomingInvoiceCandidateDates(filteredSubscriptionIdsForDryRun, context);
        for (final LocalDate curTargetDate : candidateTargetDates) {
            final Invoice invoice = processAccountWithLockAndInputTargetDate(accountId, curTargetDate, billingEvents, isDryRun, context);
            if (invoice != null) {
                filterInvoiceItemsForDryRun(filteredSubscriptionIdsForDryRun, invoice);
                if (!isDryRun && parkedAccount) {
                    try {
                        log.info("Illegal invoicing state fixed for accountId='{}', unparking account", accountId);
                        parkedAccountsManager.unparkAccount(accountId, context);
                    } catch (final TagApiException ignored) {
                        log.warn("Unable to unpark account", ignored);
                    }
                }
                return invoice;
            }
        }
        return null;
    } catch (final CatalogApiException e) {
        log.warn("Failed to retrieve BillingEvents for accountId='{}', dryRunArguments='{}'", accountId, dryRunArguments, e);
        return null;
    } catch (final AccountApiException e) {
        log.warn("Failed to retrieve BillingEvents for accountId='{}', dryRunArguments='{}'", accountId, dryRunArguments, e);
        return null;
    } catch (final SubscriptionBaseApiException e) {
        log.warn("Failed to retrieve BillingEvents for accountId='{}', dryRunArguments='{}'", accountId, dryRunArguments, e);
        return null;
    } catch (final InvoiceApiException e) {
        if (e.getCode() == ErrorCode.UNEXPECTED_ERROR.getCode() && !isDryRun) {
            log.warn("Illegal invoicing state detected for accountId='{}', dryRunArguments='{}', parking account", accountId, dryRunArguments, e);
            parkAccount(accountId, context);
        }
        throw e;
    }
}
Also used : InvoiceApiException(org.killbill.billing.invoice.api.InvoiceApiException) DefaultInvoice(org.killbill.billing.invoice.model.DefaultInvoice) Invoice(org.killbill.billing.invoice.api.Invoice) TagApiException(org.killbill.billing.util.api.TagApiException) BillingEventSet(org.killbill.billing.junction.BillingEventSet) CatalogApiException(org.killbill.billing.catalog.api.CatalogApiException) AccountApiException(org.killbill.billing.account.api.AccountApiException) UUID(java.util.UUID) LocalDate(org.joda.time.LocalDate) SubscriptionBaseApiException(org.killbill.billing.subscription.api.user.SubscriptionBaseApiException)

Example 19 with InvoiceApiException

use of org.killbill.billing.invoice.api.InvoiceApiException in project killbill by killbill.

the class InvoiceDispatcher method processParentInvoiceForAdjustmentsWithLock.

public void processParentInvoiceForAdjustmentsWithLock(final Account account, final UUID childInvoiceId, final InternalCallContext context) throws InvoiceApiException {
    final InvoiceModelDao childInvoiceModelDao = invoiceDao.getById(childInvoiceId, context);
    final InvoiceModelDao parentInvoiceModelDao = childInvoiceModelDao.getParentInvoice();
    if (parentInvoiceModelDao == null) {
        throw new InvoiceApiException(ErrorCode.INVOICE_MISSING_PARENT_INVOICE, childInvoiceModelDao.getId());
    } else if (InvoiceModelDaoHelper.getBalance(parentInvoiceModelDao).compareTo(BigDecimal.ZERO) == 0) {
        // ignore item adjustments for paid invoices.
        return;
    }
    final Long parentAccountRecordId = internalCallContextFactory.getRecordIdFromObject(account.getParentAccountId(), ObjectType.ACCOUNT, buildTenantContext(context));
    final InternalCallContext parentContext = internalCallContextFactory.createInternalCallContext(parentAccountRecordId, context);
    final String description = "Adjustment for account ".concat(account.getExternalKey());
    // find PARENT_SUMMARY invoice item for this child account
    final InvoiceItemModelDao parentSummaryInvoiceItem = Iterables.find(parentInvoiceModelDao.getInvoiceItems(), new Predicate<InvoiceItemModelDao>() {

        @Override
        public boolean apply(@Nullable final InvoiceItemModelDao input) {
            return input.getType().equals(InvoiceItemType.PARENT_SUMMARY) && input.getChildAccountId().equals(childInvoiceModelDao.getAccountId());
        }
    });
    final Iterable<InvoiceItemModelDao> childAdjustments = Iterables.filter(childInvoiceModelDao.getInvoiceItems(), new Predicate<InvoiceItemModelDao>() {

        @Override
        public boolean apply(@Nullable final InvoiceItemModelDao input) {
            return input.getType().equals(InvoiceItemType.ITEM_ADJ);
        }
    });
    // find last ITEM_ADJ invoice added in child invoice
    final InvoiceItemModelDao lastChildInvoiceItemAdjustment = Collections.max(Lists.newArrayList(childAdjustments), new Comparator<InvoiceItemModelDao>() {

        @Override
        public int compare(InvoiceItemModelDao o1, InvoiceItemModelDao o2) {
            return o1.getCreatedDate().compareTo(o2.getCreatedDate());
        }
    });
    final BigDecimal childInvoiceAdjustmentAmount = lastChildInvoiceItemAdjustment.getAmount();
    if (parentInvoiceModelDao.getStatus().equals(InvoiceStatus.COMMITTED)) {
        ItemAdjInvoiceItem adj = new ItemAdjInvoiceItem(UUIDs.randomUUID(), lastChildInvoiceItemAdjustment.getCreatedDate(), parentSummaryInvoiceItem.getInvoiceId(), parentSummaryInvoiceItem.getAccountId(), lastChildInvoiceItemAdjustment.getStartDate(), description, childInvoiceAdjustmentAmount, parentInvoiceModelDao.getCurrency(), parentSummaryInvoiceItem.getId());
        parentInvoiceModelDao.addInvoiceItem(new InvoiceItemModelDao(adj));
        invoiceDao.createInvoices(ImmutableList.<InvoiceModelDao>of(parentInvoiceModelDao), parentContext);
        return;
    }
    // update item amount
    final BigDecimal newParentInvoiceItemAmount = childInvoiceAdjustmentAmount.add(parentSummaryInvoiceItem.getAmount());
    invoiceDao.updateInvoiceItemAmount(parentSummaryInvoiceItem.getId(), newParentInvoiceItemAmount, parentContext);
}
Also used : InvoiceApiException(org.killbill.billing.invoice.api.InvoiceApiException) InvoiceItemModelDao(org.killbill.billing.invoice.dao.InvoiceItemModelDao) InvoiceModelDao(org.killbill.billing.invoice.dao.InvoiceModelDao) ItemAdjInvoiceItem(org.killbill.billing.invoice.model.ItemAdjInvoiceItem) InternalCallContext(org.killbill.billing.callcontext.InternalCallContext) PlanPhasePriceOverride(org.killbill.billing.catalog.api.PlanPhasePriceOverride) BigDecimal(java.math.BigDecimal)

Example 20 with InvoiceApiException

use of org.killbill.billing.invoice.api.InvoiceApiException in project killbill by killbill.

the class DefaultInvoiceUserApi method insertCreditForInvoice.

private InvoiceItem insertCreditForInvoice(final UUID accountId, final UUID invoiceId, final BigDecimal amount, final LocalDate effectiveDate, final Currency currency, final boolean autoCommit, final String description, final CallContext context) throws InvoiceApiException {
    if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
        throw new InvoiceApiException(ErrorCode.CREDIT_AMOUNT_INVALID, amount);
    }
    final WithAccountLock withAccountLock = new WithAccountLock() {

        private InvoiceItem creditItem;

        @Override
        public List<Invoice> prepareInvoices() throws InvoiceApiException {
            final InternalTenantContext internalTenantContext = internalCallContextFactory.createInternalTenantContext(accountId, context);
            final LocalDate invoiceDate = internalTenantContext.toLocalDate(context.getCreatedDate());
            // Create an invoice for that credit if it doesn't exist
            final Invoice invoiceForCredit;
            if (invoiceId == null) {
                final InvoiceStatus status = autoCommit ? InvoiceStatus.COMMITTED : InvoiceStatus.DRAFT;
                invoiceForCredit = new DefaultInvoice(accountId, invoiceDate, effectiveDate, currency, status);
            } else {
                invoiceForCredit = getInvoiceAndCheckCurrency(invoiceId, currency, context);
                if (InvoiceStatus.COMMITTED.equals(invoiceForCredit.getStatus())) {
                    throw new InvoiceApiException(ErrorCode.INVOICE_ALREADY_COMMITTED, invoiceId);
                }
            }
            // Create the new credit
            creditItem = new CreditAdjInvoiceItem(UUIDs.randomUUID(), context.getCreatedDate(), invoiceForCredit.getId(), accountId, effectiveDate, description, // Note! The amount is negated here!
            amount.negate(), currency);
            invoiceForCredit.addInvoiceItem(creditItem);
            return ImmutableList.<Invoice>of(invoiceForCredit);
        }
    };
    final Collection<InvoiceItem> creditInvoiceItems = Collections2.<InvoiceItem>filter(invoiceApiHelper.dispatchToInvoicePluginsAndInsertItems(accountId, false, withAccountLock, context), new Predicate<InvoiceItem>() {

        @Override
        public boolean apply(final InvoiceItem invoiceItem) {
            return InvoiceItemType.CREDIT_ADJ.equals(invoiceItem.getInvoiceItemType());
        }
    });
    Preconditions.checkState(creditInvoiceItems.size() == 1, "Should have created a single credit invoice item: " + creditInvoiceItems);
    return creditInvoiceItems.iterator().next();
}
Also used : InvoiceApiException(org.killbill.billing.invoice.api.InvoiceApiException) InvoiceItem(org.killbill.billing.invoice.api.InvoiceItem) ExternalChargeInvoiceItem(org.killbill.billing.invoice.model.ExternalChargeInvoiceItem) CreditAdjInvoiceItem(org.killbill.billing.invoice.model.CreditAdjInvoiceItem) Invoice(org.killbill.billing.invoice.api.Invoice) HtmlInvoice(org.killbill.billing.invoice.template.HtmlInvoice) DefaultInvoice(org.killbill.billing.invoice.model.DefaultInvoice) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) CreditAdjInvoiceItem(org.killbill.billing.invoice.model.CreditAdjInvoiceItem) WithAccountLock(org.killbill.billing.invoice.api.WithAccountLock) LocalDate(org.joda.time.LocalDate) InvoiceStatus(org.killbill.billing.invoice.api.InvoiceStatus) DefaultInvoice(org.killbill.billing.invoice.model.DefaultInvoice)

Aggregations

InvoiceApiException (org.killbill.billing.invoice.api.InvoiceApiException)56 UUID (java.util.UUID)29 Invoice (org.killbill.billing.invoice.api.Invoice)26 InvoiceItem (org.killbill.billing.invoice.api.InvoiceItem)24 BigDecimal (java.math.BigDecimal)23 LocalDate (org.joda.time.LocalDate)23 DefaultInvoice (org.killbill.billing.invoice.model.DefaultInvoice)19 Test (org.testng.annotations.Test)16 InternalCallContext (org.killbill.billing.callcontext.InternalCallContext)14 FixedPriceInvoiceItem (org.killbill.billing.invoice.model.FixedPriceInvoiceItem)14 RecurringInvoiceItem (org.killbill.billing.invoice.model.RecurringInvoiceItem)14 LinkedList (java.util.LinkedList)13 ItemAdjInvoiceItem (org.killbill.billing.invoice.model.ItemAdjInvoiceItem)12 RepairAdjInvoiceItem (org.killbill.billing.invoice.model.RepairAdjInvoiceItem)12 BillingEventSet (org.killbill.billing.junction.BillingEventSet)9 AccountApiException (org.killbill.billing.account.api.AccountApiException)7 MockPlan (org.killbill.billing.catalog.MockPlan)7 MockPlanPhase (org.killbill.billing.catalog.MockPlanPhase)7 MockBillingEventSet (org.killbill.billing.invoice.MockBillingEventSet)7 SubscriptionFutureNotificationDates (org.killbill.billing.invoice.generator.InvoiceWithMetadata.SubscriptionFutureNotificationDates)7