public void TestEditRecurringGiftOnlyChangePayment()
        {
            const string authUserToken = "auth";
            var today = DateTime.Today;

            var editGift = new RecurringGiftDto
            {
                RecurringGiftId = 345,
                StripeTokenId = "tok_123",
                PlanAmount = 500M,
                Program = "3",
                PlanInterval = PlanInterval.Weekly,
                StartDate = today
            };

            var donor = new ContactDonor
            {
                DonorId = 456,
                ProcessorId = "cus_123"
            };

            var existingGift = new CreateDonationDistDto
            {
                Amount = 50000,
                ProgramId = "3",
                Frequency = 1,
                StartDate = today,
                DonorAccountId = 234,
                SubscriptionId = "sub_123",
                DayOfWeek = (int)today.DayOfWeek,
                RecurringGiftId = 345,
                DonorId = 789,
                StripeCustomerId = "cus_456",
                StripeAccountId = "card_456"
            };

            var stripeSource = new SourceData
            {
                id = "bank_1234",
                bank_last4 = "5678"
            };


            const int newDonorAccountId = 987;

            _mpDonorService.Setup(mocked => mocked.GetRecurringGiftById(authUserToken, editGift.RecurringGiftId)).Returns(existingGift);
            _paymentService.Setup(mocked => mocked.UpdateCustomerSource(existingGift.StripeCustomerId, editGift.StripeTokenId)).Returns(stripeSource);
            _mpDonorService.Setup(mocked => mocked.CreateDonorAccount(null, "0", stripeSource.bank_last4, null, existingGift.DonorId, stripeSource.id, existingGift.StripeCustomerId)).Returns(newDonorAccountId);
            _mpDonorService.Setup(mocked => mocked.UpdateRecurringGiftDonorAccount(authUserToken, existingGift.RecurringGiftId.Value, newDonorAccountId));

            var result = _fixture.EditRecurringGift(authUserToken, editGift, donor);
            _mpDonorService.VerifyAll();
            _paymentService.VerifyAll();

            Assert.IsNotNull(result);
        }
        public void TestEditRecurringGiftChangePaymentAndStartDate()
        {
            const string authUserToken = "auth";
            var today = DateTime.Today;
            const int congregationId = 1;

            var editGift = new RecurringGiftDto
            {
                RecurringGiftId = 345,
                StripeTokenId = "tok_123",
                PlanAmount = 800M,
                Program = "3",
                PlanInterval = PlanInterval.Weekly,
                StartDate = today
            };

            var donor = new ContactDonor
            {
                DonorId = 456,
                ProcessorId = "cus_123",
                Email = "*****@*****.**"
            };

            var existingGift = new CreateDonationDistDto
            {
                Amount = 50000,
                ProgramId = "3",
                Frequency = 1,
                StartDate = today.AddDays(-7),
                DonorAccountId = 234,
                SubscriptionId = "sub_123",
                DayOfWeek = (int)today.AddDays(-7).DayOfWeek,
                RecurringGiftId = 345,
                DonorId = 789,
                StripeCustomerId = "cus_456",
                StripeAccountId = "card_456"
            };

            var stripeSource = new SourceData
            {
                brand = "Visa",
                last4 = "1234",
                id = "card_123"
            };

            const int newDonorAccountId = 987;

            var oldSubscription = new StripeSubscription
            {
                Id = "sub_123",
                Plan = new StripePlan
                {
                    Id = "plan_123"
                }
            };

            var newPlan = new StripePlan
            {
                Id = "plan_456"
            };

            var newSubscription = new StripeSubscription
            {
                Id = "sub_456"
            };

            const int newRecurringGiftId = 765;

            var newRecurringGift = new CreateDonationDistDto
            {
                Amount = 80000,
                ProgramId = "3",
                Frequency = 1,
                StartDate = today,
                DonorAccountId = 234,
                SubscriptionId = "sub_456",
                DayOfWeek = (int)today.DayOfWeek,
                RecurringGiftId = newRecurringGiftId,
                DonorId = 789
            };

            var contact = new MyContact()
            {
                Congregation_ID = congregationId
            };

            _mpDonorService.Setup(mocked => mocked.GetRecurringGiftById(authUserToken, editGift.RecurringGiftId)).Returns(existingGift);
            _paymentService.Setup(mocked => mocked.UpdateCustomerSource(existingGift.StripeCustomerId, editGift.StripeTokenId)).Returns(stripeSource);
            _mpDonorService.Setup(mocked => mocked.CreateDonorAccount(stripeSource.brand, "0", stripeSource.last4, null, existingGift.DonorId, stripeSource.id, existingGift.StripeCustomerId)).Returns(newDonorAccountId);
            _paymentService.Setup(mocked => mocked.CancelSubscription(existingGift.StripeCustomerId, existingGift.SubscriptionId)).Returns(oldSubscription);
            _paymentService.Setup(mocked => mocked.CreateSubscription(newPlan.Id, existingGift.StripeCustomerId, newRecurringGift.StartDate.Value)).Returns(newSubscription);
            _paymentService.Setup(mocked => mocked.CancelPlan(oldSubscription.Plan.Id)).Returns(oldSubscription.Plan);
            _paymentService.Setup(mocked => mocked.CreatePlan(editGift, donor)).Returns(newPlan);
            _mpDonorService.Setup(mocked => mocked.CancelRecurringGift(authUserToken, existingGift.RecurringGiftId.Value));
            _mpContactService.Setup(mocked => mocked.GetContactById(donor.ContactId)).Returns(contact);
            _mpDonorService.Setup(
                mocked =>
                    mocked.CreateRecurringGiftRecord(authUserToken,
                                                     donor.DonorId,
                                                     newDonorAccountId,
                                                     EnumMemberSerializationUtils.ToEnumString(editGift.PlanInterval),
                                                     editGift.PlanAmount,
                                                     editGift.StartDate,
                                                     editGift.Program,
                                                     newSubscription.Id, contact.Congregation_ID.Value)).Returns(newRecurringGiftId);
            _mpDonorService.Setup(mocked => mocked.GetRecurringGiftById(authUserToken, newRecurringGiftId)).Returns(newRecurringGift);

            var result = _fixture.EditRecurringGift(authUserToken, editGift, donor);
            _mpDonorService.VerifyAll();
            _paymentService.VerifyAll();

            Assert.IsNotNull(result);
            Assert.AreEqual(newRecurringGift.RecurringGiftId, result.RecurringGiftId);
            Assert.AreEqual(newRecurringGift.StartDate, result.StartDate);
            Assert.AreEqual(newRecurringGift.Amount, result.PlanAmount);
            Assert.AreEqual(PlanInterval.Weekly, result.PlanInterval);
            Assert.AreEqual(newRecurringGift.ProgramId, result.Program);
            Assert.AreEqual(newRecurringGift.DonorId, result.DonorID);
            Assert.AreEqual(donor.Email, result.EmailAddress);
            Assert.AreEqual(newSubscription.Id, result.SubscriptionID);
        }
        public void TestCreateRecurringGiftNoCongregation()
        {
            var recurringGiftDto = new RecurringGiftDto
            {
                StripeTokenId = "tok_123",
                PlanAmount = 123.45M,
                PlanInterval = PlanInterval.Weekly,
                Program = "987",
                StartDate = DateTime.Parse("1973-10-15")
            };

            var contactDonor = new ContactDonor
            {
                DonorId = 678,
                ProcessorId = "cus_123"
            };

            var stripeCustomer = new StripeCustomer
            {
                brand = "visa",
                last4 = "9876",
                id = "card_123"
            };

            var stripePlan = new StripePlan
            {
                Id = "plan_123"
            };

            const int donorAccountId = 999;

            var stripeSubscription = new StripeSubscription
            {
                Id = "sub_123"
            };

            var contact = new MyContact()
            {
                Congregation_ID = null
            };
            const int recurringGiftId = 888;

            _paymentService.Setup(mocked => mocked.AddSourceToCustomer(contactDonor.ProcessorId, recurringGiftDto.StripeTokenId)).Returns(stripeCustomer);
            _paymentService.Setup(mocked => mocked.CreatePlan(recurringGiftDto, contactDonor)).Returns(stripePlan);
            _mpDonorService.Setup(
                mocked =>
                    mocked.CreateDonorAccount(stripeCustomer.brand,
                                              It.IsAny<string>(),
                                              stripeCustomer.last4,
                                              null,
                                              contactDonor.DonorId,
                                              stripeCustomer.id,
                                              contactDonor.ProcessorId)).Returns(donorAccountId);
            _paymentService.Setup(mocked => mocked.CreateSubscription(stripePlan.Id, contactDonor.ProcessorId, recurringGiftDto.StartDate)).Returns(stripeSubscription);
            _mpContactService.Setup(mocked => mocked.GetContactById(contactDonor.DonorId)).Returns(contact);
            _mpDonorService.Setup(
                mocked =>
                    mocked.CreateRecurringGiftRecord("auth", contactDonor.DonorId,
                                                     donorAccountId,
                                                     EnumMemberSerializationUtils.ToEnumString(recurringGiftDto.PlanInterval),
                                                     recurringGiftDto.PlanAmount,
                                                     recurringGiftDto.StartDate,
                                                     recurringGiftDto.Program,
                                                     stripeSubscription.Id, NotSiteSpecificCongregation)).Returns(recurringGiftId);
            var response = _fixture.CreateRecurringGift("auth", recurringGiftDto, contactDonor);
            _paymentService.VerifyAll();
            _mpDonorService.VerifyAll();
            _mpContactService.VerifyAll();
            Assert.AreEqual(recurringGiftId, response);
        }
        public void TestEditRecurringGiftNoEdits()
        {
            const string authUserToken = "auth";
            var today = DateTime.Today;

            var editGift = new RecurringGiftDto
            {
                RecurringGiftId = 345,
                StripeTokenId = string.Empty,
                PlanAmount = 500M,
                Program = "3",
                PlanInterval = PlanInterval.Weekly,
                StartDate = today
            };

            var donor = new ContactDonor
            {
                DonorId = 456
            };

            var existingGift = new CreateDonationDistDto
            {
                Amount = 50000,
                ProgramId = "3",
                Frequency = 1,
                StartDate = today,
                DonorAccountId = 234,
                SubscriptionId = "sub_123",
                DayOfWeek = (int)today.DayOfWeek,
                RecurringGiftId = 345
            };

            _mpDonorService.Setup(mocked => mocked.GetRecurringGiftById(authUserToken, editGift.RecurringGiftId)).Returns(existingGift);

            var result = _fixture.EditRecurringGift(authUserToken, editGift, donor);
            _mpDonorService.VerifyAll();
            _paymentService.VerifyAll();

            Assert.IsNotNull(result);
        }
        public void TestCreateRecurringGift()
        {
            var recurringGiftDto = new RecurringGiftDto
            {
                StripeTokenId = "tok_123",
                PlanAmount = 123.45M,
                PlanInterval = PlanInterval.Weekly,
                Program = "987",
                StartDate = DateTime.Parse("1973-10-15")
            };

            var contactDonor = new ContactDonor
            {
                DonorId = 678,
                ProcessorId = "cus_123",
                ContactId = 909090
            };

            var defaultSource = new SourceData
            {
                id = "card_123",
                brand = "Visa",
                last4 = "5150"
            };

            var stripeCustomer = new StripeCustomer
            {
                brand = "visa",
                last4 = "9876",
                id = "cus_123",
                default_source = "card_123",
                sources = new Sources
                {
                    data = new List<SourceData>
                    {
                        new SourceData
                        {
                            id = "bank_123",
                            bank_last4 = "5678"
                        },
                        defaultSource
                    }
                }
            };

            var stripePlan = new StripePlan
            {
                Id = "plan_123"
            };

            const int donorAccountId = 999;

            var stripeSubscription = new StripeSubscription
            {
                Id = "sub_123"
            };

            var contact = new MyContact()
            {
                Congregation_ID = 1
            };
            const int recurringGiftId = 888;

            var recurringGift = new CreateDonationDistDto
            {
                ProgramName = "Crossroads",
                Amount = 123.45M,
                Recurrence = "12th of the month",
                DonorAccountId = 90
            };

            _paymentService.Setup(mocked => mocked.CreateCustomer(recurringGiftDto.StripeTokenId, "678, Recurring Gift Subscription")).Returns(stripeCustomer);
            _paymentService.Setup(mocked => mocked.CreatePlan(recurringGiftDto, contactDonor)).Returns(stripePlan);
            _mpDonorService.Setup(
                mocked =>
                    mocked.CreateDonorAccount(defaultSource.brand,
                                              It.IsAny<string>(),
                                              defaultSource.last4,
                                              null,
                                              contactDonor.DonorId,
                                              defaultSource.id,
                                              stripeCustomer.id)).Returns(donorAccountId);
            _paymentService.Setup(mocked => mocked.CreateSubscription(stripePlan.Id, stripeCustomer.id, recurringGiftDto.StartDate)).Returns(stripeSubscription);
            _mpContactService.Setup(mocked => mocked.GetContactById(contactDonor.ContactId)).Returns(contact);
            _mpDonorService.Setup(
                mocked =>
                    mocked.CreateRecurringGiftRecord("auth", contactDonor.DonorId,
                                                     donorAccountId,
                                                     EnumMemberSerializationUtils.ToEnumString(recurringGiftDto.PlanInterval),
                                                     recurringGiftDto.PlanAmount,
                                                     recurringGiftDto.StartDate,
                                                     recurringGiftDto.Program,
                                                     stripeSubscription.Id, contact.Congregation_ID.Value)).Returns(recurringGiftId);

            _mpDonorService.Setup(mocked => mocked.GetRecurringGiftById("auth", recurringGiftId)).Returns(recurringGift);
            _mpDonorService.Setup(mocked => mocked.GetDonorAccountPymtType(recurringGift.DonorAccountId.Value)).Returns(1);
            _mpDonorService.Setup(
                mocked =>
                    mocked.SendEmail(RecurringGiftSetupEmailTemplateId, recurringGift.DonorId, (int)(123.45M/100), "Check", It.IsAny<DateTime>(), "Crossroads", string.Empty, "12th of the month"));

            var response = _fixture.CreateRecurringGift("auth", recurringGiftDto, contactDonor);
            _paymentService.VerifyAll();
            _mpDonorService.VerifyAll();
            Assert.AreEqual(recurringGiftId, response);
        }
        public void TestCreateRecurringGiftWholeLottaFailures()
        {
            var recurringGiftDto = new RecurringGiftDto
            {
                StripeTokenId = "tok_123",
                PlanAmount = 123.45M,
                PlanInterval = PlanInterval.Weekly,
                Program = "987",
                StartDate = DateTime.Parse("1973-10-15")
            };

            var contactDonor = new ContactDonor
            {
                DonorId = 678,
                ProcessorId = "cus_123",
                ContactId = 909090
            };

            var defaultSource = new SourceData
            {
                id = "card_123",
                brand = "Visa",
                last4 = "5150"
            };

            var stripeCustomer = new StripeCustomer
            {
                brand = "visa",
                last4 = "9876",
                id = "cus_123",
                default_source = "card_123",
                sources = new Sources
                {
                    data = new List<SourceData>
                    {
                        new SourceData
                        {
                            id = "bank_123",
                            bank_last4 = "5678"
                        },
                        defaultSource
                    }
                }
            };

            var stripePlan = new StripePlan
            {
                Id = "plan_123"
            };

            const int donorAccountId = 999;

            var stripeSubscription = new StripeSubscription
            {
                Id = "sub_123"
            };

            var contact = new MyContact()
            {
                Congregation_ID = 1
            };

            _paymentService.Setup(mocked => mocked.CreateCustomer(recurringGiftDto.StripeTokenId, "678, Recurring Gift Subscription")).Returns(stripeCustomer);
            _paymentService.Setup(mocked => mocked.CreatePlan(recurringGiftDto, contactDonor)).Returns(stripePlan);
            _mpDonorService.Setup(
                mocked =>
                    mocked.CreateDonorAccount(defaultSource.brand,
                                              It.IsAny<string>(),
                                              defaultSource.last4,
                                              null,
                                              contactDonor.DonorId,
                                              defaultSource.id,
                                              stripeCustomer.id)).Returns(donorAccountId);
            _paymentService.Setup(mocked => mocked.CreateSubscription(stripePlan.Id, stripeCustomer.id, recurringGiftDto.StartDate)).Returns(stripeSubscription);
            _mpContactService.Setup(mocked => mocked.GetContactById(contactDonor.ContactId)).Returns(contact);
            var exception = new ApplicationException("Do it to it Lars");
            _mpDonorService.Setup(
                mocked =>
                    mocked.CreateRecurringGiftRecord("auth",
                                                     contactDonor.DonorId,
                                                     donorAccountId,
                                                     EnumMemberSerializationUtils.ToEnumString(recurringGiftDto.PlanInterval),
                                                     recurringGiftDto.PlanAmount,
                                                     recurringGiftDto.StartDate,
                                                     recurringGiftDto.Program,
                                                     stripeSubscription.Id,
                                                     contact.Congregation_ID.Value)).Throws(exception);

            _paymentService.Setup(mocked => mocked.CancelSubscription(stripeCustomer.id, stripeSubscription.Id)).Throws(new Exception());
            _paymentService.Setup(mocked => mocked.CancelPlan(stripePlan.Id)).Throws(new Exception());
            _paymentService.Setup(mocked => mocked.DeleteCustomer(stripeCustomer.id)).Throws(new Exception());
            _mpDonorService.Setup(mocked => mocked.DeleteDonorAccount("auth", donorAccountId)).Throws(new Exception());

            try
            {
                _fixture.CreateRecurringGift("auth", recurringGiftDto, contactDonor);
                Assert.Fail("Expected exception was not thrown");
            }
            catch (ApplicationException e)
            {
                Assert.AreSame(exception, e);
            }
            _paymentService.VerifyAll();
            _mpDonorService.VerifyAll();
            _mpContactService.VerifyAll();
        }
        public void TestEditRecurringGiftStripeError()
        {
            var authorizedUserToken = _authType + " " + _authToken;
            var donor = new ContactDonor();
            var editGift = new RecurringGiftDto();
            const int recurringGiftId = 123;

            var stripeException = new PaymentProcessorException(HttpStatusCode.Forbidden,
                                                                "aux message",
                                                                "error type",
                                                                "message",
                                                                "code",
                                                                "decline code",
                                                                "param",
                                                                new ContentBlock());

            _donorService.Setup(mocked => mocked.GetContactDonorForAuthenticatedUser(authorizedUserToken)).Returns(donor);
            _donorService.Setup(mocked => mocked.EditRecurringGift(authorizedUserToken, editGift, donor)).Throws(stripeException);

            var response = _fixture.EditRecurringGift(recurringGiftId, editGift);
            _donorService.VerifyAll();
            Assert.AreEqual(recurringGiftId, editGift.RecurringGiftId);
            Assert.IsNotNull(response);
            Assert.IsInstanceOf<RestHttpActionResult<PaymentProcessorErrorResponse>>(response);
            var err = (RestHttpActionResult<PaymentProcessorErrorResponse>)response;
            Assert.AreEqual(HttpStatusCode.Forbidden, err.StatusCode);
        }
        public void TestEditRecurringGiftMinistryPlatformException()
        {
            var authorizedUserToken = _authType + " " + _authToken;
            var donor = new ContactDonor();
            var editGift = new RecurringGiftDto();
            const int recurringGiftId = 123;

            _donorService.Setup(mocked => mocked.GetContactDonorForAuthenticatedUser(authorizedUserToken)).Returns(donor);
            _donorService.Setup(mocked => mocked.EditRecurringGift(authorizedUserToken, editGift, donor)).Throws<ApplicationException>();

            try
            {
                _fixture.EditRecurringGift(recurringGiftId, editGift);
                Assert.Fail("expected exception was not thrown");
            }
            catch (HttpResponseException)
            {
                // expected
            }
            _donorService.VerifyAll();

            Assert.AreEqual(recurringGiftId, editGift.RecurringGiftId);
        }
        public void TestCreateRecurringGiftStripeError()
        {
            const string stripeToken = "tok_123";
            var contactDonor = new ContactDonor();
            var contactDonorUpdated = new ContactDonor();
            var recurringGiftDto = new RecurringGiftDto
            {
                StripeTokenId = stripeToken
            };
            var stripeException = new PaymentProcessorException(HttpStatusCode.Forbidden,
                                                                "aux message",
                                                                "error type",
                                                                "message",
                                                                "code",
                                                                "decline code",
                                                                "param",
                                                                new ContentBlock());

            _donorService.Setup(mocked => mocked.GetContactDonorForAuthenticatedUser(_authType + " " + _authToken)).Returns(contactDonor);
            _donorService.Setup(mocked => mocked.CreateOrUpdateContactDonor(contactDonor, string.Empty, string.Empty, null, null)).Returns(contactDonorUpdated);
            _donorService.Setup(mocked => mocked.CreateRecurringGift(_authType + " " + _authToken, recurringGiftDto, contactDonorUpdated)).Throws(stripeException);

            var response = _fixture.CreateRecurringGift(recurringGiftDto);
            _donorService.VerifyAll();
            Assert.IsNotNull(response);
            Assert.IsInstanceOf<RestHttpActionResult<PaymentProcessorErrorResponse>>(response);
            var err = (RestHttpActionResult<PaymentProcessorErrorResponse>) response;
            Assert.AreEqual(HttpStatusCode.Forbidden, err.StatusCode);
        }
        public void TestEditRecurringGift()
        {
            var authorizedUserToken = _authType + " " + _authToken;
            var donor = new ContactDonor();
            var editGift = new RecurringGiftDto();
            var newGift = new RecurringGiftDto();
            const int recurringGiftId = 123;

            _donorService.Setup(mocked => mocked.GetContactDonorForAuthenticatedUser(authorizedUserToken)).Returns(donor);
            _donorService.Setup(mocked => mocked.EditRecurringGift(authorizedUserToken, editGift, donor)).Returns(newGift);

            var response = _fixture.EditRecurringGift(recurringGiftId, editGift);
            _donorService.VerifyAll();

            Assert.AreEqual(recurringGiftId, editGift.RecurringGiftId);
            Assert.IsNotNull(response);
            Assert.IsInstanceOf<OkNegotiatedContentResult<RecurringGiftDto>>(response);
            var dtoResponse = ((OkNegotiatedContentResult<RecurringGiftDto>)response).Content;
            Assert.IsNotNull(dtoResponse);
            Assert.AreSame(newGift, dtoResponse);
        }
        public void TestCreateRecurringGift()
        {
            const string stripeToken = "tok_123";
            var contactDonor = new ContactDonor
            {
                Email = "*****@*****.**"
            };
            var contactDonorUpdated = new ContactDonor
            {
                Email = "*****@*****.**"
            };
            var recurringGiftDto = new RecurringGiftDto
            {
                StripeTokenId = stripeToken
            };

            _donorService.Setup(mocked => mocked.GetContactDonorForAuthenticatedUser(_authType + " " + _authToken)).Returns(contactDonor);
            _donorService.Setup(mocked => mocked.CreateOrUpdateContactDonor(contactDonor, string.Empty, string.Empty, null, null)).Returns(contactDonorUpdated);
            _donorService.Setup(mocked => mocked.CreateRecurringGift(_authType + " " + _authToken, recurringGiftDto, contactDonorUpdated)).Returns(123);

            var response = _fixture.CreateRecurringGift(recurringGiftDto);
            _donorService.VerifyAll();
            Assert.IsNotNull(response);
            Assert.IsInstanceOf<OkNegotiatedContentResult<RecurringGiftDto>>(response);
            var dtoResponse = ((OkNegotiatedContentResult<RecurringGiftDto>) response).Content;
            Assert.IsNotNull(dtoResponse);
            Assert.AreSame(recurringGiftDto, dtoResponse);
            Assert.AreEqual(contactDonorUpdated.Email, recurringGiftDto.EmailAddress);
            Assert.AreEqual(123, recurringGiftDto.RecurringGiftId);
        }
