Search in sources :

Example 26 with Predicate

use of com.google.common.base.Predicate in project killbill by killbill.

the class TestUsage method testRecordUsageTrackingIdExists.

@Test(groups = "slow", description = "Test tracking ID already exists")
public void testRecordUsageTrackingIdExists() throws Exception {
    final Account accountJson = createAccountWithDefaultPaymentMethod();
    final Subscription base = new Subscription();
    base.setAccountId(accountJson.getAccountId());
    base.setProductName("Pistol");
    base.setProductCategory(ProductCategory.BASE);
    base.setBillingPeriod(BillingPeriod.MONTHLY);
    base.setPriceList(PriceListSet.DEFAULT_PRICELIST_NAME);
    final Subscription addOn = new Subscription();
    addOn.setAccountId(accountJson.getAccountId());
    addOn.setProductName("Bullets");
    addOn.setProductCategory(ProductCategory.ADD_ON);
    addOn.setBillingPeriod(BillingPeriod.NO_BILLING_PERIOD);
    addOn.setPriceList(PriceListSet.DEFAULT_PRICELIST_NAME);
    final Bundle bundle = killBillClient.createSubscriptionWithAddOns(ImmutableList.<Subscription>of(base, addOn), null, DEFAULT_WAIT_COMPLETION_TIMEOUT_SEC, createdBy, reason, comment);
    final UUID addOnSubscriptionId = Iterables.<Subscription>find(bundle.getSubscriptions(), new Predicate<Subscription>() {

        @Override
        public boolean apply(final Subscription input) {
            return ProductCategory.ADD_ON.equals(input.getProductCategory());
        }
    }).getSubscriptionId();
    final UsageRecord usageRecord1 = new UsageRecord();
    usageRecord1.setAmount(10L);
    usageRecord1.setRecordDate(clock.getUTCToday().minusDays(1));
    final UnitUsageRecord unitUsageRecord = new UnitUsageRecord();
    unitUsageRecord.setUnitType("bullets");
    unitUsageRecord.setUsageRecords(ImmutableList.<UsageRecord>of(usageRecord1));
    final SubscriptionUsageRecord usage = new SubscriptionUsageRecord();
    usage.setSubscriptionId(addOnSubscriptionId);
    usage.setTrackingId(UUID.randomUUID().toString());
    usage.setUnitUsageRecords(ImmutableList.<UnitUsageRecord>of(unitUsageRecord));
    killBillClient.createSubscriptionUsageRecord(usage, createdBy, reason, comment);
    try {
        killBillClient.createSubscriptionUsageRecord(usage, createdBy, reason, comment);
        Assert.fail();
    } catch (final KillBillClientException e) {
        Assert.assertEquals(e.getBillingException().getCode(), (Integer) ErrorCode.USAGE_RECORD_TRACKING_ID_ALREADY_EXISTS.getCode());
    }
}
Also used : Account(org.killbill.billing.client.model.Account) Bundle(org.killbill.billing.client.model.Bundle) UnitUsageRecord(org.killbill.billing.client.model.UnitUsageRecord) SubscriptionUsageRecord(org.killbill.billing.client.model.SubscriptionUsageRecord) UsageRecord(org.killbill.billing.client.model.UsageRecord) UnitUsageRecord(org.killbill.billing.client.model.UnitUsageRecord) KillBillClientException(org.killbill.billing.client.KillBillClientException) Subscription(org.killbill.billing.client.model.Subscription) UUID(java.util.UUID) SubscriptionUsageRecord(org.killbill.billing.client.model.SubscriptionUsageRecord) Predicate(com.google.common.base.Predicate) Test(org.testng.annotations.Test)

Example 27 with Predicate

use of com.google.common.base.Predicate in project killbill by killbill.

the class TestDefaultPriceOverride method testGetOverriddenPlan.

