Search in sources :

Example 56 with CatalogApiException

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

the class DefaultSubscriptionInternalApi method createBundleForAccount.

@Override
public SubscriptionBaseBundle createBundleForAccount(final UUID accountId, final String bundleKey, final InternalCallContext context) throws SubscriptionBaseApiException {
    final List<SubscriptionBaseBundle> existingBundles = dao.getSubscriptionBundlesForKey(bundleKey, context);
    //
    // Because the creation of the SubscriptionBundle is not atomic (with creation of Subscription/SubscriptionEvent), we verify if we were left
    // with an empty SubscriptionBaseBundle form a past failing operation (See #684). We only allow reuse if such SubscriptionBaseBundle is fully
    // empty (and don't allow use case where all Subscription are cancelled, which is the condition for that key to be re-used)
    // Such condition should have been checked upstream (to decide whether that key is valid or not)
    //
    final SubscriptionBaseBundle existingBundleForAccount = Iterables.tryFind(existingBundles, new Predicate<SubscriptionBaseBundle>() {

        @Override
        public boolean apply(final SubscriptionBaseBundle input) {
            return input.getAccountId().equals(accountId);
        }
    }).orNull();
    // If Bundle already exists, and there is 0 Subscription, we reuse
    if (existingBundleForAccount != null) {
        try {
            final Map<UUID, List<SubscriptionBase>> accountSubscriptions = dao.getSubscriptionsForAccount(context);
            final List<SubscriptionBase> subscriptions = accountSubscriptions.get(existingBundleForAccount.getId());
            if (subscriptions == null || subscriptions.size() == 0) {
                return existingBundleForAccount;
            }
        } catch (final CatalogApiException e) {
            throw new SubscriptionBaseApiException(e);
        }
    }
    final DateTime now = clock.getUTCNow();
    final DateTime originalCreatedDate = !existingBundles.isEmpty() ? existingBundles.get(0).getCreatedDate() : now;
    final DefaultSubscriptionBaseBundle bundle = new DefaultSubscriptionBaseBundle(bundleKey, accountId, now, originalCreatedDate, now, now);
    if (null != bundleKey && bundleKey.length() > 255) {
        throw new SubscriptionBaseApiException(ErrorCode.EXTERNAL_KEY_LIMIT_EXCEEDED);
    }
    return dao.createSubscriptionBundle(bundle, context);
}
Also used : SubscriptionBase(org.killbill.billing.subscription.api.SubscriptionBase) DefaultSubscriptionBase(org.killbill.billing.subscription.api.user.DefaultSubscriptionBase) DefaultSubscriptionBaseBundle(org.killbill.billing.subscription.api.user.DefaultSubscriptionBaseBundle) CatalogApiException(org.killbill.billing.catalog.api.CatalogApiException) SubscriptionBaseBundle(org.killbill.billing.subscription.api.user.SubscriptionBaseBundle) DefaultSubscriptionBaseBundle(org.killbill.billing.subscription.api.user.DefaultSubscriptionBaseBundle) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) LinkedList(java.util.LinkedList) UUID(java.util.UUID) SubscriptionBaseApiException(org.killbill.billing.subscription.api.user.SubscriptionBaseApiException) DateTime(org.joda.time.DateTime) Predicate(com.google.common.base.Predicate) PlanPhasePriceOverride(org.killbill.billing.catalog.api.PlanPhasePriceOverride)

Example 57 with CatalogApiException

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

the class TestBlockingCalculator method createRealEvent.

protected BillingEvent createRealEvent(final DateTime effectiveDate, final SubscriptionBase subscription, final SubscriptionBaseTransitionType type) {
    try {
        final Integer billCycleDay = 1;
        final Plan plan = new MockPlan();
        final Currency currency = Currency.USD;
        final String description = "";
        final BillingPeriod billingPeriod = BillingPeriod.MONTHLY;
        final Long totalOrdering = 0L;
        final DateTimeZone tz = DateTimeZone.UTC;
        final PlanPhase planPhase = Mockito.mock(PlanPhase.class);
        final InternationalPrice recurringPrice = Mockito.mock(InternationalPrice.class);
        Mockito.when(recurringPrice.getPrice(Mockito.<Currency>any())).thenReturn(BigDecimal.TEN);
        final Recurring recurring = Mockito.mock(Recurring.class);
        Mockito.when(recurring.getRecurringPrice()).thenReturn(recurringPrice);
        Mockito.when(planPhase.getRecurring()).thenReturn(recurring);
        Mockito.when(planPhase.getUsages()).thenReturn(new DefaultUsage[0]);
        final BigDecimal fixedPrice = BigDecimal.TEN;
        return new DefaultBillingEvent(subscription, effectiveDate, true, plan, planPhase, fixedPrice, currency, billingPeriod, billCycleDay, description, totalOrdering, type, tz, null, false);
    } catch (final CatalogApiException e) {
        Assert.fail("", e);
    }
    throw new IllegalStateException();
}
Also used : BillingPeriod(org.killbill.billing.catalog.api.BillingPeriod) InternationalPrice(org.killbill.billing.catalog.api.InternationalPrice) MockPlan(org.killbill.billing.catalog.MockPlan) Plan(org.killbill.billing.catalog.api.Plan) DateTimeZone(org.joda.time.DateTimeZone) BigDecimal(java.math.BigDecimal) Recurring(org.killbill.billing.catalog.api.Recurring) MockPlan(org.killbill.billing.catalog.MockPlan) Currency(org.killbill.billing.catalog.api.Currency) CatalogApiException(org.killbill.billing.catalog.api.CatalogApiException) PlanPhase(org.killbill.billing.catalog.api.PlanPhase)

