Search in sources :

Example 6 with SubscriptionBundleModelDao

use of org.killbill.billing.subscription.engine.dao.model.SubscriptionBundleModelDao in project killbill by killbill.

the class DefaultSubscriptionDao method createSubscriptionBundle.

@Override
public SubscriptionBaseBundle createSubscriptionBundle(final DefaultSubscriptionBaseBundle bundle, final SubscriptionCatalog catalog, final boolean renameCancelledBundleIfExist, final InternalCallContext context) throws SubscriptionBaseApiException {
    return transactionalSqlDao.execute(false, SubscriptionBaseApiException.class, new EntitySqlDaoTransactionWrapper<SubscriptionBaseBundle>() {

        // 
        // 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)
        // 
        private SubscriptionBaseBundle findExistingUnusedBundleForExternalKeyAndAccount(final List<SubscriptionBundleModelDao> existingBundles, final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) {
            final SubscriptionBundleModelDao existingBundleForAccount = Iterables.tryFind(existingBundles, new Predicate<SubscriptionBundleModelDao>() {

                @Override
                public boolean apply(final SubscriptionBundleModelDao input) {
                    return input.getAccountId().equals(bundle.getAccountId()) && // We look for strict equality ignoring tsf items with keys 'kbtsf-343453:'
                    bundle.getExternalKey().equals(input.getExternalKey());
                }
            }).orNull();
            // If Bundle already exists, and there is 0 Subscription associated with this bundle, we reuse
            if (existingBundleForAccount != null) {
                final List<SubscriptionModelDao> accountSubscriptions = entitySqlDaoWrapperFactory.become(SubscriptionSqlDao.class).getByAccountRecordId(context);
                if (accountSubscriptions == null || !Iterables.any(accountSubscriptions, new Predicate<SubscriptionModelDao>() {

                    @Override
                    public boolean apply(final SubscriptionModelDao input) {
                        return input.getBundleId().equals(existingBundleForAccount.getId());
                    }
                })) {
                    return SubscriptionBundleModelDao.toSubscriptionBundle(existingBundleForAccount);
                }
            }
            return null;
        }

        @Override
        public SubscriptionBaseBundle inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception {
            final List<SubscriptionBundleModelDao> existingBundles = bundle.getExternalKey() == null ? ImmutableList.<SubscriptionBundleModelDao>of() : entitySqlDaoWrapperFactory.become(BundleSqlDao.class).getBundlesForLikeKey(bundle.getExternalKey(), context);
            final SubscriptionBaseBundle unusedBundle = findExistingUnusedBundleForExternalKeyAndAccount(existingBundles, entitySqlDaoWrapperFactory);
            if (unusedBundle != null) {
                log.info("Found unused bundle for externalKey='{}': bundleId='{}'", bundle.getExternalKey(), unusedBundle.getId());
                return unusedBundle;
            }
            final BundleSqlDao bundleSqlDao = entitySqlDaoWrapperFactory.become(BundleSqlDao.class);
            for (SubscriptionBundleModelDao cur : existingBundles) {
                final List<SubscriptionModelDao> subscriptions = entitySqlDaoWrapperFactory.become(SubscriptionSqlDao.class).getSubscriptionsFromBundleId(cur.getId().toString(), context);
                final Iterable<SubscriptionModelDao> filtered = subscriptions != null ? Iterables.filter(subscriptions, new Predicate<SubscriptionModelDao>() {

                    @Override
                    public boolean apply(final SubscriptionModelDao input) {
                        return input.getCategory() != ProductCategory.ADD_ON;
                    }
                }) : ImmutableList.<SubscriptionModelDao>of();
                for (SubscriptionModelDao f : filtered) {
                    try {
                        final SubscriptionBase s = buildSubscription(SubscriptionModelDao.toSubscription(f, cur.getExternalKey()), catalog, context);
                        if (s.getState() != EntitlementState.CANCELLED) {
                            throw new SubscriptionBaseApiException(ErrorCode.SUB_CREATE_ACTIVE_BUNDLE_KEY_EXISTS, bundle.getExternalKey());
                        } else if (renameCancelledBundleIfExist) {
                            log.info("Renaming bundles with externalKey='{}', prefix='cncl'", bundle.getExternalKey());
                            renameBundleExternalKey(bundleSqlDao, bundle.getExternalKey(), "cncl", context);
                        }
                    /* else {
                                Code will throw SQLIntegrityConstraintViolationException because of unique constraint on externalKey; might be worth having an ErrorCode just for that
                            } */
                    } catch (CatalogApiException e) {
                        throw new SubscriptionBaseApiException(e);
                    }
                }
            }
            final SubscriptionBundleModelDao model = new SubscriptionBundleModelDao(bundle);
            // Preserve Original created date
            if (!existingBundles.isEmpty()) {
                model.setOriginalCreatedDate(existingBundles.get(0).getCreatedDate());
            }
            final SubscriptionBundleModelDao result = createAndRefresh(bundleSqlDao, model, context);
            return SubscriptionBundleModelDao.toSubscriptionBundle(result);
        }
    });
}
Also used : SubscriptionModelDao(org.killbill.billing.subscription.engine.dao.model.SubscriptionModelDao) SubscriptionBundleModelDao(org.killbill.billing.subscription.engine.dao.model.SubscriptionBundleModelDao) CatalogApiException(org.killbill.billing.catalog.api.CatalogApiException) SubscriptionApiException(org.killbill.billing.entitlement.api.SubscriptionApiException) IOException(java.io.IOException) SubscriptionBaseApiException(org.killbill.billing.subscription.api.user.SubscriptionBaseApiException) EventBusException(org.killbill.bus.api.PersistentBus.EventBusException) EntityPersistenceException(org.killbill.billing.entity.EntityPersistenceException) Predicate(com.google.common.base.Predicate) SubscriptionBase(org.killbill.billing.subscription.api.SubscriptionBase) DefaultSubscriptionBase(org.killbill.billing.subscription.api.user.DefaultSubscriptionBase) CatalogApiException(org.killbill.billing.catalog.api.CatalogApiException) SubscriptionBaseBundle(org.killbill.billing.subscription.api.user.SubscriptionBaseBundle) DefaultSubscriptionBaseBundle(org.killbill.billing.subscription.api.user.DefaultSubscriptionBaseBundle) EntitySqlDaoWrapperFactory(org.killbill.billing.util.entity.dao.EntitySqlDaoWrapperFactory) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) LinkedList(java.util.LinkedList) SubscriptionBaseApiException(org.killbill.billing.subscription.api.user.SubscriptionBaseApiException)