@Test(groups = "slow")
public void testGetOverriddenPlan() throws Exception {
    final StandaloneCatalog catalog = XMLLoader.getObjectFromString(Resources.getResource("SpyCarAdvanced.xml").toExternalForm(), StandaloneCatalog.class);
    catalog.initialize(catalog, null);
    final Plan plan = catalog.findCurrentPlan("discount-standard-monthly");
    final List<PlanPhasePriceOverride> overrides = new ArrayList<PlanPhasePriceOverride>();
    final PlanPhasePriceOverride phase1 = new DefaultPlanPhasePriceOverride(plan.getAllPhases()[0].getName(), Currency.USD, BigDecimal.ONE, null);
    overrides.add(phase1);
    final PlanPhasePriceOverride phase3 = new DefaultPlanPhasePriceOverride(plan.getAllPhases()[2].getName(), Currency.USD, null, new BigDecimal("142.41"));
    overrides.add(phase3);
    final DefaultPlan overriddenPlanCreated = priceOverride.getOrCreateOverriddenPlan(catalog, plan, new DateTime(catalog.getEffectiveDate()), overrides, internalCallContext);
    System.out.println("overriddenPlanCreated = " + overriddenPlanCreated.getName());
    final DefaultPlan overriddenPlan = priceOverride.getOverriddenPlan(overriddenPlanCreated.getName(), catalog, internalCallContext);
    assertEquals(overriddenPlan.getProduct().getName(), plan.getProduct().getName());
    assertEquals(overriddenPlan.getRecurringBillingPeriod(), plan.getRecurringBillingPeriod());
    if (plan.getEffectiveDateForExistingSubscriptions() != null) {
        assertEquals(overriddenPlan.getEffectiveDateForExistingSubscriptions().compareTo(plan.getEffectiveDateForExistingSubscriptions()), 0);
    }
    assertNotEquals(overriddenPlan.getFinalPhase().getName(), plan.getFinalPhase().getName());
    assertEquals(overriddenPlan.getPlansAllowedInBundle(), plan.getPlansAllowedInBundle());
    assertEquals(overriddenPlan.getAllPhases().length, overriddenPlan.getAllPhases().length);
    for (int i = 0; i < overriddenPlan.getAllPhases().length; i++) {
        final DefaultPlanPhase initialPhase = (DefaultPlanPhase) plan.getAllPhases()[i];
        final DefaultPlanPhase newPhase = (DefaultPlanPhase) overriddenPlan.getAllPhases()[i];
        final PlanPhasePriceOverride override = Iterables.tryFind(overrides, new Predicate<PlanPhasePriceOverride>() {

            @Override
            public boolean apply(final PlanPhasePriceOverride input) {
                return input.getPhaseName().equals(initialPhase.getName());
            }
        }).orNull();
        assertNotEquals(newPhase.getName(), initialPhase.getName());
        assertEquals(newPhase.getName(), overriddenPlan.getName() + "-" + initialPhase.getName().split("-")[initialPhase.getName().split("-").length - 1]);
        assertEquals(newPhase.getDuration(), initialPhase.getDuration());
        assertEquals(newPhase.getPhaseType(), initialPhase.getPhaseType());
        assertEquals(newPhase.getUsages().length, initialPhase.getUsages().length);
        if (initialPhase.getFixed() != null) {
            assertEquals(newPhase.getFixed().getType(), initialPhase.getFixed().getType());
            assertInternationalPrice(newPhase.getFixed().getPrice(), initialPhase.getFixed().getPrice(), override, true);
        }
        if (initialPhase.getRecurring() != null) {
            assertInternationalPrice(newPhase.getRecurring().getRecurringPrice(), initialPhase.getRecurring().getRecurringPrice(), override, false);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Plan(org.killbill.billing.catalog.api.Plan) BigDecimal(java.math.BigDecimal) DateTime(org.joda.time.DateTime) PlanPhasePriceOverride(org.killbill.billing.catalog.api.PlanPhasePriceOverride) Predicate(com.google.common.base.Predicate) Test(org.testng.annotations.Test)

Example 28 with Predicate

use of com.google.common.base.Predicate in project killbill by killbill.

the class TestDefaultPriceOverride method testBasic.

@Test(groups = "slow")
public void testBasic() throws Exception {
    final StandaloneCatalog catalog = XMLLoader.getObjectFromString(Resources.getResource("SpyCarAdvanced.xml").toExternalForm(), StandaloneCatalog.class);
    catalog.initialize(catalog, null);
    final Plan plan = catalog.findCurrentPlan("discount-standard-monthly");
    final List<PlanPhasePriceOverride> overrides = new ArrayList<PlanPhasePriceOverride>();
    final PlanPhasePriceOverride phase1 = new DefaultPlanPhasePriceOverride(plan.getAllPhases()[0].getName(), Currency.USD, BigDecimal.ONE, null);
    overrides.add(phase1);
    final PlanPhasePriceOverride phase3 = new DefaultPlanPhasePriceOverride(plan.getAllPhases()[2].getName(), Currency.USD, null, new BigDecimal("142.41"));
    overrides.add(phase3);
    final DefaultPlan overriddenPlan = priceOverride.getOrCreateOverriddenPlan(catalog, plan, new DateTime(catalog.getEffectiveDate()), overrides, internalCallContext);
    final Matcher m = DefaultPriceOverride.CUSTOM_PLAN_NAME_PATTERN.matcher(overriddenPlan.getName());
    assertTrue(m.matches());
    assertEquals(m.group(1), plan.getName());
    assertEquals(overriddenPlan.getProduct().getName(), plan.getProduct().getName());
    assertEquals(overriddenPlan.getRecurringBillingPeriod(), plan.getRecurringBillingPeriod());
    if (plan.getEffectiveDateForExistingSubscriptions() != null) {
        assertEquals(overriddenPlan.getEffectiveDateForExistingSubscriptions().compareTo(plan.getEffectiveDateForExistingSubscriptions()), 0);
    }
    assertNotEquals(overriddenPlan.getFinalPhase().getName(), plan.getFinalPhase().getName());
    assertEquals(overriddenPlan.getPlansAllowedInBundle(), plan.getPlansAllowedInBundle());
    assertEquals(overriddenPlan.getAllPhases().length, overriddenPlan.getAllPhases().length);
    for (int i = 0; i < overriddenPlan.getAllPhases().length; i++) {
        final DefaultPlanPhase initialPhase = (DefaultPlanPhase) plan.getAllPhases()[i];
        final DefaultPlanPhase newPhase = (DefaultPlanPhase) overriddenPlan.getAllPhases()[i];
        final PlanPhasePriceOverride override = Iterables.tryFind(overrides, new Predicate<PlanPhasePriceOverride>() {

            @Override
            public boolean apply(final PlanPhasePriceOverride input) {
                return input.getPhaseName().equals(initialPhase.getName());
            }
        }).orNull();
        assertNotEquals(newPhase.getName(), initialPhase.getName());
        assertEquals(newPhase.getDuration(), initialPhase.getDuration());
        assertEquals(newPhase.getPhaseType(), initialPhase.getPhaseType());
        assertEquals(newPhase.getUsages().length, initialPhase.getUsages().length);
        if (initialPhase.getFixed() != null) {
            assertEquals(newPhase.getFixed().getType(), initialPhase.getFixed().getType());
            assertInternationalPrice(newPhase.getFixed().getPrice(), initialPhase.getFixed().getPrice(), override, true);
        }
        if (initialPhase.getRecurring() != null) {
            assertInternationalPrice(newPhase.getRecurring().getRecurringPrice(), initialPhase.getRecurring().getRecurringPrice(), override, false);
        }
    }
}
Also used : Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) Plan(org.killbill.billing.catalog.api.Plan) BigDecimal(java.math.BigDecimal) DateTime(org.joda.time.DateTime) Predicate(com.google.common.base.Predicate) PlanPhasePriceOverride(org.killbill.billing.catalog.api.PlanPhasePriceOverride) Test(org.testng.annotations.Test)

Example 29 with Predicate

use of com.google.common.base.Predicate 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 30 with Predicate

use of com.google.common.base.Predicate in project killbill by killbill.

the class PluginControlPaymentProcessor method retryPaymentTransaction.

public void retryPaymentTransaction(final UUID attemptId, final List<String> paymentControlPluginNames, final InternalCallContext internalCallContext) {
    final PaymentAttemptModelDao attempt = paymentDao.getPaymentAttempt(attemptId, internalCallContext);
    log.info("Retrying attemptId='{}', paymentExternalKey='{}', transactionExternalKey='{}'. paymentControlPluginNames='{}'", attemptId, attempt.getPaymentExternalKey(), attempt.getTransactionExternalKey(), paymentControlPluginNames);
    final PaymentModelDao paymentModelDao = paymentDao.getPaymentByExternalKey(attempt.getPaymentExternalKey(), internalCallContext);
    final UUID paymentId = paymentModelDao != null ? paymentModelDao.getId() : null;
    final CallContext callContext = buildCallContext(internalCallContext);
    final String transactionType = TransactionType.PURCHASE.name();
    Account account = null;
    Payment payment = null;
    PaymentTransaction paymentTransaction = null;
    try {
        account = accountInternalApi.getAccountById(attempt.getAccountId(), internalCallContext);
        final State state = paymentControlStateMachineHelper.getState(attempt.getStateName());
        final Iterable<PluginProperty> pluginProperties = PluginPropertySerializer.deserialize(attempt.getPluginProperties());
        logEnterAPICall(log, transactionType, account, attempt.getPaymentMethodId(), paymentId, null, attempt.getAmount(), attempt.getCurrency(), attempt.getPaymentExternalKey(), attempt.getTransactionExternalKey(), null, paymentControlPluginNames);
        payment = pluginControlledPaymentAutomatonRunner.run(state, false, attempt.getTransactionType(), ControlOperation.valueOf(attempt.getTransactionType().toString()), account, attempt.getPaymentMethodId(), paymentId, attempt.getPaymentExternalKey(), attempt.getTransactionExternalKey(), attempt.getAmount(), attempt.getCurrency(), pluginProperties, paymentControlPluginNames, callContext, internalCallContext);
        paymentTransaction = Iterables.<PaymentTransaction>find(Lists.<PaymentTransaction>reverse(payment.getTransactions()), new Predicate<PaymentTransaction>() {

            @Override
            public boolean apply(final PaymentTransaction input) {
                return attempt.getTransactionExternalKey().equals(input.getExternalKey());
            }
        });
    } catch (final AccountApiException e) {
        log.warn("Failed to retry attemptId='{}', paymentControlPlugins='{}'", attemptId, toPluginNamesOnError(paymentControlPluginNames), e);
    } catch (final PaymentApiException e) {
        // Log exception unless nothing left to be paid
        if (e.getCode() == ErrorCode.PAYMENT_PLUGIN_API_ABORTED.getCode() && paymentControlPluginNames != null && paymentControlPluginNames.size() == 1 && InvoicePaymentControlPluginApi.PLUGIN_NAME.equals(paymentControlPluginNames.get(0))) {
            log.warn("Failed to retry attemptId='{}', paymentControlPlugins='{}'. Invoice has already been paid", attemptId, toPluginNamesOnError(paymentControlPluginNames));
        } else {
            log.warn("Failed to retry attemptId='{}', paymentControlPlugins='{}'", attemptId, toPluginNamesOnError(paymentControlPluginNames), e);
        }
    } catch (final PluginPropertySerializerException e) {
        log.warn("Failed to retry attemptId='{}', paymentControlPlugins='{}'", attemptId, toPluginNamesOnError(paymentControlPluginNames), e);
    } catch (final MissingEntryException e) {
        log.warn("Failed to retry attemptId='{}', paymentControlPlugins='{}'", attemptId, toPluginNamesOnError(paymentControlPluginNames), e);
    } finally {
        logExitAPICall(log, transactionType, account, payment != null ? payment.getPaymentMethodId() : null, payment != null ? payment.getId() : null, paymentTransaction != null ? paymentTransaction.getId() : null, paymentTransaction != null ? paymentTransaction.getProcessedAmount() : null, paymentTransaction != null ? paymentTransaction.getProcessedCurrency() : null, payment != null ? payment.getExternalKey() : null, paymentTransaction != null ? paymentTransaction.getExternalKey() : null, paymentTransaction != null ? paymentTransaction.getTransactionStatus() : null, paymentControlPluginNames, null);
    }
}
Also used : PaymentAttemptModelDao(org.killbill.billing.payment.dao.PaymentAttemptModelDao) Account(org.killbill.billing.account.api.Account) PaymentModelDao(org.killbill.billing.payment.dao.PaymentModelDao) PluginPropertySerializerException(org.killbill.billing.payment.dao.PluginPropertySerializer.PluginPropertySerializerException) PaymentApiException(org.killbill.billing.payment.api.PaymentApiException) InternalCallContext(org.killbill.billing.callcontext.InternalCallContext) CallContext(org.killbill.billing.util.callcontext.CallContext) Predicate(com.google.common.base.Predicate) PaymentTransaction(org.killbill.billing.payment.api.PaymentTransaction) PluginProperty(org.killbill.billing.payment.api.PluginProperty) Payment(org.killbill.billing.payment.api.Payment) State(org.killbill.automaton.State) AccountApiException(org.killbill.billing.account.api.AccountApiException) MissingEntryException(org.killbill.automaton.MissingEntryException) UUID(java.util.UUID)

Aggregations

Predicate (com.google.common.base.Predicate)180 ArrayList (java.util.ArrayList)29 Nullable (javax.annotation.Nullable)29 Test (org.junit.Test)29 List (java.util.List)28 UUID (java.util.UUID)21 IOException (java.io.IOException)20 Map (java.util.Map)20 File (java.io.File)15 Test (org.testng.annotations.Test)14 ImmutableList (com.google.common.collect.ImmutableList)12 HashMap (java.util.HashMap)12 Set (java.util.Set)9 DateTime (org.joda.time.DateTime)9 BigDecimal (java.math.BigDecimal)8 Path (javax.ws.rs.Path)8 PaymentTransactionModelDao (org.killbill.billing.payment.dao.PaymentTransactionModelDao)8 Account (org.killbill.billing.account.api.Account)7 PlanPhasePriceOverride (org.killbill.billing.catalog.api.PlanPhasePriceOverride)7 PaymentModelDao (org.killbill.billing.payment.dao.PaymentModelDao)7