Example #12
0
        public StripePlan CreatePlan(RecurringGiftDto recurringGiftDto, ContactDonor contactDonor)
        {
            var request = new RestRequest("plans", Method.POST);

            var interval = EnumMemberSerializationUtils.ToEnumString(recurringGiftDto.PlanInterval);

            request.AddParameter("amount", (int)(recurringGiftDto.PlanAmount * Constants.StripeDecimalConversionValue));
            request.AddParameter("interval", interval);
            request.AddParameter("name", string.Format("Donor ID #{0} {1}ly", contactDonor.DonorId, interval));
            request.AddParameter("currency", "usd");
            request.AddParameter("id", contactDonor.DonorId + " " + DateTime.Now);

            var response = _stripeRestClient.Execute<StripePlan>(request);
            CheckStripeResponse("Invalid plan creation request", response);

            return response.Data;
        }
Example #13
0
        /// <summary>
        /// Edit an existing recurring gift.  This will cancel (end-date) an existing RecurringGift and then create a new one
        /// if the Program, Amount, Frequency, Day of Week, or Day of Month are changed.  This will simply edit the existing gift
        /// if only the payment method (credit card, bank account) is changed.
        /// </summary>
        /// <param name="authorizedUserToken">An OAuth token for the user who is logged in to cr.net/MP</param>
        /// <param name="editGift">The edited values for the Recurring Gift</param>
        /// <param name="donor">The donor performing the edits</param>
        /// <returns>A RecurringGiftDto, populated with any new/updated values after any edits</returns>
        public RecurringGiftDto EditRecurringGift(string authorizedUserToken, RecurringGiftDto editGift, ContactDonor donor)
        {
            var existingGift = _mpDonorService.GetRecurringGiftById(authorizedUserToken, editGift.RecurringGiftId);

            // Assuming payment info is changed if a token is given.
            var changedPayment = !string.IsNullOrWhiteSpace(editGift.StripeTokenId);

            var changedAmount = (int)(editGift.PlanAmount * Constants.StripeDecimalConversionValue) != existingGift.Amount;
            var changedProgram = !editGift.Program.Equals(existingGift.ProgramId);
            var changedFrequency = !editGift.PlanInterval.Equals(existingGift.Frequency == RecurringGiftFrequencyWeekly ? PlanInterval.Weekly : PlanInterval.Monthly);
            var changedDayOfWeek = changedFrequency || (editGift.PlanInterval == PlanInterval.Weekly && (int) editGift.StartDate.DayOfWeek != existingGift.DayOfWeek);
            var changedDayOfMonth = changedFrequency || (editGift.PlanInterval == PlanInterval.Monthly && editGift.StartDate.Day != existingGift.DayOfMonth);
            var changedStartDate = editGift.StartDate.Date != existingGift.StartDate.GetValueOrDefault().Date;

            var needsUpdatedStripeSubscription = changedAmount && !(changedFrequency || changedDayOfWeek || changedDayOfMonth || changedStartDate);
            var needsNewStripePlan = changedAmount || changedFrequency || changedDayOfWeek || changedDayOfMonth || changedStartDate;
            var needsNewMpRecurringGift = changedAmount || changedProgram || needsNewStripePlan;

            var recurringGiftId = existingGift.RecurringGiftId.GetValueOrDefault(-1);

            int donorAccountId;

            if (changedPayment)
            {
                // If the payment method changed, we need to create a new Stripe Source.
                var source = _paymentService.UpdateCustomerSource(existingGift.StripeCustomerId, editGift.StripeTokenId);

                donorAccountId = _mpDonorService.CreateDonorAccount(source.brand,
                                                                    DonorRoutingNumberDefault,
                                                                    string.IsNullOrWhiteSpace(source.bank_last4) ? source.last4 : source.bank_last4,
                                                                    null, //Encrypted account
                                                                    existingGift.DonorId,
                                                                    source.id,
                                                                    existingGift.StripeCustomerId);

                // If we are not going to create a new Recurring Gift, then we'll update the existing
                // gift with the new donor account
                if (!needsNewMpRecurringGift)
                {
                    _mpDonorService.UpdateRecurringGiftDonorAccount(authorizedUserToken, recurringGiftId, donorAccountId);
                }
            }
            else
            {
                // If the payment method is not changed, set the donorAccountId with the existing ID so we can use it later
                donorAccountId = existingGift.DonorAccountId.GetValueOrDefault();
            }

            // Initialize a StripeSubscription, as we need the ID later on
            var stripeSubscription = new StripeSubscription {Id = existingGift.SubscriptionId};

            if (needsNewMpRecurringGift)
            {
                if (needsNewStripePlan)
                {
                    // Create the new Stripe Plan
                    var plan = _paymentService.CreatePlan(editGift, donor);
                    StripeSubscription oldSubscription;
                    if (needsUpdatedStripeSubscription)
                    {
                        // If we just changed the amount, we just need to update the Subscription to point to the new plan
                        oldSubscription = _paymentService.GetSubscription(existingGift.StripeCustomerId, stripeSubscription.Id);
                        stripeSubscription = _paymentService.UpdateSubscriptionPlan(existingGift.StripeCustomerId,
                                                                                    stripeSubscription.Id,
                                                                                    plan.Id,
                                                                                    oldSubscription.TrialEnd);
                    }
                    else
                    {
                        // Otherwise, we need to cancel the old Subscription and create a new one
                        oldSubscription = _paymentService.CancelSubscription(existingGift.StripeCustomerId, stripeSubscription.Id);
                        stripeSubscription = _paymentService.CreateSubscription(plan.Id, existingGift.StripeCustomerId, editGift.StartDate);
                    }

                    // In either case, we created a new Stripe Plan above, so cancel the old one
                    _paymentService.CancelPlan(oldSubscription.Plan.Id);
                }

                // Cancel the old recurring gift, and create a new one
                _mpDonorService.CancelRecurringGift(authorizedUserToken, recurringGiftId);
                var contact = _mpContactService.GetContactById(donor.ContactId);
                var congregation = contact.Congregation_ID ?? 5;

                recurringGiftId = _mpDonorService.CreateRecurringGiftRecord(authorizedUserToken,
                                                                            donor.DonorId,
                                                                            donorAccountId,
                                                                            EnumMemberSerializationUtils.ToEnumString(editGift.PlanInterval),
                                                                            editGift.PlanAmount,
                                                                            editGift.StartDate,
                                                                            editGift.Program,
                                                                            stripeSubscription.Id,
                                                                            congregation);

            }

            // Get the new/updated recurring gift so we can return a DTO with all the new values
            var newGift = _mpDonorService.GetRecurringGiftById(authorizedUserToken, recurringGiftId);

            var newRecurringGift = new RecurringGiftDto
            {
                RecurringGiftId = newGift.RecurringGiftId.GetValueOrDefault(),
                StartDate = newGift.StartDate.GetValueOrDefault(),
                PlanAmount = newGift.Amount,
                PlanInterval = newGift.Frequency == RecurringGiftFrequencyWeekly ? PlanInterval.Weekly : PlanInterval.Monthly,
                Program = newGift.ProgramId,
                DonorID = newGift.DonorId,
                EmailAddress = donor.Email,
                SubscriptionID = stripeSubscription.Id,
            };

            SendRecurringGiftConfirmationEmail(authorizedUserToken, _recurringGiftUpdateEmailTemplateId, newGift);

            return (newRecurringGift);
        }