Example 58 with CatalogApiException

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

the class OverriddenPlanCacheLoader method load.

@Override
public Object load(final Object key, final Object argument) {
    checkCacheLoaderStatus();
    if (!(key instanceof String)) {
        throw new IllegalArgumentException("Unexpected key type of " + key.getClass().getName());
    }
    if (!(argument instanceof CacheLoaderArgument)) {
        throw new IllegalArgumentException("Unexpected argument type of " + argument.getClass().getName());
    }
    final CacheLoaderArgument cacheLoaderArgument = (CacheLoaderArgument) argument;
    if (cacheLoaderArgument.getArgs() == null || cacheLoaderArgument.getArgs().length != 2) {
        throw new IllegalArgumentException("Invalid arguments for overridden plans");
    }
    if (!(cacheLoaderArgument.getArgs()[0] instanceof LoaderCallback)) {
        throw new IllegalArgumentException("Invalid arguments for overridden plans: missing loaderCallback from argument");
    }
    if (!(cacheLoaderArgument.getArgs()[1] instanceof StaticCatalog)) {
        throw new IllegalArgumentException("Invalid arguments for overridden plans: missing catalog from argument");
    }
    final String planName = (String) key;
    final LoaderCallback callback = (LoaderCallback) cacheLoaderArgument.getArgs()[0];
    final StaticCatalog catalog = (StaticCatalog) cacheLoaderArgument.getArgs()[1];
    final InternalTenantContext internalTenantContext = ((CacheLoaderArgument) argument).getInternalTenantContext();
    try {
        log.info("Loading overridden plan {} for tenant {}", planName, internalTenantContext.getTenantRecordId());
        return callback.loadPlan(planName, catalog, internalTenantContext);
    } catch (final CatalogApiException e) {
        throw new IllegalStateException(String.format("Failed to load overridden plan for tenant %s : %s", planName, internalTenantContext.getTenantRecordId()), e);
    }
}
Also used : InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) CatalogApiException(org.killbill.billing.catalog.api.CatalogApiException) StaticCatalog(org.killbill.billing.catalog.api.StaticCatalog)

Example 59 with CatalogApiException

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

the class DefaultEntitlement method changePlanWithDate.