Example 7 with SubscriptionBundleModelDao

use of org.killbill.billing.subscription.engine.dao.model.SubscriptionBundleModelDao in project killbill by killbill.

the class DefaultSubscriptionDao method getSubscriptionsFromAccountId.

public Map<UUID, List<DefaultSubscriptionBase>> getSubscriptionsFromAccountId(@Nullable final LocalDate cutoffDt, final InternalTenantContext context) {
    final List<DefaultSubscriptionBase> allSubscriptions = transactionalSqlDao.execute(true, new EntitySqlDaoTransactionWrapper<List<DefaultSubscriptionBase>>() {

        @Override
        public List<DefaultSubscriptionBase> inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception {
            final SubscriptionSqlDao subscriptionSqlDao = entitySqlDaoWrapperFactory.become(SubscriptionSqlDao.class);
            final List<SubscriptionModelDao> subscriptionModels = cutoffDt == null ? subscriptionSqlDao.getByAccountRecordId(context) : subscriptionSqlDao.getActiveByAccountRecordId(cutoffDt.toDate(), context);
            // We avoid pulling the bundles when a cutoffDt is specified, as those are not really used
            final List<SubscriptionBundleModelDao> bundleModels = cutoffDt == null ? entitySqlDaoWrapperFactory.become(BundleSqlDao.class).getByAccountRecordId(context) : ImmutableList.of();
            return new ArrayList<DefaultSubscriptionBase>(Collections2.transform(subscriptionModels, new Function<SubscriptionModelDao, DefaultSubscriptionBase>() {

                @Override
                public DefaultSubscriptionBase apply(final SubscriptionModelDao input) {
                    final SubscriptionBundleModelDao bundleModel = Iterables.tryFind(bundleModels, new Predicate<SubscriptionBundleModelDao>() {

                        @Override
                        public boolean apply(final SubscriptionBundleModelDao bundleInput) {
                            return bundleInput.getId().equals(input.getBundleId());
                        }
                    }).orNull();
                    final String bundleExternalKey = bundleModel != null ? bundleModel.getExternalKey() : null;
                    return SubscriptionModelDao.toSubscription(input, bundleExternalKey);
                }
            }));
        }
    });
    final Map<UUID, List<DefaultSubscriptionBase>> result = new HashMap<UUID, List<DefaultSubscriptionBase>>();
    for (final DefaultSubscriptionBase subscriptionBase : allSubscriptions) {
        if (result.get(subscriptionBase.getBundleId()) == null) {
            result.put(subscriptionBase.getBundleId(), new LinkedList<DefaultSubscriptionBase>());
        }
        result.get(subscriptionBase.getBundleId()).add(subscriptionBase);
    }
    return result;
}
Also used : SubscriptionModelDao(org.killbill.billing.subscription.engine.dao.model.SubscriptionModelDao) HashMap(java.util.HashMap) SubscriptionBundleModelDao(org.killbill.billing.subscription.engine.dao.model.SubscriptionBundleModelDao) CatalogApiException(org.killbill.billing.catalog.api.CatalogApiException) SubscriptionApiException(org.killbill.billing.entitlement.api.SubscriptionApiException) IOException(java.io.IOException) SubscriptionBaseApiException(org.killbill.billing.subscription.api.user.SubscriptionBaseApiException) EventBusException(org.killbill.bus.api.PersistentBus.EventBusException) EntityPersistenceException(org.killbill.billing.entity.EntityPersistenceException) EntitySqlDaoWrapperFactory(org.killbill.billing.util.entity.dao.EntitySqlDaoWrapperFactory) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) LinkedList(java.util.LinkedList) DefaultSubscriptionBase(org.killbill.billing.subscription.api.user.DefaultSubscriptionBase) UUID(java.util.UUID)

