use of org.killbill.billing.util.entity.dao.EntitySqlDaoWrapperFactory 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);
}
});
}
use of org.killbill.billing.util.entity.dao.EntitySqlDaoWrapperFactory 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;
}
use of org.killbill.billing.util.entity.dao.EntitySqlDaoWrapperFactory in project killbill by killbill.
the class TestInvoiceTrackingSqlDao method testInvalidation.
@Test(groups = "slow")
public void testInvalidation() {
LocalDate startRange = new LocalDate(2019, 1, 1);
LocalDate endRange = new LocalDate(2019, 1, 31);
final UUID invoiceId1 = UUID.randomUUID();
final UUID invoiceId2 = UUID.randomUUID();
final UUID subscriptionId = UUID.randomUUID();
// invoiceId1
final InvoiceTrackingModelDao input1 = new InvoiceTrackingModelDao(UUID.randomUUID(), clock.getUTCNow(), "trackingId1", invoiceId1, subscriptionId, "unit", new LocalDate(2019, 1, 1));
final InvoiceTrackingModelDao input2 = new InvoiceTrackingModelDao(UUID.randomUUID(), clock.getUTCNow(), "trackingId2", invoiceId1, subscriptionId, "unit", new LocalDate(2019, 1, 2));
final InvoiceTrackingModelDao input3 = new InvoiceTrackingModelDao(UUID.randomUUID(), clock.getUTCNow(), "trackingId3", invoiceId1, subscriptionId, "unit", new LocalDate(2019, 1, 3));
// invoiceId2
final InvoiceTrackingModelDao input4 = new InvoiceTrackingModelDao(UUID.randomUUID(), clock.getUTCNow(), "trackingId4", invoiceId2, subscriptionId, "unit", new LocalDate(2019, 1, 5));
final List<InvoiceTrackingModelDao> inputs = new ArrayList<>();
inputs.add(input1);
inputs.add(input2);
inputs.add(input3);
inputs.add(input4);
// Create state
transactionalSqlDao.execute(false, new EntitySqlDaoTransactionWrapper<Void>() {
@Override
public Void inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception {
final InvoiceTrackingSqlDao dao = entitySqlDaoWrapperFactory.become(InvoiceTrackingSqlDao.class);
dao.create(inputs, internalCallContext);
return null;
}
});
// Verify audit logs from existing state
final List<InvoiceTrackingModelDao> initialTrackingIdsByRange = transactionalSqlDao.execute(false, new EntitySqlDaoTransactionWrapper<List<InvoiceTrackingModelDao>>() {
@Override
public List<InvoiceTrackingModelDao> inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception {
final InvoiceTrackingSqlDao dao = entitySqlDaoWrapperFactory.become(InvoiceTrackingSqlDao.class);
final List<InvoiceTrackingModelDao> result = dao.getTrackingsByDateRange(startRange.toDate(), endRange.toDate(), internalCallContext);
Assert.assertEquals(result.size(), 4);
final List<EntityHistoryModelDao> entityHistoryModelDaos = new ArrayList<>();
final List<AuditLogModelDao> auditLogsPostCreate = new ArrayList<>();
for (int i = 0; i < 4; i++) {
List<AuditLogModelDao> tmp1 = dao.getAuditLogsViaHistoryForTargetRecordId(TableName.INVOICE_TRACKING_ID_HISTORY.name(), TableName.INVOICE_TRACKING_ID_HISTORY.getTableName().toLowerCase(), result.get(i).getRecordId(), internalCallContext);
auditLogsPostCreate.addAll(tmp1);
final List<EntityHistoryModelDao<InvoiceTrackingModelDao, Entity>> tmp2 = dao.getHistoryForTargetRecordId(true, result.get(i).getRecordId(), internalCallContext);
entityHistoryModelDaos.addAll(tmp2);
}
Assert.assertEquals(auditLogsPostCreate.size(), 4);
Assert.assertEquals(entityHistoryModelDaos.size(), 4);
for (int i = 0; i < 4; i++) {
Assert.assertEquals(auditLogsPostCreate.get(i).getChangeType(), ChangeType.INSERT);
// From the audit log entry, lookup the matching history entry
final int curIdx = i;
final EntityHistoryModelDao history = Iterables.find(entityHistoryModelDaos, new Predicate<EntityHistoryModelDao>() {
@Override
public boolean apply(final EntityHistoryModelDao input) {
return Objects.equals(input.getHistoryRecordId(), auditLogsPostCreate.get(curIdx).getTargetRecordId());
}
});
Assert.assertEquals(auditLogsPostCreate.get(i).getTargetRecordId(), history.getHistoryRecordId());
}
return result;
}
});
clock.addDays(1);
// Create state
transactionalSqlDao.execute(false, new EntitySqlDaoTransactionWrapper<Void>() {
@Override
public Void inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception {
final InvoiceTrackingSqlDao dao = entitySqlDaoWrapperFactory.become(InvoiceTrackingSqlDao.class);
final InternalCallContext updatedContext = new InternalCallContext(internalCallContext.getTenantRecordId(), internalCallContext.getAccountRecordId(), internalCallContext.getFixedOffsetTimeZone(), clock.getUTCNow(), internalCallContext.getUserToken(), "invalidation-user", internalCallContext.getCallOrigin(), internalCallContext.getContextUserType(), internalCallContext.getReasonCode(), internalCallContext.getComments(), internalCallContext.getCreatedDate(), clock.getUTCNow());
dao.deactivateByIds(ImmutableList.<String>of(input1.getId().toString(), input2.getId().toString(), input3.getId().toString()), updatedContext);
return null;
}
});
// Verify audit logs from existing state
transactionalSqlDao.execute(false, new EntitySqlDaoTransactionWrapper<Void>() {
@Override
public Void inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception {
final InvoiceTrackingSqlDao dao = entitySqlDaoWrapperFactory.become(InvoiceTrackingSqlDao.class);
final List<InvoiceTrackingModelDao> result2 = dao.getTrackingsByDateRange(startRange.toDate(), endRange.toDate(), internalCallContext);
Assert.assertEquals(result2.size(), 1);
final List<AuditLogModelDao> auditLogsPostDelete = new ArrayList<>();
for (int i = 0; i < 4; i++) {
List<AuditLogModelDao> tmp = dao.getAuditLogsViaHistoryForTargetRecordId(TableName.INVOICE_TRACKING_ID_HISTORY.name(), TableName.INVOICE_TRACKING_ID_HISTORY.getTableName().toLowerCase(), initialTrackingIdsByRange.get(i).getRecordId(), internalCallContext);
auditLogsPostDelete.addAll(tmp);
}
Assert.assertEquals(auditLogsPostDelete.size(), 7);
// First 3 records will show an INSERT & DELETE
for (int i = 0; i < 3; i++) {
Assert.assertEquals(auditLogsPostDelete.get(2 * i).getChangeType(), ChangeType.INSERT);
Assert.assertEquals(auditLogsPostDelete.get(2 * i + 1).getChangeType(), ChangeType.DELETE);
}
// Last record will only show an INSERT
Assert.assertEquals(auditLogsPostDelete.get(6).getChangeType(), ChangeType.INSERT);
return null;
}
});
}
use of org.killbill.billing.util.entity.dao.EntitySqlDaoWrapperFactory in project killbill by killbill.
the class TestInvoiceTrackingSqlDao method testBasicTrackingIds.
@Test(groups = "slow")
public void testBasicTrackingIds() {
LocalDate startRange = new LocalDate(2018, 8, 1);
LocalDate endRange = new LocalDate(2018, 11, 23);
final UUID invoiceId1 = UUID.randomUUID();
final UUID invoiceId2 = UUID.randomUUID();
final UUID subscriptionId = UUID.randomUUID();
// Before desired range
final InvoiceTrackingModelDao input0 = new InvoiceTrackingModelDao(UUID.randomUUID(), clock.getUTCNow(), "trackingId0", invoiceId1, subscriptionId, "unit", startRange.minusDays(1));
final InvoiceTrackingModelDao input1 = new InvoiceTrackingModelDao(UUID.randomUUID(), clock.getUTCNow(), "trackingId1", invoiceId1, subscriptionId, "unit", startRange);
final InvoiceTrackingModelDao input2 = new InvoiceTrackingModelDao(UUID.randomUUID(), clock.getUTCNow(), "trackingId2", invoiceId1, subscriptionId, "unit", new LocalDate(2018, 8, 5));
final InvoiceTrackingModelDao input3 = new InvoiceTrackingModelDao(UUID.randomUUID(), clock.getUTCNow(), "trackingId3", invoiceId2, subscriptionId, "unit", new LocalDate(2018, 9, 1));
// After desired range
final InvoiceTrackingModelDao input4 = new InvoiceTrackingModelDao(UUID.randomUUID(), clock.getUTCNow(), "trackingId4", invoiceId1, subscriptionId, "unit", endRange);
final List<InvoiceTrackingModelDao> inputs = new ArrayList<>();
inputs.add(input0);
inputs.add(input1);
inputs.add(input2);
inputs.add(input3);
inputs.add(input4);
transactionalSqlDao.execute(false, new EntitySqlDaoTransactionWrapper<Void>() {
@Override
public Void inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception {
final InvoiceTrackingSqlDao dao = entitySqlDaoWrapperFactory.become(InvoiceTrackingSqlDao.class);
dao.create(inputs, internalCallContext);
final List<InvoiceTrackingModelDao> result = dao.getTrackingsByDateRange(startRange.toDate(), endRange.toDate(), internalCallContext);
Assert.assertEquals(result.size(), 3);
Assert.assertEquals(result.get(0).getTrackingId(), "trackingId1");
Assert.assertEquals(result.get(0).getInvoiceId(), invoiceId1);
Assert.assertEquals(result.get(0).getRecordDate(), startRange);
Assert.assertEquals(result.get(0).getSubscriptionId(), subscriptionId);
Assert.assertEquals(result.get(1).getTrackingId(), "trackingId2");
Assert.assertEquals(result.get(1).getInvoiceId(), invoiceId1);
Assert.assertEquals(result.get(1).getRecordDate(), new LocalDate(2018, 8, 5));
Assert.assertEquals(result.get(1).getSubscriptionId(), subscriptionId);
Assert.assertEquals(result.get(2).getTrackingId(), "trackingId3");
Assert.assertEquals(result.get(2).getInvoiceId(), invoiceId2);
Assert.assertEquals(result.get(2).getRecordDate(), new LocalDate(2018, 9, 1));
Assert.assertEquals(result.get(2).getSubscriptionId(), subscriptionId);
return null;
}
});
transactionalSqlDao.execute(false, new EntitySqlDaoTransactionWrapper<Void>() {
@Override
public Void inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception {
final InvoiceTrackingSqlDao dao = entitySqlDaoWrapperFactory.become(InvoiceTrackingSqlDao.class);
final List<InvoiceTrackingModelDao> result = dao.getTrackingsForInvoices(ImmutableList.of(invoiceId1.toString(), invoiceId2.toString()), internalCallContext);
Assert.assertEquals(result.size(), 5);
return null;
}
});
}
use of org.killbill.billing.util.entity.dao.EntitySqlDaoWrapperFactory in project killbill by killbill.
the class TestInvoiceBillingEventSqlDao method testBasic.
@Test(groups = "slow")
public void testBasic() {
final UUID invoiceId = UUID.randomUUID();
final int NB_BYTES = 100;
final byte[] data = new byte[NB_BYTES];
for (int i = 0; i < NB_BYTES; i++) {
data[i] = (byte) i;
}
final InvoiceBillingEventModelDao entry = new InvoiceBillingEventModelDao(invoiceId, data, new DateTime());
transactionalSqlDao.execute(false, new EntitySqlDaoTransactionWrapper<Void>() {
@Override
public Void inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception {
final InvoiceBillingEventSqlDao dao = entitySqlDaoWrapperFactory.become(InvoiceBillingEventSqlDao.class);
final InvoiceBillingEventModelDao result = (InvoiceBillingEventModelDao) dao.create(entry, internalCallContext);
Assert.assertEquals(result.getInvoiceId(), invoiceId);
Assert.assertEquals(result.getBillingEvents(), data);
return null;
}
});
}
Aggregations