Search in sources :

Example 16 with Currency

use of org.killbill.billing.catalog.api.Currency in project killbill by killbill.

the class InvoicePaymentResource method completeInvoicePaymentTransaction.

@TimedResource(name = "completeInvoicePaymentTransaction")
@PUT
@Path("/{paymentId:" + UUID_PATTERN + "}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Complete an existing transaction")
@ApiResponses(value = { @ApiResponse(code = 204, message = "Successful operation"), @ApiResponse(code = 400, message = "Invalid paymentId supplied"), @ApiResponse(code = 404, message = "Account or payment not found"), @ApiResponse(code = 402, message = "Transaction declined by gateway"), @ApiResponse(code = 422, message = "Payment is aborted by a control plugin"), @ApiResponse(code = 502, message = "Failed to submit payment transaction"), @ApiResponse(code = 503, message = "Payment in unknown status, failed to receive gateway response"), @ApiResponse(code = 504, message = "Payment operation timeout") })
public Response completeInvoicePaymentTransaction(@PathParam("paymentId") final UUID paymentId, final PaymentTransactionJson json, @QueryParam(QUERY_PAYMENT_CONTROL_PLUGIN_NAME) final List<String> paymentControlPluginNames, @QueryParam(QUERY_PLUGIN_PROPERTY) final List<String> pluginPropertiesString, @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 UriInfo uriInfo, @javax.ws.rs.core.Context final HttpServletRequest request) throws PaymentApiException, AccountApiException {
    final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
    final Payment payment = paymentApi.getPayment(paymentId, false, false, ImmutableList.<PluginProperty>of(), tenantContext);
    final List<InvoicePayment> invoicePayments = invoicePaymentApi.getInvoicePayments(paymentId, tenantContext);
    final InvoicePayment originalInvoicePaymentAttempt = Iterables.tryFind(invoicePayments, new Predicate<InvoicePayment>() {

        @Override
        public boolean apply(final InvoicePayment input) {
            return input.getType() == InvoicePaymentType.ATTEMPT && !input.isSuccess();
        }
    }).orNull();
    final UUID invoiceId = originalInvoicePaymentAttempt != null ? originalInvoicePaymentAttempt.getInvoiceId() : null;
    if (invoiceId == null) {
        return Response.status(Status.NOT_FOUND).build();
    }
    final Iterable<PluginProperty> pluginProperties = extractPluginProperties(pluginPropertiesString);
    final List<String> controlPluginNames = new ArrayList<String>();
    controlPluginNames.addAll(paymentControlPluginNames);
    final Account account = accountUserApi.getAccountById(payment.getAccountId(), tenantContext);
    final BigDecimal amount = json == null ? null : json.getAmount();
    final Currency currency = json == null ? null : json.getCurrency();
    final CallContext callContext = context.createCallContextWithAccountId(account.getId(), createdBy, reason, comment, request);
    final PaymentTransaction pendingOrSuccessTransaction = lookupPendingOrSuccessTransaction(payment, json != null ? json.getTransactionId() : null, json != null ? json.getTransactionExternalKey() : null, json != null ? json.getTransactionType() : null);
    // If transaction was already completed, return early (See #626)
    if (pendingOrSuccessTransaction.getTransactionStatus() == TransactionStatus.SUCCESS) {
        return Response.status(Status.NO_CONTENT).build();
    }
    final PaymentOptions paymentOptions = createControlPluginApiPaymentOptions(paymentControlPluginNames);
    invoicePaymentApi.createPurchaseForInvoicePayment(account, invoiceId, payment.getPaymentMethodId(), payment.getId(), amount, currency, null, payment.getExternalKey(), pendingOrSuccessTransaction.getExternalKey(), pluginProperties, paymentOptions, callContext);
    return Response.status(Status.NO_CONTENT).build();
}
Also used : InvoicePayment(org.killbill.billing.invoice.api.InvoicePayment) Account(org.killbill.billing.account.api.Account) ArrayList(java.util.ArrayList) TenantContext(org.killbill.billing.util.callcontext.TenantContext) PaymentOptions(org.killbill.billing.payment.api.PaymentOptions) CallContext(org.killbill.billing.util.callcontext.CallContext) BigDecimal(java.math.BigDecimal) Predicate(com.google.common.base.Predicate) PaymentTransaction(org.killbill.billing.payment.api.PaymentTransaction) PluginProperty(org.killbill.billing.payment.api.PluginProperty) InvoicePayment(org.killbill.billing.invoice.api.InvoicePayment) Payment(org.killbill.billing.payment.api.Payment) Currency(org.killbill.billing.catalog.api.Currency) UUID(java.util.UUID) Path(javax.ws.rs.Path) TimedResource(org.killbill.commons.metrics.TimedResource) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) PUT(javax.ws.rs.PUT) ApiResponses(io.swagger.annotations.ApiResponses)

