killbill-memoizeit

server: add test for audit logs in the account timeline Signed-off-by:

8/11/2012 4:30:19 PM

Details

diff --git a/server/src/test/java/com/ning/billing/jaxrs/TestAccount.java b/server/src/test/java/com/ning/billing/jaxrs/TestAccount.java
index 7f6c232..c234411 100644
--- a/server/src/test/java/com/ning/billing/jaxrs/TestAccount.java
+++ b/server/src/test/java/com/ning/billing/jaxrs/TestAccount.java
@@ -16,34 +16,36 @@
 
 package com.ning.billing.jaxrs;
 
+import java.math.BigDecimal;
 import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.UUID;
 
+import javax.annotation.Nullable;
 import javax.ws.rs.core.Response.Status;
 
 import org.joda.time.DateTime;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 
-import com.ning.billing.catalog.api.BillingPeriod;
-import com.ning.billing.catalog.api.ProductCategory;
 import com.ning.billing.jaxrs.json.AccountJson;
 import com.ning.billing.jaxrs.json.AccountTimelineJson;
+import com.ning.billing.jaxrs.json.AuditLogJson;
 import com.ning.billing.jaxrs.json.BillCycleDayJson;
-import com.ning.billing.jaxrs.json.BundleJsonNoSubscriptions;
+import com.ning.billing.jaxrs.json.ChargebackJson;
+import com.ning.billing.jaxrs.json.CreditJson;
 import com.ning.billing.jaxrs.json.CustomFieldJson;
+import com.ning.billing.jaxrs.json.InvoiceJsonSimple;
 import com.ning.billing.jaxrs.json.PaymentJsonSimple;
+import com.ning.billing.jaxrs.json.PaymentJsonWithBundleKeys;
 import com.ning.billing.jaxrs.json.PaymentMethodJson;
 import com.ning.billing.jaxrs.json.RefundJson;
-import com.ning.billing.jaxrs.json.SubscriptionJsonNoEvents;
 import com.ning.billing.jaxrs.json.TagDefinitionJson;
 import com.ning.billing.jaxrs.json.TagJson;
 import com.ning.billing.jaxrs.resources.JaxrsResource;
+import com.ning.billing.util.ChangeType;
 import com.ning.http.client.Response;
 
 import com.fasterxml.jackson.core.type.TypeReference;
@@ -110,6 +112,100 @@ public class TestAccount extends TestJaxrsBase {
         Assert.assertEquals(timeline.getBundles().get(0).getSubscriptions().get(0).getEvents().size(), 2);
     }
 
