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());
}
}
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);
}
}
}
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);
}
}
}
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;
}
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);
}
}
Aggregations