Example 17 with Currency

use of org.killbill.billing.catalog.api.Currency in project killbill by killbill.

the class PaymentResource method refundPaymentInternal.

private Response refundPaymentInternal(final PaymentTransactionJson json, @Nullable final UUID paymentId, final List<String> paymentControlPluginNames, final List<String> pluginPropertiesString, final String createdBy, final String reason, final String comment, final UriInfo uriInfo, final HttpServletRequest request) throws PaymentApiException, AccountApiException {
    verifyNonNullOrEmpty(json, "PaymentTransactionJson body should be specified");
    verifyNonNullOrEmpty(json.getAmount(), "PaymentTransactionJson amount needs to be set");
    final Iterable<PluginProperty> pluginPropertiesFromBody = extractPluginProperties(json.getProperties());
    final Iterable<PluginProperty> pluginPropertiesFromQuery = extractPluginProperties(pluginPropertiesString);
    final Iterable<PluginProperty> pluginProperties = Iterables.concat(pluginPropertiesFromQuery, pluginPropertiesFromBody);
    final CallContext callContext = context.createCallContextNoAccountId(createdBy, reason, comment, request);
    final Payment initialPayment = getPaymentByIdOrKey(paymentId, json.getPaymentExternalKey(), pluginProperties, callContext);
    final Account account = accountUserApi.getAccountById(initialPayment.getAccountId(), callContext);
    final Currency currency = json.getCurrency() == null ? account.getCurrency() : json.getCurrency();
    final PaymentOptions paymentOptions = createControlPluginApiPaymentOptions(paymentControlPluginNames);
    final Payment payment = paymentApi.createRefundWithPaymentControl(account, initialPayment.getId(), json.getAmount(), currency, json.getEffectiveDate(), json.getTransactionExternalKey(), pluginProperties, paymentOptions, callContext);
    return createPaymentResponse(uriInfo, payment, TransactionType.REFUND, json.getTransactionExternalKey(), request);
}
Also used : PluginProperty(org.killbill.billing.payment.api.PluginProperty) Account(org.killbill.billing.account.api.Account) Payment(org.killbill.billing.payment.api.Payment) Currency(org.killbill.billing.catalog.api.Currency) PaymentOptions(org.killbill.billing.payment.api.PaymentOptions) CallContext(org.killbill.billing.util.callcontext.CallContext)

Example 18 with Currency

use of org.killbill.billing.catalog.api.Currency in project killbill by killbill.

the class PaymentResource method chargebackPaymentInternal.

private Response chargebackPaymentInternal(final PaymentTransactionJson json, @Nullable final UUID paymentId, final List<String> paymentControlPluginNames, final List<String> pluginPropertiesString, final String createdBy, final String reason, final String comment, final UriInfo uriInfo, final HttpServletRequest request) throws PaymentApiException, AccountApiException {
    verifyNonNullOrEmpty(json, "PaymentTransactionJson body should be specified");
    verifyNonNullOrEmpty(json.getAmount(), "PaymentTransactionJson amount needs to be set");
    final Iterable<PluginProperty> pluginPropertiesFromBody = extractPluginProperties(json.getProperties());
    final Iterable<PluginProperty> pluginPropertiesFromQuery = extractPluginProperties(pluginPropertiesString);
    final Iterable<PluginProperty> pluginProperties = Iterables.concat(pluginPropertiesFromQuery, pluginPropertiesFromBody);
    final CallContext callContext = context.createCallContextNoAccountId(createdBy, reason, comment, request);
    final Payment initialPayment = getPaymentByIdOrKey(paymentId, json.getPaymentExternalKey(), pluginProperties, callContext);
    final Account account = accountUserApi.getAccountById(initialPayment.getAccountId(), callContext);
    final Currency currency = json.getCurrency() == null ? account.getCurrency() : json.getCurrency();
    final PaymentOptions paymentOptions = createControlPluginApiPaymentOptions(paymentControlPluginNames);
    final Payment payment = paymentApi.createChargebackWithPaymentControl(account, initialPayment.getId(), json.getAmount(), currency, json.getEffectiveDate(), json.getTransactionExternalKey(), paymentOptions, callContext);
    return createPaymentResponse(uriInfo, payment, TransactionType.CHARGEBACK, json.getTransactionExternalKey(), request);
}
Also used : PluginProperty(org.killbill.billing.payment.api.PluginProperty) Account(org.killbill.billing.account.api.Account) Payment(org.killbill.billing.payment.api.Payment) Currency(org.killbill.billing.catalog.api.Currency) PaymentOptions(org.killbill.billing.payment.api.PaymentOptions) CallContext(org.killbill.billing.util.callcontext.CallContext)