@Override
public Entitlement changePlanWithDate(final PlanSpecifier spec, final List<PlanPhasePriceOverride> overrides, @Nullable final LocalDate effectiveDate, final Iterable<PluginProperty> properties, final CallContext callContext) throws EntitlementApiException {
    logChangePlan(log, this, spec, overrides, effectiveDate, null);
    checkForPermissions(Permission.ENTITLEMENT_CAN_CHANGE_PLAN, callContext);
    // Get the latest state from disk
    refresh(callContext);
    final BaseEntitlementWithAddOnsSpecifier baseEntitlementWithAddOnsSpecifier = new DefaultBaseEntitlementWithAddOnsSpecifier(getBundleId(), getExternalKey(), null, effectiveDate, effectiveDate, false);
    final List<BaseEntitlementWithAddOnsSpecifier> baseEntitlementWithAddOnsSpecifierList = new ArrayList<BaseEntitlementWithAddOnsSpecifier>();
    baseEntitlementWithAddOnsSpecifierList.add(baseEntitlementWithAddOnsSpecifier);
    final EntitlementContext pluginContext = new DefaultEntitlementContext(OperationType.CHANGE_PLAN, getAccountId(), null, baseEntitlementWithAddOnsSpecifierList, null, properties, callContext);
    final WithEntitlementPlugin<Entitlement> changePlanWithPlugin = new WithEntitlementPlugin<Entitlement>() {

        @Override
        public Entitlement doCall(final EntitlementApi entitlementApi, final EntitlementContext updatedPluginContext) throws EntitlementApiException {
            if (!eventsStream.isEntitlementActive()) {
                throw new EntitlementApiException(ErrorCode.SUB_CHANGE_NON_ACTIVE, getId(), getState());
            }
            final InternalCallContext context = internalCallContextFactory.createInternalCallContext(getAccountId(), callContext);
            final DateTime effectiveChangeDate = dateHelper.fromLocalDateAndReferenceTime(updatedPluginContext.getBaseEntitlementWithAddOnsSpecifiers().iterator().next().getBillingEffectiveDate(), context);
            final DateTime resultingEffectiveDate;
            try {
                resultingEffectiveDate = subscriptionInternalApi.getDryRunChangePlanEffectiveDate(getSubscriptionBase(), spec, effectiveChangeDate, null, overrides, context);
            } catch (final SubscriptionBaseApiException e) {
                throw new EntitlementApiException(e, e.getCode(), e.getMessage());
            } catch (final CatalogApiException e) {
                throw new EntitlementApiException(e, e.getCode(), e.getMessage());
            }
            try {
                checker.checkBlockedChange(getSubscriptionBase(), resultingEffectiveDate, context);
            } catch (final BlockingApiException e) {
                throw new EntitlementApiException(e, e.getCode(), e.getMessage());
            }
            try {
                getSubscriptionBase().changePlanWithDate(spec, overrides, resultingEffectiveDate, callContext);
            } catch (final SubscriptionBaseApiException e) {
                throw new EntitlementApiException(e);
            }
            final Collection<NotificationEvent> notificationEvents = new ArrayList<NotificationEvent>();
            final Iterable<BlockingState> addOnsBlockingStates = computeAddOnBlockingStates(resultingEffectiveDate, notificationEvents, callContext, context);
            // Record the new state first, then insert the notifications to avoid race conditions
            setBlockingStates(addOnsBlockingStates, context);
            for (final NotificationEvent notificationEvent : notificationEvents) {
                recordFutureNotification(resultingEffectiveDate, notificationEvent, context);
            }
            return entitlementApi.getEntitlementForId(getId(), callContext);
        }
    };
    return pluginExecution.executeWithPlugin(changePlanWithPlugin, pluginContext);
}
Also used : WithEntitlementPlugin(org.killbill.billing.entitlement.api.EntitlementPluginExecution.WithEntitlementPlugin) ArrayList(java.util.ArrayList) NotificationEvent(org.killbill.notificationq.api.NotificationEvent) InternalCallContext(org.killbill.billing.callcontext.InternalCallContext) DefaultBlockingState(org.killbill.billing.junction.DefaultBlockingState) DateTime(org.joda.time.DateTime) CatalogApiException(org.killbill.billing.catalog.api.CatalogApiException) EntitlementLoggingHelper.logCancelEntitlement(org.killbill.billing.entitlement.logging.EntitlementLoggingHelper.logCancelEntitlement) EntitlementLoggingHelper.logUncancelEntitlement(org.killbill.billing.entitlement.logging.EntitlementLoggingHelper.logUncancelEntitlement) EntitlementContext(org.killbill.billing.entitlement.plugin.api.EntitlementContext) SubscriptionBaseApiException(org.killbill.billing.subscription.api.user.SubscriptionBaseApiException) PlanPhasePriceOverride(org.killbill.billing.catalog.api.PlanPhasePriceOverride)

Example 60 with CatalogApiException

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

the class DefaultEntitlement method changePlanOverrideBillingPolicy.