+    @Test
+    public void testAccountTimelineWithAudits() throws Exception {
+        final DateTime startTime = clock.getUTCNow();
+        final AccountJson accountJson = createAccountWithPMBundleAndSubscriptionAndWaitForFirstInvoice();
+        final DateTime endTime = clock.getUTCNow();
+
+        // Add credit
+        final InvoiceJsonSimple invoice = getInvoicesForAccount(accountJson.getAccountId()).get(1);
+        final DateTime creditEffectiveDate = clock.getUTCNow();
+        final BigDecimal creditAmount = BigDecimal.ONE;
+        createCreditForInvoice(accountJson.getAccountId(), invoice.getInvoiceId(),
+                               creditAmount, clock.getUTCNow(), creditEffectiveDate);
+
+        // Add refund
+        final PaymentJsonSimple postedPayment = getPaymentsForAccount(accountJson.getAccountId()).get(0);
+        final BigDecimal refundAmount = BigDecimal.ONE;
+        createRefund(postedPayment.getPaymentId(), refundAmount);
+
+        // Add chargeback
+        final BigDecimal chargebackAmount = BigDecimal.ONE;
+        createChargeBack(postedPayment.getPaymentId(), chargebackAmount);
+
+        final AccountTimelineJson timeline = getAccountTimelineWithAudits(accountJson.getAccountId());
+
+        // Verify payments
+        Assert.assertEquals(timeline.getPayments().size(), 1);
+        final PaymentJsonWithBundleKeys paymentJson = timeline.getPayments().get(0);
+        final List<AuditLogJson> paymentAuditLogs = paymentJson.getAuditLogs();
+        Assert.assertEquals(paymentAuditLogs.size(), 2);
+        verifyAuditLog(paymentAuditLogs.get(0), ChangeType.INSERT, null, null, "PaymentRequestProcessor", startTime, endTime);
+        verifyAuditLog(paymentAuditLogs.get(1), ChangeType.UPDATE, null, null, "PaymentRequestProcessor", startTime, endTime);
+
+        // Verify refunds
+        Assert.assertEquals(paymentJson.getRefunds().size(), 1);
+        final RefundJson refundJson = paymentJson.getRefunds().get(0);
+        Assert.assertEquals(refundJson.getPaymentId(), paymentJson.getPaymentId());
+        Assert.assertEquals(refundJson.getRefundAmount().compareTo(refundAmount), 0);
+        final List<AuditLogJson> refundAuditLogs = refundJson.getAuditLogs();
+        Assert.assertEquals(refundAuditLogs.size(), 3);
+        verifyAuditLog(refundAuditLogs.get(0), ChangeType.INSERT, reason, comment, createdBy, startTime, endTime);
+        verifyAuditLog(refundAuditLogs.get(1), ChangeType.UPDATE, reason, comment, createdBy, startTime, endTime);
+        verifyAuditLog(refundAuditLogs.get(2), ChangeType.UPDATE, reason, comment, createdBy, startTime, endTime);
+
+        // Verify chargebacks
+        Assert.assertEquals(paymentJson.getChargebacks().size(), 1);
+        final ChargebackJson chargebackJson = paymentJson.getChargebacks().get(0);
+        Assert.assertEquals(chargebackJson.getPaymentId(), paymentJson.getPaymentId());
+        Assert.assertEquals(chargebackJson.getChargebackAmount().compareTo(chargebackAmount), 0);
+        final List<AuditLogJson> chargebackAuditLogs = chargebackJson.getAuditLogs();
+        Assert.assertEquals(chargebackAuditLogs.size(), 1);
+        verifyAuditLog(chargebackAuditLogs.get(0), ChangeType.INSERT, reason, comment, createdBy, startTime, endTime);
+
+        // Verify invoices
+        Assert.assertEquals(timeline.getInvoices().size(), 2);
+        final List<AuditLogJson> firstInvoiceAuditLogs = timeline.getInvoices().get(0).getAuditLogs();
+        Assert.assertEquals(firstInvoiceAuditLogs.size(), 1);
+        verifyAuditLog(firstInvoiceAuditLogs.get(0), ChangeType.INSERT, null, null, "Transition", startTime, endTime);
+        final List<AuditLogJson> secondInvoiceAuditLogs = timeline.getInvoices().get(1).getAuditLogs();
+        Assert.assertEquals(secondInvoiceAuditLogs.size(), 1);
+        verifyAuditLog(secondInvoiceAuditLogs.get(0), ChangeType.INSERT, null, null, "Transition", startTime, endTime);
+
+        // Verify credits
+        final List<CreditJson> credits = timeline.getInvoices().get(1).getCredits();
+        Assert.assertEquals(credits.size(), 1);
+        Assert.assertEquals(credits.get(0).getCreditAmount().compareTo(creditAmount.negate()), 0);
+        final List<AuditLogJson> creditAuditLogs = credits.get(0).getAuditLogs();
+        Assert.assertEquals(creditAuditLogs.size(), 1);
+        verifyAuditLog(creditAuditLogs.get(0), ChangeType.INSERT, reason, comment, createdBy, startTime, endTime);
+
+        // Verify bundles
+        Assert.assertEquals(timeline.getBundles().size(), 1);
+        Assert.assertEquals(timeline.getBundles().get(0).getSubscriptions().size(), 1);
+        Assert.assertEquals(timeline.getBundles().get(0).getSubscriptions().get(0).getEvents().size(), 2);
+        final List<AuditLogJson> bundleAuditLogs = timeline.getBundles().get(0).getAuditLogs();
+        Assert.assertEquals(bundleAuditLogs.size(), 3);
+        verifyAuditLog(bundleAuditLogs.get(0), ChangeType.INSERT, reason, comment, createdBy, startTime, endTime);
+        verifyAuditLog(bundleAuditLogs.get(1), ChangeType.UPDATE, null, null, "Transition", startTime, endTime);
+        verifyAuditLog(bundleAuditLogs.get(2), ChangeType.UPDATE, null, null, "Transition", startTime, endTime);
+
+        // TODO subscription events audit logs
+    }
+
+    private void verifyAuditLog(final AuditLogJson auditLogJson, final ChangeType changeType, @Nullable final String reasonCode,
+                                @Nullable final String comments, @Nullable final String changedBy,
+                                final DateTime startTime, final DateTime endTime) {
+        Assert.assertEquals(auditLogJson.getChangeType(), changeType.toString());
+        Assert.assertFalse(auditLogJson.getChangeDate().isBefore(startTime));
+        // Flaky
+        //Assert.assertFalse(auditLogJson.getChangeDate().isAfter(endTime));
+        Assert.assertEquals(auditLogJson.getReasonCode(), reasonCode);
+        Assert.assertEquals(auditLogJson.getComments(), comments);
+        Assert.assertEquals(auditLogJson.getChangedBy(), changedBy);
+    }
+
     @Test(groups = "slow")
     public void testAccountPaymentMethods() throws Exception {
 
@@ -195,18 +291,17 @@ public class TestAccount extends TestJaxrsBase {
         paymentMethods = mapper.readValue(baseJson, new TypeReference<List<PaymentMethodJson>>() {});
         assertEquals(paymentMethods.size(), 1);
 
-
         //
         // DELETE DEFAULT PAYMENT METHOD (without special flag first)
         //
-        uri = JaxrsResource.PAYMENT_METHODS_PATH + "/" + paymentMethodPP.getPaymentMethodId() ;
+        uri = JaxrsResource.PAYMENT_METHODS_PATH + "/" + paymentMethodPP.getPaymentMethodId();
         response = doDelete(uri, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
         Assert.assertEquals(response.getStatusCode(), Status.BAD_REQUEST.getStatusCode());
 
         //
         // RETRY TO DELETE DEFAULT PAYMENT METHOD (with special flag this time)
         //
-        uri = JaxrsResource.PAYMENT_METHODS_PATH + "/" + paymentMethodPP.getPaymentMethodId() ;
+        uri = JaxrsResource.PAYMENT_METHODS_PATH + "/" + paymentMethodPP.getPaymentMethodId();
         queryParams = new HashMap<String, String>();
         queryParams.put(JaxrsResource.QUERY_DELETE_DEFAULT_PM_WITH_AUTO_PAY_OFF, "true");
 
diff --git a/server/src/test/java/com/ning/billing/jaxrs/TestCredit.java b/server/src/test/java/com/ning/billing/jaxrs/TestCredit.java
index b459ce3..3668f5b 100644
--- a/server/src/test/java/com/ning/billing/jaxrs/TestCredit.java
+++ b/server/src/test/java/com/ning/billing/jaxrs/TestCredit.java
@@ -17,33 +17,21 @@
 package com.ning.billing.jaxrs;
 
 import java.math.BigDecimal;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
 import java.util.UUID;
 
 import javax.ws.rs.core.Response.Status;
 
 import org.joda.time.DateTime;
-import org.joda.time.Interval;
-import org.testng.Assert;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
-import com.ning.billing.catalog.api.BillingPeriod;
-import com.ning.billing.catalog.api.ProductCategory;
 import com.ning.billing.jaxrs.json.AccountJson;
-import com.ning.billing.jaxrs.json.BundleJsonNoSubscriptions;
 import com.ning.billing.jaxrs.json.CreditJson;
 import com.ning.billing.jaxrs.json.InvoiceJsonSimple;
-import com.ning.billing.jaxrs.json.SubscriptionJsonNoEvents;
 import com.ning.billing.jaxrs.resources.JaxrsResource;
 import com.ning.http.client.Response;
 
-import com.fasterxml.jackson.core.type.TypeReference;
-
 import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
 
 public class TestCredit extends TestJaxrsBase {
 
@@ -51,69 +39,22 @@ public class TestCredit extends TestJaxrsBase {
 
     @BeforeMethod(groups = "slow")
     public void setUp() throws Exception {
-        accountJson = createAccount(UUID.randomUUID().toString(), UUID.randomUUID().toString(), "foo@bar.com");
-        assertNotNull(accountJson);
+        accountJson = createAccountWithPMBundleAndSubscriptionAndWaitForFirstInvoice();
     }
 
     @Test(groups = "slow")
     public void testAddCreditToInvoice() throws Exception {
-        final DateTime requestedDate = clock.getUTCNow();
-        final DateTime effectiveDate = clock.getUTCNow();
-        final InvoiceJsonSimple invoice = createInvoice();
-        final CreditJson input = new CreditJson(BigDecimal.TEN, invoice.getInvoiceId(), UUID.randomUUID().toString(),
-                                                requestedDate, effectiveDate,
-                                                UUID.randomUUID().toString(), accountJson.getAccountId(),
-                                                null);
-        final String jsonInput = mapper.writeValueAsString(input);
+        final InvoiceJsonSimple invoice = getInvoicesForAccount(accountJson.getAccountId()).get(1);
 
-        // Create the credit
-        Response response = doPost(JaxrsResource.CREDITS_PATH, jsonInput, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
-        assertEquals(response.getStatusCode(), Status.CREATED.getStatusCode(), response.getResponseBody());
-
-        final String location = response.getHeader("Location");
-        assertNotNull(location);
-
-        // Retrieves by Id based on Location returned
-        response = doGetWithUrl(location, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
-        assertEquals(response.getStatusCode(), Status.OK.getStatusCode());
+        final DateTime effectiveDate = clock.getUTCNow();
+        final BigDecimal creditAmount = BigDecimal.ONE;
+        final CreditJson objFromJson = createCreditForInvoice(accountJson.getAccountId(), invoice.getInvoiceId(),
+                                                              creditAmount, clock.getUTCNow(), effectiveDate);
 
         // We can't just compare the object via .equals() due e.g. to the invoice id
-        final CreditJson objFromJson = mapper.readValue(response.getResponseBody(), CreditJson.class);
-        assertEquals(objFromJson.getAccountId(), input.getAccountId());
-        assertEquals(objFromJson.getCreditAmount().compareTo(input.getCreditAmount()), 0);
-        assertEquals(objFromJson.getEffectiveDate().toLocalDate().compareTo(input.getEffectiveDate().toLocalDate()), 0);
-    }
-
-    private InvoiceJsonSimple createInvoice() throws Exception {
-        final DateTime initialDate = new DateTime(2012, 4, 25, 0, 3, 42, 0);
-        clock.setDeltaFromReality(initialDate.getMillis() - clock.getUTCNow().getMillis());
-
-        final AccountJson accountJson = createAccountWithDefaultPaymentMethod("poupou", "qhddffrwe", "poupou@yahoo.com");
-        assertNotNull(accountJson);
-
-        final BundleJsonNoSubscriptions bundleJson = createBundle(accountJson.getAccountId(), "9967599");
-        assertNotNull(bundleJson);
-
-        final SubscriptionJsonNoEvents subscriptionJson = createSubscription(bundleJson.getBundleId(), "Shotgun", ProductCategory.BASE.toString(), BillingPeriod.MONTHLY.toString(), true);
-        assertNotNull(subscriptionJson);
-
-        // MOVE AFTER TRIAL
-        final Interval it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusDays(30));
-        clock.addDeltaFromReality(it.toDurationMillis());
-        crappyWaitForLackOfProperSynchonization();
-
-        final String uri = JaxrsResource.INVOICES_PATH;
-        final Map<String, String> queryParams = new HashMap<String, String>();
-        queryParams.put(JaxrsResource.QUERY_ACCOUNT_ID, accountJson.getAccountId());
-
-        final Response response = doGet(uri, queryParams, DEFAULT_HTTP_TIMEOUT_SEC);
-        Assert.assertEquals(response.getStatusCode(), Status.OK.getStatusCode());
-        final String baseJson = response.getResponseBody();
-        final List<InvoiceJsonSimple> objFromJson = mapper.readValue(baseJson, new TypeReference<List<InvoiceJsonSimple>>() {});
-        assertNotNull(objFromJson);
-        assertEquals(objFromJson.size(), 2);
-
-        return objFromJson.get(1);
+        assertEquals(objFromJson.getAccountId(), accountJson.getAccountId());
+        assertEquals(objFromJson.getCreditAmount().compareTo(creditAmount), 0);
+        assertEquals(objFromJson.getEffectiveDate().toLocalDate().compareTo(effectiveDate.toLocalDate()), 0);
     }
 
     @Test(groups = "slow")
diff --git a/server/src/test/java/com/ning/billing/jaxrs/TestJaxrsBase.java b/server/src/test/java/com/ning/billing/jaxrs/TestJaxrsBase.java
index 3de0e0e..c8941c2 100644
--- a/server/src/test/java/com/ning/billing/jaxrs/TestJaxrsBase.java
+++ b/server/src/test/java/com/ning/billing/jaxrs/TestJaxrsBase.java
@@ -67,6 +67,8 @@ import com.ning.billing.jaxrs.json.AccountJson;
 import com.ning.billing.jaxrs.json.AccountTimelineJson;
 import com.ning.billing.jaxrs.json.BillCycleDayJson;
 import com.ning.billing.jaxrs.json.BundleJsonNoSubscriptions;
+import com.ning.billing.jaxrs.json.ChargebackJson;
+import com.ning.billing.jaxrs.json.CreditJson;
 import com.ning.billing.jaxrs.json.InvoiceItemJsonSimple;
 import com.ning.billing.jaxrs.json.InvoiceJsonSimple;
 import com.ning.billing.jaxrs.json.InvoiceJsonWithItems;
@@ -76,6 +78,7 @@ import com.ning.billing.jaxrs.json.PaymentMethodJson.PaymentMethodPluginDetailJs
 import com.ning.billing.jaxrs.json.PaymentMethodJson.PaymentMethodProperties;
 import com.ning.billing.jaxrs.json.RefundJson;
 import com.ning.billing.jaxrs.json.SubscriptionJsonNoEvents;
+import com.ning.billing.jaxrs.resources.AccountResource;
 import com.ning.billing.jaxrs.resources.JaxrsResource;
 import com.ning.billing.junction.glue.DefaultJunctionModule;
 import com.ning.billing.payment.glue.PaymentModule;
@@ -140,9 +143,9 @@ public class TestJaxrsBase extends ServerTestSuiteWithEmbeddedDB {
     protected TestApiListener busHandler;
 
     // Context information to be passed around
-    private static final String createdBy = "Toto";
-    private static final String reason = "i am god";
-    private static final String comment = "no comment";
+    protected static final String createdBy = "Toto";
+    protected static final String reason = "i am god";
+    protected static final String comment = "no comment";
 
     public static void loadSystemPropertiesFromClasspath(final String resource) {
         final URL url = TestJaxrsBase.class.getResource(resource);
@@ -361,9 +364,17 @@ public class TestJaxrsBase extends ServerTestSuiteWithEmbeddedDB {
     }
 
     protected AccountTimelineJson getAccountTimeline(final String accountId) throws Exception {
+        return doGetAccountTimeline(accountId, false);
+    }
+
+    protected AccountTimelineJson getAccountTimelineWithAudits(final String accountId) throws Exception {
+        return doGetAccountTimeline(accountId, true);
+    }
+
+    private AccountTimelineJson doGetAccountTimeline(final String accountId, final Boolean withAudits) throws Exception {
         final String uri = JaxrsResource.ACCOUNTS_PATH + "/" + accountId + "/" + JaxrsResource.TIMELINE;
 
-        final Response response = doGet(uri, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
+        final Response response = doGet(uri, ImmutableMap.<String, String>of(JaxrsResource.QUERY_AUDIT, withAudits.toString()), DEFAULT_HTTP_TIMEOUT_SEC);
         Assert.assertEquals(response.getStatusCode(), Status.OK.getStatusCode());
 
         final String baseJson = response.getResponseBody();
@@ -728,6 +739,27 @@ public class TestJaxrsBase extends ServerTestSuiteWithEmbeddedDB {
     }
 
     //
+    // CHARGEBACKS
+    //
+
+    protected ChargebackJson createChargeBack(final String paymentId, final BigDecimal chargebackAmount) throws IOException {
+        final ChargebackJson input = new ChargebackJson(null, null, chargebackAmount, paymentId, null, null);
+        final String jsonInput = mapper.writeValueAsString(input);
+
+        // Create the chargeback
+        final Response response = doPost(JaxrsResource.CHARGEBACKS_PATH, jsonInput, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
+        assertEquals(response.getStatusCode(), Status.CREATED.getStatusCode(), response.getResponseBody());
+
+        // Find the chargeback by location
+        final String location = response.getHeader("Location");
+        assertNotNull(location);
+        final Response responseByLocation = doGetWithUrl(location, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
+        assertEquals(responseByLocation.getStatusCode(), Status.OK.getStatusCode());
+
+        return mapper.readValue(responseByLocation.getResponseBody(), ChargebackJson.class);
+    }
+
+    //
     // REFUNDS
     //
 
@@ -737,7 +769,7 @@ public class TestJaxrsBase extends ServerTestSuiteWithEmbeddedDB {
 
         Assert.assertEquals(response.getStatusCode(), Status.OK.getStatusCode());
         final String baseJson = response.getResponseBody();
-        List<RefundJson> refunds = mapper.readValue(baseJson, new TypeReference<List<RefundJson>>() {});
+        final List<RefundJson> refunds = mapper.readValue(baseJson, new TypeReference<List<RefundJson>>() {});
         assertNotNull(refunds);
 
         return refunds;
@@ -803,6 +835,37 @@ public class TestJaxrsBase extends ServerTestSuiteWithEmbeddedDB {
     }
 
     //
+    // CREDITS
+    //
+
+    protected CreditJson createCreditForAccount(final String accountId, final BigDecimal creditAmount,
+                                                final DateTime requestedDate, final DateTime effectiveDate) throws IOException {
+        return createCreditForInvoice(accountId, null, creditAmount, requestedDate, effectiveDate);
+    }
+
+    protected CreditJson createCreditForInvoice(final String accountId, final String invoiceId, final BigDecimal creditAmount,
+                                                final DateTime requestedDate, final DateTime effectiveDate) throws IOException {
+        final CreditJson input = new CreditJson(creditAmount, invoiceId, UUID.randomUUID().toString(),
+                                                requestedDate, effectiveDate,
+                                                UUID.randomUUID().toString(), accountId,
+                                                null);
+        final String jsonInput = mapper.writeValueAsString(input);
+
+        // Create the credit
+        Response response = doPost(JaxrsResource.CREDITS_PATH, jsonInput, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
+        assertEquals(response.getStatusCode(), Status.CREATED.getStatusCode(), response.getResponseBody());
+
+        final String location = response.getHeader("Location");
+        assertNotNull(location);
+
+        // Retrieves by Id based on Location returned
+        response = doGetWithUrl(location, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
+        assertEquals(response.getStatusCode(), Status.OK.getStatusCode());
+
+        return mapper.readValue(response.getResponseBody(), CreditJson.class);
+    }
+
+    //
     // HTTP CLIENT HELPERS
     //
     protected Response doPost(final String uri, @Nullable final String body, final Map<String, String> queryParams, final int timeoutSec) {