Search in sources :

Example 6 with InvoicePayment

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

the class TestInvoiceDao method testAccountBalanceWithRefundInternal.

private void testAccountBalanceWithRefundInternal(final boolean withAdjustment) throws InvoiceApiException, EntityPersistenceException {
    final UUID accountId = account.getId();
    final UUID bundleId = UUID.randomUUID();
    final LocalDate targetDate1 = new LocalDate(2011, 10, 6);
    final Invoice invoice1 = new DefaultInvoice(accountId, clock.getUTCToday(), targetDate1, Currency.USD);
    invoiceUtil.createInvoice(invoice1, context);
    final LocalDate startDate = new LocalDate(2011, 3, 1);
    final LocalDate endDate = startDate.plusMonths(1);
    final BigDecimal rate1 = new BigDecimal("20.0");
    final BigDecimal refund1 = new BigDecimal("7.00");
    // Recurring item
    final RecurringInvoiceItem item2 = new RecurringInvoiceItem(invoice1.getId(), accountId, bundleId, UUID.randomUUID(), "test plan", "test phase B", startDate, endDate, rate1, rate1, Currency.USD);
    invoiceUtil.createInvoiceItem(item2, context);
    BigDecimal balance = invoiceDao.getAccountBalance(accountId, context);
    assertEquals(balance.compareTo(new BigDecimal("20.00")), 0);
    // Pay the whole thing
    final UUID paymentId = UUID.randomUUID();
    final BigDecimal payment1 = rate1;
    final InvoicePayment payment = new DefaultInvoicePayment(InvoicePaymentType.ATTEMPT, paymentId, invoice1.getId(), new DateTime(), payment1, Currency.USD, Currency.USD, null, true);
    invoiceUtil.createPayment(payment, context);
    balance = invoiceDao.getAccountBalance(accountId, context);
    assertEquals(balance.compareTo(new BigDecimal("0.00")), 0);
    invoiceDao.createRefund(paymentId, refund1, withAdjustment, ImmutableMap.<UUID, BigDecimal>of(), UUID.randomUUID().toString(), context);
    balance = invoiceDao.getAccountBalance(accountId, context);
    if (withAdjustment) {
        assertEquals(balance.compareTo(BigDecimal.ZERO), 0);
    } else {
        assertEquals(balance.compareTo(new BigDecimal("7.00")), 0);
    }
}
Also used : InvoicePayment(org.killbill.billing.invoice.api.InvoicePayment) DefaultInvoicePayment(org.killbill.billing.invoice.model.DefaultInvoicePayment) Invoice(org.killbill.billing.invoice.api.Invoice) DefaultInvoice(org.killbill.billing.invoice.model.DefaultInvoice) RecurringInvoiceItem(org.killbill.billing.invoice.model.RecurringInvoiceItem) UUID(java.util.UUID) LocalDate(org.joda.time.LocalDate) DefaultInvoice(org.killbill.billing.invoice.model.DefaultInvoice) BigDecimal(java.math.BigDecimal) DateTime(org.joda.time.DateTime) DefaultInvoicePayment(org.killbill.billing.invoice.model.DefaultInvoicePayment)

Example 7 with InvoicePayment

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

the class InvoicePaymentControlPluginApi method checkForIncompleteInvoicePaymentAndRepair.