Example 19 with Currency

use of org.killbill.billing.catalog.api.Currency 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 20 with Currency

use of org.killbill.billing.catalog.api.Currency in project killbill by killbill.

the class TestInvoiceHelper method generateRegularInvoice.

public UUID generateRegularInvoice(final Account account, final BigDecimal fixedPrice, final BigDecimal recurringPrice, final LocalDate targetDate, final CallContext callContext) throws Exception {
    final SubscriptionBase subscription = Mockito.mock(SubscriptionBase.class);
    Mockito.when(subscription.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(subscription.getBundleId()).thenReturn(new UUID(0L, 0L));
    final BillingEventSet events = new MockBillingEventSet();
    final Plan plan = MockPlan.createBicycleNoTrialEvergreen1USD();
    final PlanPhase planPhase = MockPlanPhase.create1USDMonthlyEvergreen();
    final DateTime effectiveDate = new DateTime().minusDays(1);
    final Currency currency = Currency.USD;
    events.add(createMockBillingEvent(account, subscription, effectiveDate, plan, planPhase, fixedPrice, recurringPrice, currency, BillingPeriod.MONTHLY, 1, BillingMode.IN_ADVANCE, "", 1L, SubscriptionBaseTransitionType.CREATE));
    Mockito.when(billingApi.getBillingEventsForAccountAndUpdateAccountBCD(Mockito.<UUID>any(), Mockito.<DryRunArguments>any(), Mockito.<LocalDate>any(), Mockito.<InternalCallContext>any())).thenReturn(events);
    final InternalCallContext context = internalCallContextFactory.createInternalCallContext(account.getId(), callContext);
    Invoice invoice = generateInvoice(account.getId(), targetDate, new DryRunFutureDateArguments(), context);
    Assert.assertNotNull(invoice);
    List<InvoiceModelDao> invoices = invoiceDao.getInvoicesByAccount(false, context);
    Assert.assertEquals(invoices.size(), 0);
    invoice = generateInvoice(account.getId(), targetDate, null, context);
    Assert.assertNotNull(invoice);
    invoices = invoiceDao.getInvoicesByAccount(false, context);
    Assert.assertEquals(invoices.size(), 1);
    return invoice.getId();
}
Also used : Invoice(org.killbill.billing.invoice.api.Invoice) InvoiceModelDao(org.killbill.billing.invoice.dao.InvoiceModelDao) InternalCallContext(org.killbill.billing.callcontext.InternalCallContext) MutableInternalCallContext(org.killbill.billing.callcontext.MutableInternalCallContext) MockPlan(org.killbill.billing.catalog.MockPlan) Plan(org.killbill.billing.catalog.api.Plan) DateTime(org.joda.time.DateTime) SubscriptionBase(org.killbill.billing.subscription.api.SubscriptionBase) BillingEventSet(org.killbill.billing.junction.BillingEventSet) Currency(org.killbill.billing.catalog.api.Currency) PlanPhase(org.killbill.billing.catalog.api.PlanPhase) MockPlanPhase(org.killbill.billing.catalog.MockPlanPhase) UUID(java.util.UUID)

Aggregations

Currency (org.killbill.billing.catalog.api.Currency)65 BigDecimal (java.math.BigDecimal)36 UUID (java.util.UUID)31 DateTime (org.joda.time.DateTime)21 Test (org.testng.annotations.Test)20 LocalDate (org.joda.time.LocalDate)18 PluginProperty (org.killbill.billing.payment.api.PluginProperty)16 Invoice (org.killbill.billing.invoice.api.Invoice)15 MockPlan (org.killbill.billing.catalog.MockPlan)13 Plan (org.killbill.billing.catalog.api.Plan)13 Account (org.killbill.billing.account.api.Account)12 PlanPhase (org.killbill.billing.catalog.api.PlanPhase)12 DefaultInvoice (org.killbill.billing.invoice.model.DefaultInvoice)12 PaymentOptions (org.killbill.billing.payment.api.PaymentOptions)12 CallContext (org.killbill.billing.util.callcontext.CallContext)12 MockPlanPhase (org.killbill.billing.catalog.MockPlanPhase)11 Payment (org.killbill.billing.payment.api.Payment)11 SubscriptionBase (org.killbill.billing.subscription.api.SubscriptionBase)11 AccountInvoices (org.killbill.billing.invoice.optimizer.InvoiceOptimizerBase.AccountInvoices)9 BillingEventSet (org.killbill.billing.junction.BillingEventSet)9