Example #14
0
        public int CreateRecurringGift(string authorizedUserToken, RecurringGiftDto recurringGiftDto, ContactDonor contactDonor)
        {
            StripeCustomer customer = null;
            StripePlan plan = null;
            StripeSubscription stripeSubscription = null;
            var donorAccountId = -1;
            var recurGiftId = -1;

            try
            {

                customer = _paymentService.CreateCustomer(recurringGiftDto.StripeTokenId, string.Format("{0}, Recurring Gift Subscription", contactDonor.DonorId));

                var source = customer.sources.data.Find(s => s.id == customer.default_source);

                donorAccountId = _mpDonorService.CreateDonorAccount(source.brand,
                                                                        DonorRoutingNumberDefault,
                                                                        string.IsNullOrWhiteSpace(source.bank_last4) ? source.last4 : source.bank_last4,
                                                                        null,
                                                                        contactDonor.DonorId,
                                                                        source.id,
                                                                        customer.id);

                plan = _paymentService.CreatePlan(recurringGiftDto, contactDonor);

                stripeSubscription = _paymentService.CreateSubscription(plan.Id, customer.id, recurringGiftDto.StartDate);

                var contact = _mpContactService.GetContactById(contactDonor.ContactId);
                var congregation = contact.Congregation_ID ?? _notSiteSpecificCongregation;

                recurGiftId = _mpDonorService.CreateRecurringGiftRecord(authorizedUserToken,
                                                                            contactDonor.DonorId,
                                                                            donorAccountId,
                                                                            EnumMemberSerializationUtils.ToEnumString(recurringGiftDto.PlanInterval),
                                                                            recurringGiftDto.PlanAmount,
                                                                            recurringGiftDto.StartDate,
                                                                            recurringGiftDto.Program,
                                                                            stripeSubscription.Id,
                                                                            congregation);

                SendRecurringGiftConfirmationEmail(authorizedUserToken, _recurringGiftSetupEmailTemplateId, null, recurGiftId);

                return recurGiftId;
            }
            catch (Exception e)
            {
                // "Rollback" any updates
                _logger.Warn(string.Format("Error setting up recurring gift for donor {0}", contactDonor.DonorId), e);
                if (stripeSubscription != null)
                {
                    _logger.Debug(string.Format("Deleting Stripe Subscription {0} for donor {1}", stripeSubscription.Id, contactDonor.DonorId));
                    try
                    {
                        _paymentService.CancelSubscription(customer.id, stripeSubscription.Id);
                    }
                    catch (Exception ex)
                    {
                        _logger.Warn(string.Format("Error deleting Stripe Subscription {0} for donor {1}", stripeSubscription.Id, contactDonor.DonorId), ex);
                    }
                }

                if (plan != null)
                {
                    _logger.Debug(string.Format("Deleting Stripe Plan {0} for donor {1}", plan.Id, contactDonor.DonorId));
                    try
                    {
                        _paymentService.CancelPlan(plan.Id);
                    }
                    catch (Exception ex)
                    {
                        _logger.Warn(string.Format("Error deleting Stripe Plan {0} for donor {1}", plan.Id, contactDonor.DonorId), ex);
                    }
                }

                if (customer != null)
                {
                    _logger.Debug(string.Format("Deleting Stripe Customer {0} for donor {1}", customer.id, contactDonor.DonorId));
                    try
                    {
                        _paymentService.DeleteCustomer(customer.id);
                    }
                    catch (Exception ex)
                    {
                        _logger.Warn(string.Format("Error deleting Stripe Customer {0} for donor {1}", customer.id, contactDonor.DonorId), ex);
                    }
                }

                if (donorAccountId != -1)
                {
                    _logger.Debug(string.Format("Deleting Donor Account {0} for donor {1}", donorAccountId, contactDonor.DonorId));
                    try
                    {
                        _mpDonorService.DeleteDonorAccount(authorizedUserToken, donorAccountId);
                    }
                    catch (Exception ex)
                    {
                        _logger.Warn(string.Format("Error deleting Donor Account {0} for donor {1}", donorAccountId, contactDonor.DonorId), ex);
                    }
                }

                if (recurGiftId != -1)
                {
                    _logger.Debug(string.Format("Deleting Recurring Gift {0} for donor {1}", recurGiftId, contactDonor.DonorId));
                    try
                    {
                        _mpDonorService.CancelRecurringGift(authorizedUserToken, recurGiftId);
                    }
                    catch (Exception ex)
                    {
                        _logger.Warn(string.Format("Error deleting Recurring Gift {0} for donor {1}", recurGiftId, contactDonor.DonorId), ex);
                    }
                }

                throw;
            }
        }
        public void TestCreatePlan()
        {
            const int expectedTrialDays = 3;
            var recurringGiftDto = new RecurringGiftDto
            {
                StripeTokenId = "tok_123",
                PlanAmount = 123.45M,
                PlanInterval = PlanInterval.Weekly,
                Program = "987",
                StartDate = DateTime.Now.AddDays(expectedTrialDays)
            };
            var interval = EnumMemberSerializationUtils.ToEnumString(recurringGiftDto.PlanInterval);

            var contactDonor = new ContactDonor
            {
                DonorId = 678,
                ProcessorId = "cus_123"
            };

            var stripePlan = new StripePlan();

            var stripeResponse = new Mock<IRestResponse<StripePlan>>(MockBehavior.Strict);
            stripeResponse.SetupGet(mocked => mocked.ResponseStatus).Returns(ResponseStatus.Completed).Verifiable();
            stripeResponse.SetupGet(mocked => mocked.StatusCode).Returns(HttpStatusCode.OK).Verifiable();
            stripeResponse.SetupGet(mocked => mocked.Data).Returns(stripePlan).Verifiable();

            _restClient.Setup(mocked => mocked.Execute<StripePlan>(It.IsAny<IRestRequest>())).Returns(stripeResponse.Object);

            var response = _fixture.CreatePlan(recurringGiftDto, contactDonor);
            _restClient.Verify(mocked => mocked.Execute<StripePlan>(It.Is<IRestRequest>(o =>
                o.Method == Method.POST
                && o.Resource.Equals("plans")
                && o.Parameters.Matches("amount", (int)(recurringGiftDto.PlanAmount * Constants.StripeDecimalConversionValue))
                && o.Parameters.Matches("interval", interval)
                && o.Parameters.Matches("name", "Donor ID #" + contactDonor.DonorId + " " + interval + "ly")
                && o.Parameters.Matches("currency", "usd")
                && o.Parameters.Matches("id", contactDonor.DonorId + " " + DateTime.Now))));

            Assert.AreSame(stripePlan, response);
        }