private boolean checkForIncompleteInvoicePaymentAndRepair(final Invoice invoice, final InternalCallContext internalContext) throws InvoiceApiException {
    final List<InvoicePayment> invoicePayments = invoice.getPayments();
    // Look for ATTEMPT matching that invoiceId that are not successful and extract matching paymentTransaction
    final InvoicePayment incompleteInvoicePayment = Iterables.tryFind(invoicePayments, new Predicate<InvoicePayment>() {

        @Override
        public boolean apply(final InvoicePayment input) {
            return input.getType() == InvoicePaymentType.ATTEMPT && !input.isSuccess();
        }
    }).orNull();
    // If such (incomplete) paymentTransaction exists, verify the state of the payment transaction
    if (incompleteInvoicePayment != null) {
        final String transactionExternalKey = incompleteInvoicePayment.getPaymentCookieId();
        final List<PaymentTransactionModelDao> transactions = paymentDao.getPaymentTransactionsByExternalKey(transactionExternalKey, internalContext);
        final PaymentTransactionModelDao successfulTransaction = Iterables.tryFind(transactions, new Predicate<PaymentTransactionModelDao>() {

            @Override
            public boolean apply(final PaymentTransactionModelDao input) {
                //
                return input.getTransactionStatus() == TransactionStatus.SUCCESS;
            }
        }).orNull();
        if (successfulTransaction != null) {
            log.info(String.format("Detected an incomplete invoicePayment row for invoiceId='%s' and transactionExternalKey='%s', will correct status", invoice.getId(), successfulTransaction.getTransactionExternalKey()));
            invoiceApi.recordPaymentAttemptCompletion(invoice.getId(), successfulTransaction.getAmount(), successfulTransaction.getCurrency(), successfulTransaction.getProcessedCurrency(), successfulTransaction.getPaymentId(), successfulTransaction.getTransactionExternalKey(), successfulTransaction.getCreatedDate(), true, internalContext);
            return true;
        }
    }
    return false;
}
Also used : InvoicePayment(org.killbill.billing.invoice.api.InvoicePayment) PaymentTransactionModelDao(org.killbill.billing.payment.dao.PaymentTransactionModelDao) Predicate(com.google.common.base.Predicate)

Example 8 with InvoicePayment

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

the class DefaultInvoiceFormatter method getProcessedPaymentRate.

@Override
public String getProcessedPaymentRate() {
    final Currency currency = getProcessedCurrency();
    if (currency == null) {
        return null;
    }
    // If there were multiple payments (and refunds) we pick chose the last one
    DateTime latestPaymentDate = null;
    final Iterator<InvoicePayment> paymentIterator = invoice.getPayments().iterator();
    while (paymentIterator.hasNext()) {
        final InvoicePayment cur = paymentIterator.next();
        latestPaymentDate = latestPaymentDate != null && latestPaymentDate.isAfter(cur.getPaymentDate()) ? latestPaymentDate : cur.getPaymentDate();
    }
    try {
        final CurrencyConversion conversion = currencyConversionApi.getCurrencyConversion(currency, latestPaymentDate);
        for (final Rate rate : conversion.getRates()) {
            if (rate.getCurrency() == getCurrency()) {
                return rate.getValue().toString();
            }
        }
    } catch (final CurrencyConversionException e) {
        logger.warn("Failed to retrieve currency conversion rates for currency='{}', dateConversion='{}'", currency, latestPaymentDate, e);
        return null;
    }
    logger.warn("Failed to retrieve currency conversion rates for currency='{}', dateConversion='{}'", currency, latestPaymentDate);
    return null;
}
Also used : InvoicePayment(org.killbill.billing.invoice.api.InvoicePayment) Rate(org.killbill.billing.currency.api.Rate) Currency(org.killbill.billing.catalog.api.Currency) CurrencyConversion(org.killbill.billing.currency.api.CurrencyConversion) CurrencyConversionException(org.killbill.billing.currency.api.CurrencyConversionException) DateTime(org.joda.time.DateTime)

Example 9 with InvoicePayment

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

the class InvoiceTestUtils method createAndPersistPayment.

