private async Task SyncCompanyAsync(DomainCompany company, JObject subscriptionPlans, DateTime? syncDate = null)
        {
            syncDate = syncDate ?? DateTime.UtcNow.AddMinutes(-1); // just to be sure that all transactions were committed
            List<CompanySubscription> subscriptions = company.Subscriptions.Where(s => s.State == ResourceState.Available).ToList();
            List<Task> subscriptionTasks = subscriptions.Select(s => SyncSubscriptionAsync(company.Id, s, syncDate.Value, subscriptionPlans)).ToList();

            await Task.WhenAll(subscriptionTasks);
        }
        public void TestInaccauntableClicks()
        {
            // 1. Arrange

            // config
            _config.Setup(x => x.SubscriptionPlans)
                .Returns(
                    () =>
                        JObject.Parse(
                            "{ 0: { syncPeriodMs: 0, cyclePeriodMs: 0, clickRates: { 0: 0 } }, 1: { syncPeriodMs: 60000, cyclePeriodMs: 2592000000, clickRates: { 0: 0, 20: 10 } }, 2: { syncPeriodMs: 2592000000, cyclePeriodMs: 2592000000, clickRates: { 0: 0, 100000: 0.05, 1000000: 0.01 } }, 3: { syncPeriodMs: 2592000000, cyclePeriodMs: 2592000000, clickRates: { 0: 0, 100000: 0.05, 1000000: 0.01 } } }"));
            _config.Setup(x => x.BillingInvoiceItemDescriptionTemplate).Returns(() => "{0}");

            // stats service
            var stas = new List<TrackingStatEntity>
            {
                new TrackingStatEntity { Date = new DateTime(2014, 6, 4, 14, 28, 35, 596) },
                new TrackingStatEntity { Date = new DateTime(2014, 6, 4, 14, 28, 36, 995) },
                new TrackingStatEntity { Date = new DateTime(2014, 6, 4, 14, 28, 41, 889) },
                new TrackingStatEntity { Date = new DateTime(2014, 6, 4, 14, 28, 44, 249) },
                new TrackingStatEntity { Date = new DateTime(2014, 6, 4, 14, 28, 48, 335) }
            };
            _statService.Setup(x => x.GetTotalAsync(It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns<string, DateTime?, DateTime?>((i, f, t) =>
            {
                IQueryable<TrackingStatEntity> r = stas.AsQueryable();
                if (f.HasValue)
                {
                    r = r.Where(s => s.Date >= f.Value);
                }

                if (t.HasValue)
                {
                    r = r.Where(s => s.Date < t.Value);
                }

                return Task.FromResult(r.LongCount());
            });

            // company service
            var company = new DomainCompany
            {
                State = ResourceState.Available,
                Subscriptions = new List<CompanySubscription>
                {
                    new CompanySubscription
                    {
                        State = ResourceState.Available,
                        Type = SubscriptionType.Basic,
                        Created = new DateTime(2014, 6, 4, 14, 25, 14, 133),
                        LastSyncDate = null,
                        LastCycleDate = new DateTime(2014, 6, 4, 14, 27, 37, 939),
                        HasTrialClicks = false
                    }
                }
            };
            var companies = new List<DomainCompany> { company };
            _companyService.Setup(x => x.ListAsync()).Returns(() => Task.FromResult(companies.AsEnumerable()));

            // balance service
            var balance = new DomainBalanceHistory();
            _balanceService.Setup(x => x.AddAsync(It.IsAny<DomainBalanceHistory>())).Returns<DomainBalanceHistory>(b =>
            {
                balance = b;
                return Task.FromResult(balance);
            });


            // 2. Act
            var syncDate = new DateTime(2014, 6, 4, 14, 28, 37, 939);
            _syncManager.SyncAsync(syncDate).Wait();


            // 3. Assert
            long actualCount = Int64.Parse(balance.Description);
            Assert.AreEqual(2, actualCount);
        }
Ejemplo n.º 3
0
        public async Task<ActionResult> ActivateClient(string code)
        {
            DomainPendingClient model;

            try
            {
                model = await _pendingClientService.GetAndDeleteAsync(code);
            }
            catch (NotFoundException)
            {
                return (ActionResult)RedirectToAction("Index", "Home");
            }
            catch (Exception e)
            {
                Trace.TraceError("Failed to find client: {0}", e);
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }

            // Add profile
            var user = new DomainUser
            {
                ApplicationName = AppName,
                Name = model.ContactPerson,
                Country = model.Country,
                UserAgent = _productIdExtractor.Get(Request.UserAgent),
                Email = model.Email,
                Roles = new List<string> { DomainRoles.Client }
            };

            try
            {
                user = await _userService.AddAsync(user);
            }
            catch (ConflictException)
            {
                return new HttpStatusCodeResult(HttpStatusCode.Conflict);
            }
            catch (Exception e)
            {
                Trace.TraceError("Failed to create user profile for {0}: {1}", model.Email, e);
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }

            // Set user password
            try
            {
                await _passwordService.SetPasswordAsync(user.Id, model.Password, model.PasswordSalt);
            }
            catch (Exception e)
            {
                Trace.TraceError("Failed to set user {0} password: {1}", user.Id, e);
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }

            // Add company
            var company = new DomainCompany
            {
                Email = model.Email,
                Name = model.CompanyName,
                Address = model.Address,
                ZipCode = model.ZipCode,
                Phone = model.PhoneNumber,
                Country = model.Country,
                Ein = model.Ein,
                Users = new List<string> { user.Id }
            };

            try
            {
                await _companyService.AddAsync(company);
            }
            catch (Exception e)
            {
                Trace.TraceError("Failed to create company for user {0}: {1}", user.Id, e);
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }

            // Authenticate
            await _authenticationService.SetUserAsync(user, null, true);

            return RedirectToRoute(RouteNames.ClientSubscriptions);
        }
Ejemplo n.º 4
0
        public async Task<DomainCompany> AddAsync(DomainCompany company)
        {
            company.Created = DateTime.UtcNow;
            company.Email = company.Email.ToLowerInvariant();

            CompanyEntity entity = _mapper.Map<DomainCompany, CompanyEntity>(company);

            // Creating customer in billing system
            var customerCreateOptions = new DomainCustomerCreateOptions
            {
                Email = entity.Email
            };

            DomainCustomer customer;
            try
            {
                customer = await _billingCustomerService.AddAsync(customerCreateOptions);
            }
            catch (BillingException e)
            {
                throw new BadRequestException(string.Format("Failed to register customer {0}: {1}", entity.Email, e));
            }

            entity.BillingCustomerId = customer.Id;
            entity = await _companyRepository.AddAsync(entity);

            return _mapper.Map<CompanyEntity, DomainCompany>(entity);
        }
        public async Task SendPaymentNotificationAsync(DomainEvent billingEvent, DomainCompany company, DomainCharge charge)
        {
            if (billingEvent == null)
            {
                throw new ArgumentNullException("billingEvent");
            }

            if (company == null)
            {
                throw new ArgumentNullException("company");
            }

            if (charge == null)
            {
                throw new ArgumentNullException("charge");
            }

            if (!_settings.EmailNotifications)
            {
                return;
            }

            var email = new SendEmailDomain
            {
                Address = _settings.EmailAddressAlerts,
                DisplayName = Emails.SenderDisplayName,
                Emails = new List<string> { company.Email }
            };

            switch (billingEvent.Type)
            {
                case EventType.ChargeFailed:
                    email.Subject = Emails.SubjectPaymentFailed;
                    email.Body = string.Format(
                        PortalResources.PaymentFailed,
                        company.Name,
                        billingEvent.Id,
                        string.Format("{0} {1}", charge.AmountInCents*0.01, charge.Currency),
                        charge.Created);
                    break;

                case EventType.ChargeSucceeded:
                    email.Subject = Emails.SubjectPaymentCompleted;
                    email.Body = string.Format(
                        PortalResources.PaymentCompleted,
                        company.Name,
                        billingEvent.Id,
                        string.Format("{0} {1}", charge.AmountInCents*0.01, charge.Currency),
                        charge.Created);
                    break;

                case EventType.ChargeRefunded:
                    email.Subject = Emails.SubjectPaymentRefunded;
                    email.Body = string.Format(
                        PortalResources.PaymentRefunded,
                        company.Name,
                        billingEvent.Id,
                        string.Format("{0} {1}", charge.AmountInCents*0.01, charge.Currency),
                        charge.Created);
                    break;

                default:
                    return;
            }


            // Send email on user registration
            await _emailSenderService.SendEmailAsync(email);
        }