Example 8 with SubscriptionBundleModelDao

use of org.killbill.billing.subscription.engine.dao.model.SubscriptionBundleModelDao in project killbill by killbill.

the class TestSubscriptionModelDao method testBundleExternalKeyPattern2.

@Test(groups = "fast")
public void testBundleExternalKeyPattern2() throws Exception {
    final SubscriptionBundleModelDao b = new SubscriptionBundleModelDao();
    b.setExternalKey("kbtsf-343453:1235");
    assertEquals(SubscriptionBundleModelDao.toSubscriptionBundle(b).getExternalKey(), "1235");
}
Also used : SubscriptionBundleModelDao(org.killbill.billing.subscription.engine.dao.model.SubscriptionBundleModelDao) Test(org.testng.annotations.Test)

Example 9 with SubscriptionBundleModelDao

use of org.killbill.billing.subscription.engine.dao.model.SubscriptionBundleModelDao in project killbill by killbill.

the class TestSubscriptionModelDao method testBundleExternalKeyPattern1.

@Test(groups = "fast")
public void testBundleExternalKeyPattern1() throws Exception {
    final SubscriptionBundleModelDao b = new SubscriptionBundleModelDao();
    b.setExternalKey("1235");
    assertEquals(SubscriptionBundleModelDao.toSubscriptionBundle(b).getExternalKey(), "1235");
}
Also used : SubscriptionBundleModelDao(org.killbill.billing.subscription.engine.dao.model.SubscriptionBundleModelDao) Test(org.testng.annotations.Test)

Aggregations

SubscriptionBundleModelDao (org.killbill.billing.subscription.engine.dao.model.SubscriptionBundleModelDao)9 DefaultSubscriptionBase (org.killbill.billing.subscription.api.user.DefaultSubscriptionBase)5 SubscriptionModelDao (org.killbill.billing.subscription.engine.dao.model.SubscriptionModelDao)5 LinkedList (java.util.LinkedList)4 Test (org.testng.annotations.Test)4 ImmutableList (com.google.common.collect.ImmutableList)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 CatalogApiException (org.killbill.billing.catalog.api.CatalogApiException)3 SubscriptionApiException (org.killbill.billing.entitlement.api.SubscriptionApiException)3 EntityPersistenceException (org.killbill.billing.entity.EntityPersistenceException)3 DefaultSubscriptionBaseBundle (org.killbill.billing.subscription.api.user.DefaultSubscriptionBaseBundle)3 EntitySqlDaoWrapperFactory (org.killbill.billing.util.entity.dao.EntitySqlDaoWrapperFactory)3 EventBusException (org.killbill.bus.api.PersistentBus.EventBusException)3 Predicate (com.google.common.base.Predicate)2 HashMap (java.util.HashMap)2 UUID (java.util.UUID)2 SubscriptionBase (org.killbill.billing.subscription.api.SubscriptionBase)2 SubscriptionBaseApiException (org.killbill.billing.subscription.api.user.SubscriptionBaseApiException)2