public static InvoicePayment createAndPersistPayment(final InvoiceInternalApi invoicePaymentApi, final Clock clock, final UUID invoiceId, final BigDecimal amount, final Currency currency, final InternalCallContext callContext) throws InvoiceApiException {
    final InvoicePayment payment = Mockito.mock(InvoicePayment.class);
    Mockito.when(payment.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(payment.getType()).thenReturn(InvoicePaymentType.ATTEMPT);
    Mockito.when(payment.getInvoiceId()).thenReturn(invoiceId);
    Mockito.when(payment.getPaymentId()).thenReturn(UUID.randomUUID());
    Mockito.when(payment.getPaymentCookieId()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(payment.getPaymentDate()).thenReturn(clock.getUTCNow());
    Mockito.when(payment.getAmount()).thenReturn(amount);
    Mockito.when(payment.getCurrency()).thenReturn(currency);
    Mockito.when(payment.getProcessedCurrency()).thenReturn(currency);
    Mockito.when(payment.isSuccess()).thenReturn(true);
    invoicePaymentApi.recordPaymentAttemptCompletion(payment.getInvoiceId(), payment.getAmount(), payment.getCurrency(), payment.getProcessedCurrency(), payment.getPaymentId(), payment.getPaymentCookieId(), payment.getPaymentDate(), payment.isSuccess(), callContext);
    return payment;
}
Also used : InvoicePayment(org.killbill.billing.invoice.api.InvoicePayment)

Example 10 with InvoicePayment

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

the class InvoicePaymentResource method getInvoicePayment.

@TimedResource
@GET
@Path("/{paymentId:" + UUID_PATTERN + "}/")
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Retrieve a payment by id", response = InvoicePaymentJson.class)
@ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid payment id supplied"), @ApiResponse(code = 404, message = "Payment not found") })
public Response getInvoicePayment(@PathParam("paymentId") final String paymentIdStr, @QueryParam(QUERY_WITH_PLUGIN_INFO) @DefaultValue("false") final Boolean withPluginInfo, @QueryParam(QUERY_WITH_ATTEMPTS) @DefaultValue("false") final Boolean withAttempts, @QueryParam(QUERY_PLUGIN_PROPERTY) final List<String> pluginPropertiesString, @QueryParam(QUERY_AUDIT) @DefaultValue("NONE") final AuditMode auditMode, @javax.ws.rs.core.Context final HttpServletRequest request) throws PaymentApiException {
    final Iterable<PluginProperty> pluginProperties = extractPluginProperties(pluginPropertiesString);
    final UUID paymentIdId = UUID.fromString(paymentIdStr);
    final TenantContext tenantContext = context.createContext(request);
    final Payment payment = paymentApi.getPayment(paymentIdId, withPluginInfo, withAttempts, pluginProperties, tenantContext);
    final AccountAuditLogs accountAuditLogs = auditUserApi.getAccountAuditLogs(payment.getAccountId(), auditMode.getLevel(), tenantContext);
    final List<InvoicePayment> invoicePayments = invoicePaymentApi.getInvoicePayments(paymentIdId, tenantContext);
    final InvoicePayment invoicePayment = Iterables.tryFind(invoicePayments, new Predicate<InvoicePayment>() {

        @Override
        public boolean apply(final InvoicePayment input) {
            return input.getType() == InvoicePaymentType.ATTEMPT && input.isSuccess();
        }
    }).orNull();
    final UUID invoiceId = invoicePayment != null ? invoicePayment.getInvoiceId() : null;
    final InvoicePaymentJson result = new InvoicePaymentJson(payment, invoiceId, accountAuditLogs);
    return Response.status(Response.Status.OK).entity(result).build();
}
Also used : PluginProperty(org.killbill.billing.payment.api.PluginProperty) InvoicePayment(org.killbill.billing.invoice.api.InvoicePayment) InvoicePayment(org.killbill.billing.invoice.api.InvoicePayment) Payment(org.killbill.billing.payment.api.Payment) InvoicePaymentJson(org.killbill.billing.jaxrs.json.InvoicePaymentJson) TenantContext(org.killbill.billing.util.callcontext.TenantContext) UUID(java.util.UUID) AccountAuditLogs(org.killbill.billing.util.audit.AccountAuditLogs) Predicate(com.google.common.base.Predicate) Path(javax.ws.rs.Path) TimedResource(org.killbill.commons.metrics.TimedResource) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

InvoicePayment (org.killbill.billing.invoice.api.InvoicePayment)20 UUID (java.util.UUID)11 BigDecimal (java.math.BigDecimal)9 DateTime (org.joda.time.DateTime)8 Invoice (org.killbill.billing.invoice.api.Invoice)8 DefaultInvoicePayment (org.killbill.billing.invoice.model.DefaultInvoicePayment)8 LocalDate (org.joda.time.LocalDate)7 DefaultInvoice (org.killbill.billing.invoice.model.DefaultInvoice)6 Payment (org.killbill.billing.payment.api.Payment)6 RecurringInvoiceItem (org.killbill.billing.invoice.model.RecurringInvoiceItem)5 ApiOperation (io.swagger.annotations.ApiOperation)4 ApiResponses (io.swagger.annotations.ApiResponses)4 GET (javax.ws.rs.GET)4 Path (javax.ws.rs.Path)4 Produces (javax.ws.rs.Produces)4 TenantContext (org.killbill.billing.util.callcontext.TenantContext)4 TimedResource (org.killbill.commons.metrics.TimedResource)4 Predicate (com.google.common.base.Predicate)3 ArrayList (java.util.ArrayList)3 CreditBalanceAdjInvoiceItem (org.killbill.billing.invoice.model.CreditBalanceAdjInvoiceItem)3