@Override
public Entitlement changePlanOverrideBillingPolicy(final PlanSpecifier spec, final List<PlanPhasePriceOverride> overrides, final LocalDate entitlementEffectiveDate, final BillingActionPolicy actionPolicy, final Iterable<PluginProperty> properties, final CallContext callContext) throws EntitlementApiException {
    logChangePlan(log, this, spec, overrides, entitlementEffectiveDate, actionPolicy);
    checkForPermissions(Permission.ENTITLEMENT_CAN_CHANGE_PLAN, callContext);
    // Get the latest state from disk
    refresh(callContext);
    final BaseEntitlementWithAddOnsSpecifier baseEntitlementWithAddOnsSpecifier = new DefaultBaseEntitlementWithAddOnsSpecifier(getBundleId(), getExternalKey(), null, entitlementEffectiveDate, null, false);
    final List<BaseEntitlementWithAddOnsSpecifier> baseEntitlementWithAddOnsSpecifierList = new ArrayList<BaseEntitlementWithAddOnsSpecifier>();
    baseEntitlementWithAddOnsSpecifierList.add(baseEntitlementWithAddOnsSpecifier);
    final EntitlementContext pluginContext = new DefaultEntitlementContext(OperationType.CHANGE_PLAN, getAccountId(), null, baseEntitlementWithAddOnsSpecifierList, actionPolicy, properties, callContext);
    final WithEntitlementPlugin<Entitlement> changePlanWithPlugin = new WithEntitlementPlugin<Entitlement>() {

        @Override
        public Entitlement doCall(final EntitlementApi entitlementApi, final EntitlementContext updatedPluginContext) throws EntitlementApiException {
            if (!eventsStream.isEntitlementActive()) {
                throw new EntitlementApiException(ErrorCode.SUB_CHANGE_NON_ACTIVE, getId(), getState());
            }
            final InternalCallContext context = internalCallContextFactory.createInternalCallContext(getAccountId(), callContext);
            final DateTime effectiveChangeDate;
            try {
                effectiveChangeDate = subscriptionInternalApi.getDryRunChangePlanEffectiveDate(getSubscriptionBase(), spec, null, actionPolicy, overrides, context);
            } catch (final SubscriptionBaseApiException e) {
                throw new EntitlementApiException(e, e.getCode(), e.getMessage());
            } catch (final CatalogApiException e) {
                throw new EntitlementApiException(e, e.getCode(), e.getMessage());
            }
            try {
                checker.checkBlockedChange(getSubscriptionBase(), effectiveChangeDate, context);
            } catch (final BlockingApiException e) {
                throw new EntitlementApiException(e, e.getCode(), e.getMessage());
            }
            try {
                getSubscriptionBase().changePlanWithPolicy(spec, overrides, actionPolicy, callContext);
            } catch (final SubscriptionBaseApiException e) {
                throw new EntitlementApiException(e);
            }
            final Collection<NotificationEvent> notificationEvents = new ArrayList<NotificationEvent>();
            final Iterable<BlockingState> addOnsBlockingStates = computeAddOnBlockingStates(effectiveChangeDate, notificationEvents, callContext, context);
            // Record the new state first, then insert the notifications to avoid race conditions
            setBlockingStates(addOnsBlockingStates, context);
            for (final NotificationEvent notificationEvent : notificationEvents) {
                recordFutureNotification(effectiveChangeDate, notificationEvent, context);
            }
            return entitlementApi.getEntitlementForId(getId(), callContext);
        }
    };
    return pluginExecution.executeWithPlugin(changePlanWithPlugin, pluginContext);
}
Also used : WithEntitlementPlugin(org.killbill.billing.entitlement.api.EntitlementPluginExecution.WithEntitlementPlugin) ArrayList(java.util.ArrayList) NotificationEvent(org.killbill.notificationq.api.NotificationEvent) InternalCallContext(org.killbill.billing.callcontext.InternalCallContext) DefaultBlockingState(org.killbill.billing.junction.DefaultBlockingState) DateTime(org.joda.time.DateTime) CatalogApiException(org.killbill.billing.catalog.api.CatalogApiException) EntitlementLoggingHelper.logCancelEntitlement(org.killbill.billing.entitlement.logging.EntitlementLoggingHelper.logCancelEntitlement) EntitlementLoggingHelper.logUncancelEntitlement(org.killbill.billing.entitlement.logging.EntitlementLoggingHelper.logUncancelEntitlement) EntitlementContext(org.killbill.billing.entitlement.plugin.api.EntitlementContext) SubscriptionBaseApiException(org.killbill.billing.subscription.api.user.SubscriptionBaseApiException) PlanPhasePriceOverride(org.killbill.billing.catalog.api.PlanPhasePriceOverride)

Aggregations

CatalogApiException (org.killbill.billing.catalog.api.CatalogApiException)106 DateTime (org.joda.time.DateTime)36 SubscriptionBaseApiException (org.killbill.billing.subscription.api.user.SubscriptionBaseApiException)28 InternalCallContext (org.killbill.billing.callcontext.InternalCallContext)22 ArrayList (java.util.ArrayList)21 SubscriptionCatalog (org.killbill.billing.subscription.catalog.SubscriptionCatalog)20 Plan (org.killbill.billing.catalog.api.Plan)19 PlanPhasePriceOverride (org.killbill.billing.catalog.api.PlanPhasePriceOverride)19 DefaultSubscriptionBase (org.killbill.billing.subscription.api.user.DefaultSubscriptionBase)17 UUID (java.util.UUID)14 LinkedList (java.util.LinkedList)13 InternalTenantContext (org.killbill.billing.callcontext.InternalTenantContext)13 StaticCatalog (org.killbill.billing.catalog.api.StaticCatalog)13 HashMap (java.util.HashMap)10 PlanPhaseSpecifier (org.killbill.billing.catalog.api.PlanPhaseSpecifier)10 ImmutableList (com.google.common.collect.ImmutableList)9 List (java.util.List)9 SubscriptionBase (org.killbill.billing.subscription.api.SubscriptionBase)9 SubscriptionBaseEvent (org.killbill.billing.subscription.events.SubscriptionBaseEvent)9 Test (org.testng.annotations.Test)9