Beispiel #1
0
        public async Task CanCreateUpdateRemoveAsync()
        {
            Assert.Equal(0, await _repository.CountAsync());

            var organization = new Organization {
                Name = "Test Organization", PlanId = BillingManager.FreePlan.Id
            };

            Assert.Null(organization.Id);

            await _repository.AddAsync(organization);

            await _configuration.Client.RefreshAsync(Indices.All);

            Assert.NotNull(organization.Id);

            organization = await _repository.GetByIdAsync(organization.Id);

            Assert.NotNull(organization);

            organization.Name = "New organization";
            await _repository.SaveAsync(organization);

            await _repository.RemoveAsync(organization.Id);
        }
        public async Task CanCreateUpdateRemoveAsync()
        {
            Assert.Equal(0, await _repository.CountAsync());

            var organization = new Organization {
                Name = "Test Organization", PlanId = _plans.FreePlan.Id
            };

            Assert.Null(organization.Id);

            await _repository.AddAsync(organization);

            await RefreshDataAsync();

            Assert.NotNull(organization.Id);

            organization = await _repository.GetByIdAsync(organization.Id);

            Assert.NotNull(organization);

            organization.Name = "New organization";
            await _repository.SaveAsync(organization);

            await _repository.RemoveAsync(organization.Id);
        }
        public async Task <Organization> CreateAsync(string name)
        {
            var organization = new Organization {
                Name = name
            };

            await organizationRepository.AddAsync(organization);

            await dataContext.SaveChangesAsync();

            return(organization);
        }
        public async Task CreateOrganizationAndProjectAsync(User user)
        {
            if (await _tokenRepository.ExistsAsync(TEST_API_KEY).AnyContext())
            {
                return;
            }

            var organization = new Organization {
                Id = TEST_ORG_ID, Name = "Acme"
            };

            _billingManager.ApplyBillingPlan(organization, _billingPlans.UnlimitedPlan, user);
            organization = await _organizationRepository.AddAsync(organization, o => o.ImmediateConsistency().Cache()).AnyContext();

            var project = new Project {
                Id                       = TEST_PROJECT_ID,
                Name                     = "Disintegrating Pistol",
                OrganizationId           = organization.Id,
                NextSummaryEndOfDayTicks = SystemClock.UtcNow.Date.AddDays(1).AddHours(1).Ticks
            };

            project.Configuration.Settings.Add("IncludeConditionalData", "true");
            project.AddDefaultNotificationSettings(user.Id);
            project = await _projectRepository.AddAsync(project, o => o.ImmediateConsistency().Cache()).AnyContext();

            await _tokenRepository.AddAsync(new List <Token>()
            {
                new Token {
                    Id             = TEST_API_KEY,
                    OrganizationId = organization.Id,
                    ProjectId      = project.Id,
                    CreatedUtc     = SystemClock.UtcNow,
                    UpdatedUtc     = SystemClock.UtcNow,
                    Type           = TokenType.Access
                },
                new Token {
                    Id         = TEST_USER_API_KEY,
                    UserId     = user.Id,
                    CreatedUtc = SystemClock.UtcNow,
                    UpdatedUtc = SystemClock.UtcNow,
                    Type       = TokenType.Access
                }
            }, o => o.ImmediateConsistency().Cache()).AnyContext();

            user.OrganizationIds.Add(organization.Id);
            await _userRepository.SaveAsync(user, o => o.ImmediateConsistency().Cache()).AnyContext();

            _logger.LogDebug("Created Organization {OrganizationName} and Project {ProjectName}", organization.Name, project.Name);
        }
Beispiel #5
0
        public async Task <string> Handle(OrganizationCreateCommand request, CancellationToken cancellationToken)
        {
            var organ = new Organization(Enumeration.FromValue <OrganizationType>(request.OrganizationTypeId), request.Name, request.Description, request.Mail, request.Phone, identityService.GetUserId(), identityService.GetOrganizationId());
            await organRepository.AddAsync(organ);

            return(organ.Id);
        }
Beispiel #6
0
 private Task CreateOrganizationAndProjectsAsync()
 {
     return(Task.WhenAll(
                _organizationRepository.AddAsync(OrganizationData.GenerateSampleOrganizations(), o => o.ImmediateConsistency()),
                _projectRepository.AddAsync(ProjectData.GenerateSampleProjects(), o => o.ImmediateConsistency())
                ));
 }
        public async Task HandleAsync(OrganizationCreated @event)
        {
            var organization = await _organizationRepository.GetAsync(@event.UserId, @event.Name);

            if (organization.HasValue)
            {
                return;
            }

            await _organizationRepository.AddAsync(new OrganizationDto
            {
                Id          = @event.OrganizationId,
                Name        = @event.Name,
                Description = @event.Description,
                OwnerId     = @event.UserId,
                Users       = new List <UserInOrganizationDto>
                {
                    new UserInOrganizationDto
                    {
                        UserId    = @event.UserId,
                        Email     = @event.UserEmail,
                        Role      = @event.UserOrganizationRole,
                        CreatedAt = @event.UserCreatedAt
                    }
                },
                Wardens = new List <WardenDto>()
            });
        }
Beispiel #8
0
        public async Task CreateAsync(Guid id, string userId, string name, string description = "")
        {
            if (name.Empty())
            {
                throw new ServiceException("Organization name can not be empty.");
            }

            var userValue = await _userRepository.GetAsync(userId);

            if (userValue.HasNoValue)
            {
                throw new ServiceException($"User has not been found for given id: '{userId}'.");
            }

            var organizationValue = await _organizationRepository.GetAsync(name, userId);

            if (organizationValue.HasValue)
            {
                throw new ServiceException($"There's already an organization with name: '{name}' " +
                                           $"for user with id: '{userId}'.");
            }

            var organization = new Organization(id, name, userValue.Value, description);
            await _organizationRepository.AddAsync(organization);
        }
 public async Task HandleAsync(OrganizationCreated @event)
 {
     await _handler
     .Run(async() =>
     {
         var organization = await _groupServiceClient.GetOrganizationAsync <Organization>(@event.OrganizationId);
         organization.Value.GroupsCount  = organization.Value.Groups?.Count ?? 0;
         organization.Value.MembersCount = organization.Value.Members?.Count ?? 0;
         await _organizationRepository.AddAsync(organization.Value);
         await _organizationCache.AddAsync(organization.Value);
         var owner = organization.Value.Members.First(x => x.Role == "owner");
         var user  = await _userRepository.GetByIdAsync(owner.UserId);
         if (user.Value.Organizations == null)
         {
             user.Value.Organizations = new HashSet <UserOrganization>();
         }
         user.Value.Organizations.Add(new UserOrganization
         {
             Id       = organization.Value.Id,
             Name     = organization.Value.Name,
             Role     = owner.Role,
             IsActive = owner.IsActive
         });
         await _userRepository.EditAsync(user.Value);
         await _userCache.AddAsync(user.Value);
     })
     .OnError((ex, logger) =>
     {
         logger.Error(ex, $"Error occured while handling {@event.GetType().Name} event");
     })
     .ExecuteAsync();
 }
Beispiel #10
0
 private Task CreateTestOrganizationAndProjectsAsync()
 {
     return(Task.WhenAll(
                _organizationRepository.AddAsync(OrganizationData.GenerateSampleOrganizations(GetService <BillingManager>(), GetService <BillingPlans>()), o => o.ImmediateConsistency()),
                _projectRepository.AddAsync(ProjectData.GenerateSampleProjects(), o => o.ImmediateConsistency())
                ));
 }
 public async Task HandleAsync(OrganizationCreated @event)
 {
     await _handler
     .Run(async() => await _organizationRepository.AddAsync(
              new Organization(@event.OrganizationId, @event.Name, @event.UserId)))
     .OnError((ex, logger) => logger.Error("Error occured while creating an Organization."))
     .ExecuteAsync();
 }
        public async Task CreateOrganizationAndProjectsAsync()
        {
            await _organizationRepository.AddAsync(OrganizationData.GenerateSampleOrganizations());

            await _projectRepository.AddAsync(ProjectData.GenerateSampleProjects());

            await _configuration.Client.RefreshAsync(Indices.All);
        }
Beispiel #13
0
        public async Task CreateOrganizationAndProjectAsync(string userId)
        {
            if (await _tokenRepository.GetByIdAsync(TEST_API_KEY).AnyContext() != null)
            {
                return;
            }

            User user = await _userRepository.GetByIdAsync(userId, true).AnyContext();

            var organization = new Organization {
                Id = TEST_ORG_ID, Name = "Acme"
            };

            BillingManager.ApplyBillingPlan(organization, BillingManager.UnlimitedPlan, user);
            organization = await _organizationRepository.AddAsync(organization, true).AnyContext();

            var project = new Project {
                Id = TEST_PROJECT_ID, Name = "Disintegrating Pistol", OrganizationId = organization.Id
            };

            project.NextSummaryEndOfDayTicks = SystemClock.UtcNow.Date.AddDays(1).AddHours(1).Ticks;
            project.Configuration.Settings.Add("IncludeConditionalData", "true");
            project.AddDefaultOwnerNotificationSettings(userId);
            project = await _projectRepository.AddAsync(project, true).AnyContext();

            await _tokenRepository.AddAsync(new Token {
                Id             = TEST_API_KEY,
                OrganizationId = organization.Id,
                ProjectId      = project.Id,
                CreatedUtc     = SystemClock.UtcNow,
                ModifiedUtc    = SystemClock.UtcNow,
                Type           = TokenType.Access
            }).AnyContext();

            await _tokenRepository.AddAsync(new Token {
                Id          = TEST_USER_API_KEY,
                UserId      = user.Id,
                CreatedUtc  = SystemClock.UtcNow,
                ModifiedUtc = SystemClock.UtcNow,
                Type        = TokenType.Access
            }).AnyContext();

            user.OrganizationIds.Add(organization.Id);
            await _userRepository.SaveAsync(user, true).AnyContext();
        }
    public async Task CanCleanupSoftDeletedOrganization()
    {
        var organization = OrganizationData.GenerateSampleOrganization(_billingManager, _plans);

        organization.IsDeleted = true;
        await _organizationRepository.AddAsync(organization, o => o.ImmediateConsistency());

        var project = await _projectRepository.AddAsync(ProjectData.GenerateSampleProject(), o => o.ImmediateConsistency());

        var stack = await _stackRepository.AddAsync(StackData.GenerateSampleStack(), o => o.ImmediateConsistency());

        var persistentEvent = await _eventRepository.AddAsync(EventData.GenerateEvent(organization.Id, project.Id, stack.Id), o => o.ImmediateConsistency());

        await _job.RunAsync();

        Assert.Null(await _organizationRepository.GetByIdAsync(organization.Id, o => o.IncludeSoftDeletes()));
        Assert.Null(await _projectRepository.GetByIdAsync(project.Id, o => o.IncludeSoftDeletes()));
        Assert.Null(await _stackRepository.GetByIdAsync(stack.Id, o => o.IncludeSoftDeletes()));
        Assert.Null(await _eventRepository.GetByIdAsync(persistentEvent.Id, o => o.IncludeSoftDeletes()));
    }
        public async Task HandleAsync(OrganizationCreated @event)
        {
            var organization = await _organizationRepository.GetAsync(@event.UserId, @event.Name);

            if (organization.HasValue)
            {
                return;
            }

            await _organizationRepository.AddAsync(new Organization(@event.OrganizationId,
                                                                    @event.Name, @event.UserId));
        }
        public async Task AddSampleOrganizationsAsync()
        {
            if (_sampleOrganizationsAdded)
            {
                return;
            }

            await _organizationRepository.AddAsync(OrganizationData.GenerateSampleOrganizations());

            await _client.RefreshAsync();

            _sampleOrganizationsAdded = true;
        }
Beispiel #17
0
        public async Task <IActionResult> Post(OrganizationDto org)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var orgToInsert = _mapper.Map <Organization>(org);
            await _organizationRepository.AddAsync(orgToInsert);

            await _unitOfWork.SaveChangesAsync();

            return(Ok(orgToInsert));
        }
        public async Task CreateAsync(Guid id, string name, string userId,
                                      bool isPublic, IDictionary <string, ISet <string> > criteria)
        {
            if (await ExistsAsync(name))
            {
                throw new ServiceException(OperationCodes.OrganizationNameInUse,
                                           $"Organization with name: '{name}' already exists.");
            }
            var user = await _userRepository.GetAsync(userId);

            var owner        = Member.Owner(user.Value.UserId, user.Value.Name);
            var organization = new Organization(id, name, owner, isPublic, criteria);
            await _organizationRepository.AddAsync(organization);
        }
        private async Task CreateDataAsync()
        {
            await _client.RefreshAsync();

            foreach (Organization organization in OrganizationData.GenerateSampleOrganizations())
            {
                if (organization.Id == TestConstants.OrganizationId3)
                {
                    BillingManager.ApplyBillingPlan(organization, BillingManager.FreePlan, UserData.GenerateSampleUser());
                }
                else
                {
                    BillingManager.ApplyBillingPlan(organization, BillingManager.SmallPlan, UserData.GenerateSampleUser());
                }

                organization.StripeCustomerId = Guid.NewGuid().ToString("N");
                organization.CardLast4        = "1234";
                organization.SubscribeDate    = DateTime.Now;

                if (organization.IsSuspended)
                {
                    organization.SuspendedByUserId = TestConstants.UserId;
                    organization.SuspensionCode    = SuspensionCode.Billing;
                    organization.SuspensionDate    = DateTime.Now;
                }

                await _organizationRepository.AddAsync(organization, true);
            }

            await _projectRepository.AddAsync(ProjectData.GenerateSampleProjects(), true);

            foreach (User user in UserData.GenerateSampleUsers())
            {
                if (user.Id == TestConstants.UserId)
                {
                    user.OrganizationIds.Add(TestConstants.OrganizationId2);
                    user.OrganizationIds.Add(TestConstants.OrganizationId3);
                }

                if (!user.IsEmailAddressVerified)
                {
                    user.CreateVerifyEmailAddressToken();
                }

                await _userRepository.AddAsync(user, true);
            }

            await _client.RefreshAsync();
        }
Beispiel #20
0
        private async Task CreateDataAsync(int eventCount = 100, bool multipleProjects = true)
        {
            var orgs = OrganizationData.GenerateSampleOrganizations();
            await _organizationRepository.AddAsync(orgs);

            var projects = ProjectData.GenerateSampleProjects();
            await _projectRepository.AddAsync(projects);

            var events = EventData.GenerateEvents(eventCount, projectIds: multipleProjects ? projects.Select(p => p.Id).ToArray() : new[] { TestConstants.ProjectId }, startDate: DateTimeOffset.UtcNow.SubtractDays(60), endDate: DateTimeOffset.UtcNow);

            foreach (var eventGroup in events.GroupBy(ev => ev.ProjectId))
            {
                await _eventPipeline.RunAsync(eventGroup);
            }
        }
        private async Task CreateDataAsync(int eventCount = 0, bool multipleProjects = true)
        {
            var orgs = OrganizationData.GenerateSampleOrganizations(_billingManager, _plans);
            await _organizationRepository.AddAsync(orgs, o => o.Cache());

            var projects = ProjectData.GenerateSampleProjects();
            await _projectRepository.AddAsync(projects, o => o.Cache());

            await _configuration.Client.RefreshAsync(Indices.All);

            if (eventCount > 0)
            {
                await CreateEventsAsync(eventCount, multipleProjects?projects.Select(p => p.Id).ToArray() : new[] { TestConstants.ProjectId });
            }
        }
Beispiel #22
0
        private async Task CreateDataAsync()
        {
            foreach (var organization in OrganizationData.GenerateSampleOrganizations(_billingManager, _plans))
            {
                if (organization.Id == TestConstants.OrganizationId3)
                {
                    _billingManager.ApplyBillingPlan(organization, _plans.FreePlan, UserData.GenerateSampleUser());
                }
                else
                {
                    _billingManager.ApplyBillingPlan(organization, _plans.SmallPlan, UserData.GenerateSampleUser());
                }

                organization.StripeCustomerId = Guid.NewGuid().ToString("N");
                organization.CardLast4        = "1234";
                organization.SubscribeDate    = SystemClock.UtcNow;

                if (organization.IsSuspended)
                {
                    organization.SuspendedByUserId = TestConstants.UserId;
                    organization.SuspensionCode    = SuspensionCode.Billing;
                    organization.SuspensionDate    = SystemClock.UtcNow;
                }

                await _organizationRepository.AddAsync(organization, o => o.Cache());
            }

            await _projectRepository.AddAsync(ProjectData.GenerateSampleProjects(), o => o.Cache());

            foreach (var user in UserData.GenerateSampleUsers())
            {
                if (user.Id == TestConstants.UserId)
                {
                    user.OrganizationIds.Add(TestConstants.OrganizationId2);
                    user.OrganizationIds.Add(TestConstants.OrganizationId3);
                }

                if (!user.IsEmailAddressVerified)
                {
                    user.CreateVerifyEmailAddressToken();
                }

                await _userRepository.AddAsync(user, o => o.Cache());
            }

            await _configuration.Client.RefreshAsync(Indices.All);
        }
Beispiel #23
0
 public async Task HandleAsync(OrganizationCreated @event)
 {
     await _handler
     .Run(async() =>
     {
         var organization = await _groupServiceClient.GetOrganizationAsync <Organization>(@event.OrganizationId);
         organization.Value.GroupsCount  = organization.Value.Groups?.Count ?? 0;
         organization.Value.MembersCount = organization.Value.Members?.Count ?? 0;
         await _organizationRepository.AddAsync(organization.Value);
         await _cache.AddAsync(organization.Value);
     })
     .OnError((ex, logger) =>
     {
         logger.Error(ex, $"Error occured while handling {@event.GetType().Name} event");
     })
     .ExecuteAsync();
 }
Beispiel #24
0
        private async Task CreateDataAsync(int eventCount = 0, bool multipleProjects = true)
        {
            await _client.RefreshAsync();

            var orgs = OrganizationData.GenerateSampleOrganizations();
            await _organizationRepository.AddAsync(orgs, true);

            var projects = ProjectData.GenerateSampleProjects();
            await _projectRepository.AddAsync(projects, true);

            await _client.RefreshAsync();

            if (eventCount > 0)
            {
                await CreateEventsAsync(eventCount, multipleProjects?projects.Select(p => p.Id).ToArray() : new[] { TestConstants.ProjectId });
            }
        }
Beispiel #25
0
        public async Task <Unit> Handle(RegisterOrganizationCommand request, CancellationToken cancellationToken)
        {
            var user = await _service.GetbyId(request.UserId);

            if (user == null)
            {
                throw new OrganizationException("User doesn't exists", HttpErrorCodes.ResourceNotFound, InternalErrorCodes.OrganizationDoesntExits);
            }
            var organization = await _repository.GetbyName(request.OrganizationName);

            if (organization != null)
            {
                throw new OrganizationException("Organization name is taken", HttpErrorCodes.ResourceNotFound, InternalErrorCodes.UserDoesntExists);
            }
            var organizationToAdd = Organization.Create(request.OrgnizationId, request.OrganizationName,
                                                        user.Id, user.Email, user.DisplayName);

            await _repository.AddAsync(organizationToAdd);

            return(Unit.Value);
        }
Beispiel #26
0
        public async Task CreateTestOrganizationAsync(string userId, string organizationId, string organizationName, string apiKey, string userApiKey)
        {
            if (await _tokenRepository.GetByIdAsync(apiKey).AnyContext() != null)
            {
                return;
            }

            var user = await _userRepository.GetByIdAsync(userId, true).AnyContext();

            var organization = new Organization {
                Id = organizationId, Name = organizationName
            };

            organization = await _organizationRepository.AddAsync(organization).AnyContext();

            await _tokenRepository.AddAsync(new Token
            {
                Id             = apiKey,
                OrganizationId = organization.Id,
                CreatedUtc     = DateTime.UtcNow,
                UpdatedUtc     = DateTime.UtcNow,
                Type           = TokenType.Access
            }).AnyContext();

            await _tokenRepository.AddAsync(new Token
            {
                Id             = userApiKey,
                UserId         = user.Id,
                OrganizationId = organization.Id,
                CreatedUtc     = DateTime.UtcNow,
                UpdatedUtc     = DateTime.UtcNow,
                Type           = TokenType.Access
            }).AnyContext();

            user.AddAdminMembership(organization.Id);
            await _userRepository.SaveAsync(user, true).AnyContext();
        }
        public async Task <IActionResult> Index(IndexViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var email = user.Email;

            if (model.Email != email)
            {
                // Update to identity user.
                var setEmailResult = await _userManager.SetEmailAsync(user, model.Email); // this update to dbo.AspNetUsers

                if (!setEmailResult.Succeeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'.");
                }

                // Update to UserClaims (dbo.AspNetUserClaims)
                var claimKeyValuePairs = new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("Email", model.Email),
                };

                var identityResult = await _claimsHelper.AddOrReplaceClaimsAsync(user, claimKeyValuePairs);
            }

            var phoneNumber = user.PhoneNumber;

            if (model.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, model.PhoneNumber);

                if (!setPhoneResult.Succeeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting phone number for user with ID '{user.Id}'.");
                }

                var claimKeyValuePairs = new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("PhoneNumber", model.PhoneNumber),
                };

                var identityResult = await _claimsHelper.AddOrReplaceClaimsAsync(user, claimKeyValuePairs);
            }

            if (!string.IsNullOrEmpty(model.OrganizationName))
            {
                var organization = _organizationRepository.GetAll().FirstOrDefault(p => p.Name.ToLower() == model.OrganizationName.ToLower());

                if (organization == null)
                {
                    // Create new organization
                    var orgId = Guid.NewGuid().ToString();
                    organization = await _organizationRepository.AddAsync(new Organization()
                    {
                        Id   = orgId,
                        Name = model.OrganizationName
                    });
                }

                if (organization.Id != user.OrgId)
                {
                    // Write update to dbo.Organizations and dbo.AspNetUsers.
                    user.OrgId = organization.Id;
                    var result = await _userManager.UpdateAsync(user);

                    if (result.Errors.Any())
                    {
                        throw new ApplicationException($"Unexpected error occurred setting OrgId for user with ID '{user.Id}'.");
                    }
                }

                // Add or replace claim
                var claimKeyValuePairs = new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("OrgId", user.OrgId),
                };
                var identityResult = await _claimsHelper.AddOrReplaceClaimsAsync(user, claimKeyValuePairs);
            }

            StatusMessage = "Your profile has been updated";
            return(RedirectToAction(nameof(Index)));
        }
Beispiel #28
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            //#if !DEBUG
            context.Database.Migrate();

            #region 创建默认组织和用户
            {
                var softWareOrgan = await organizationRepository.FindAsync(DomainEntityDefaultIdConst.SoftwareProviderOrganizationId);

                //await organizationRepository.Entry(softWareOrgan).Collection(x => x.OwnAccounts).LoadAsync();

                if (softWareOrgan == null)
                {
                    var softwareProviderOrgan = new Organization(OrganizationType.ServiceProvider, appConfig.SoftwareProviderSettings.Name, "默认组织", appConfig.SoftwareProviderSettings.Mail, appConfig.SoftwareProviderSettings.Phone, DomainEntityDefaultIdConst.SoftwareProviderAdminId);
                    softwareProviderOrgan.CustomizeId(DomainEntityDefaultIdConst.SoftwareProviderOrganizationId);
                    await organizationRepository.AddAsync(softwareProviderOrgan);
                }
            }

            #endregion

            #region 创建默认的权限点
            var hasProductManagement = await accessPointRepository.Get(new PointKeyUniqueCheckSpecification(AccessPointInnerPointKeyConst.ProductBasicInfoManagement)).AnyAsync();

            if (!hasProductManagement)
            {
                var accPoint = new AccessPoint("AccessPoint.ProductBasicInfoManagement", AccessPointInnerPointKeyConst.ProductBasicInfoManagement, string.Empty, new List <int> {
                    OrganizationType.Brand.Id
                });
                accPoint.SignInner();
                await accessPointRepository.AddAsync(accPoint);
            }

            var hasRetrievePrice = await accessPointRepository.Get(new PointKeyUniqueCheckSpecification(AccessPointInnerPointKeyConst.PriceRetrieve)).AnyAsync();

            if (!hasRetrievePrice)
            {
                var accPoint = new AccessPoint("AccessPoint.RetrievePrice", AccessPointInnerPointKeyConst.PriceRetrieve, string.Empty, new List <int> {
                    OrganizationType.Brand.Id
                });
                accPoint.SignInner();
                await accessPointRepository.AddAsync(accPoint);
            }

            var hasEditPrice = await accessPointRepository.Get(new PointKeyUniqueCheckSpecification(AccessPointInnerPointKeyConst.PriceEdit)).AnyAsync();

            if (!hasEditPrice)
            {
                var accPoint = new AccessPoint("AccessPoint.PriceEdit", AccessPointInnerPointKeyConst.PriceEdit, string.Empty, new List <int> {
                    OrganizationType.Brand.Id
                });
                accPoint.SignInner();
                await accessPointRepository.AddAsync(accPoint);
            }

            var hasRetrievePartnerPrice = await accessPointRepository.Get(new PointKeyUniqueCheckSpecification(AccessPointInnerPointKeyConst.PartnerPriceRetrieve)).AnyAsync();

            if (!hasRetrievePartnerPrice)
            {
                var accPoint = new AccessPoint("AccessPoint.RetrievePartnerPrice", AccessPointInnerPointKeyConst.PartnerPriceRetrieve, string.Empty, new List <int> {
                    OrganizationType.Brand.Id, OrganizationType.Partner.Id
                });
                accPoint.SignInner();
                await accessPointRepository.AddAsync(accPoint);
            }

            var hasEditPartnerPrice = await accessPointRepository.Get(new PointKeyUniqueCheckSpecification(AccessPointInnerPointKeyConst.PartnerPriceEdit)).AnyAsync();

            if (!hasEditPartnerPrice)
            {
                var accPoint = new AccessPoint("AccessPoint.PartnerPriceEdit", AccessPointInnerPointKeyConst.PartnerPriceEdit, string.Empty, new List <int> {
                    OrganizationType.Brand.Id
                });
                accPoint.SignInner();
                await accessPointRepository.AddAsync(accPoint);
            }

            var hasRetrievePurchasePrice = await accessPointRepository.Get(new PointKeyUniqueCheckSpecification(AccessPointInnerPointKeyConst.PurchasePriceRetrieve)).AnyAsync();

            if (!hasRetrievePurchasePrice)
            {
                var accPoint = new AccessPoint("AccessPoint.RetrievePurchasePrice", AccessPointInnerPointKeyConst.PurchasePriceRetrieve, string.Empty, new List <int> {
                    OrganizationType.Brand.Id, OrganizationType.Supplier.Id
                });
                accPoint.SignInner();
                await accessPointRepository.AddAsync(accPoint);
            }

            var hasEditPurchasePrice = await accessPointRepository.Get(new PointKeyUniqueCheckSpecification(AccessPointInnerPointKeyConst.PurchasePriceEdit)).AnyAsync();

            if (!hasEditPurchasePrice)
            {
                var accPoint = new AccessPoint("AccessPoint.PurchasePriceEdit", AccessPointInnerPointKeyConst.PurchasePriceEdit, string.Empty, new List <int> {
                    OrganizationType.Brand.Id
                });
                accPoint.SignInner();
                await accessPointRepository.AddAsync(accPoint);
            }

            var hasClientAssetManagement = await accessPointRepository.Get(new PointKeyUniqueCheckSpecification(AccessPointInnerPointKeyConst.ClientAssetManagement)).AnyAsync();

            if (!hasClientAssetManagement)
            {
                var accPoint = new AccessPoint("AccessPoint.ClientAssetManagement", AccessPointInnerPointKeyConst.ClientAssetManagement, string.Empty, new List <int> {
                    OrganizationType.Brand.Id
                });
                accPoint.SignInner();
                await accessPointRepository.AddAsync(accPoint);
            }



            #endregion
            //#endif
        }
        public async Task CanIncrementUsageAsync()
        {
            var messageBus = GetService <IMessageBus>();

            var countdown = new AsyncCountdownEvent(2);
            await messageBus.SubscribeAsync <PlanOverage>(po => {
                _logger.Info($"Plan Overage for {po.OrganizationId} (Hourly: {po.IsHourly})");
                countdown.Signal();
            });

            var o = await _organizationRepository.AddAsync(new Organization { Name = "Test", MaxEventsPerMonth = 750, PlanId = BillingManager.SmallPlan.Id });

            var project = await _projectRepository.AddAsync(new Project { Name = "Test", OrganizationId = o.Id, NextSummaryEndOfDayTicks = SystemClock.UtcNow.Ticks }, opt => opt.Cache());

            await _configuration.Client.RefreshAsync(Indices.All);

            Assert.InRange(o.GetHourlyEventLimit(), 1, 750);

            int totalToIncrement = o.GetHourlyEventLimit() - 1;

            Assert.False(await _usageService.IncrementUsageAsync(o.Id, project.Id, false, totalToIncrement));
            await _configuration.Client.RefreshAsync(Indices.All);

            o = await _organizationRepository.GetByIdAsync(o.Id);

            await countdown.WaitAsync(TimeSpan.FromMilliseconds(150));

            Assert.Equal(2, countdown.CurrentCount);
            Assert.Equal(totalToIncrement, await _cache.GetAsync <long>(GetHourlyTotalCacheKey(o.Id), 0));
            Assert.Equal(totalToIncrement, await _cache.GetAsync <long>(GetHourlyTotalCacheKey(o.Id, project.Id), 0));
            Assert.Equal(totalToIncrement, await _cache.GetAsync <long>(GetMonthlyTotalCacheKey(o.Id), 0));
            Assert.Equal(totalToIncrement, await _cache.GetAsync <long>(GetMonthlyTotalCacheKey(o.Id, project.Id), 0));
            Assert.Equal(0, await _cache.GetAsync <long>(GetHourlyBlockedCacheKey(o.Id), 0));
            Assert.Equal(0, await _cache.GetAsync <long>(GetHourlyBlockedCacheKey(o.Id, project.Id), 0));
            Assert.Equal(0, await _cache.GetAsync <long>(GetMonthlyBlockedCacheKey(o.Id), 0));
            Assert.Equal(0, await _cache.GetAsync <long>(GetMonthlyBlockedCacheKey(o.Id, project.Id), 0));

            Assert.True(await _usageService.IncrementUsageAsync(o.Id, project.Id, false, 2));
            await _configuration.Client.RefreshAsync(Indices.All);

            o = await _organizationRepository.GetByIdAsync(o.Id);

            await countdown.WaitAsync(TimeSpan.FromMilliseconds(150));

            Assert.Equal(1, countdown.CurrentCount);
            Assert.Equal(totalToIncrement + 2, await _cache.GetAsync <long>(GetHourlyTotalCacheKey(o.Id), 0));
            Assert.Equal(totalToIncrement + 2, await _cache.GetAsync <long>(GetHourlyTotalCacheKey(o.Id, project.Id), 0));
            Assert.Equal(totalToIncrement + 2, await _cache.GetAsync <long>(GetMonthlyTotalCacheKey(o.Id), 0));
            Assert.Equal(totalToIncrement + 2, await _cache.GetAsync <long>(GetMonthlyTotalCacheKey(o.Id, project.Id), 0));
            Assert.Equal(1, await _cache.GetAsync <long>(GetHourlyBlockedCacheKey(o.Id), 0));
            Assert.Equal(1, await _cache.GetAsync <long>(GetHourlyBlockedCacheKey(o.Id, project.Id), 0));
            Assert.Equal(1, await _cache.GetAsync <long>(GetMonthlyBlockedCacheKey(o.Id), 0));
            Assert.Equal(1, await _cache.GetAsync <long>(GetMonthlyBlockedCacheKey(o.Id, project.Id), 0));

            o = await _organizationRepository.AddAsync(new Organization { Name = "Test", MaxEventsPerMonth = 750, PlanId = BillingManager.SmallPlan.Id });

            project = await _projectRepository.AddAsync(new Project { Name = "Test", OrganizationId = o.Id, NextSummaryEndOfDayTicks = SystemClock.UtcNow.Ticks }, opt => opt.Cache());

            await _configuration.Client.RefreshAsync(Indices.All);

            await _cache.RemoveAllAsync();

            totalToIncrement = o.GetHourlyEventLimit() + 20;
            Assert.True(await _usageService.IncrementUsageAsync(o.Id, project.Id, false, totalToIncrement));

            await countdown.WaitAsync(TimeSpan.FromMilliseconds(150));

            Assert.Equal(0, countdown.CurrentCount);
            Assert.Equal(totalToIncrement, await _cache.GetAsync <long>(GetHourlyTotalCacheKey(o.Id), 0));
            Assert.Equal(totalToIncrement, await _cache.GetAsync <long>(GetHourlyTotalCacheKey(o.Id, project.Id), 0));
            Assert.Equal(totalToIncrement, await _cache.GetAsync <long>(GetMonthlyTotalCacheKey(o.Id), 0));
            Assert.Equal(totalToIncrement, await _cache.GetAsync <long>(GetMonthlyTotalCacheKey(o.Id, project.Id), 0));
            Assert.Equal(20, await _cache.GetAsync <long>(GetHourlyBlockedCacheKey(o.Id), 0));
            Assert.Equal(20, await _cache.GetAsync <long>(GetHourlyBlockedCacheKey(o.Id, project.Id), 0));
            Assert.Equal(20, await _cache.GetAsync <long>(GetMonthlyBlockedCacheKey(o.Id), 0));
            Assert.Equal(20, await _cache.GetAsync <long>(GetMonthlyBlockedCacheKey(o.Id, project.Id), 0));
        }
Beispiel #30
0
    public async Task CanIncrementUsageAsync()
    {
        var messageBus = GetService <IMessageBus>();

        var countdown = new AsyncCountdownEvent(2);
        await messageBus.SubscribeAsync <PlanOverage>(po => {
            _logger.LogInformation("Plan Overage for {organization} (Hourly: {IsHourly})", po.OrganizationId, po.IsHourly);
            countdown.Signal();
        });

        var organization = await _organizationRepository.AddAsync(new Organization { Name = "Test", MaxEventsPerMonth = 750, PlanId = _plans.SmallPlan.Id }, o => o.ImmediateConsistency());

        var project = await _projectRepository.AddAsync(new Project { Name = "Test", OrganizationId = organization.Id, NextSummaryEndOfDayTicks = SystemClock.UtcNow.Ticks }, o => o.ImmediateConsistency());

        Assert.InRange(organization.GetHourlyEventLimit(_plans), 1, 750);

        int totalToIncrement = organization.GetHourlyEventLimit(_plans) - 1;

        Assert.False(await _usageService.IncrementUsageAsync(organization, project, totalToIncrement));
        organization = await _organizationRepository.GetByIdAsync(organization.Id);

        await countdown.WaitAsync(TimeSpan.FromMilliseconds(150));

        Assert.Equal(2, countdown.CurrentCount);
        var organizationUsage = await _usageService.GetUsageAsync(organization);

        var projectUsage = await _usageService.GetUsageAsync(organization, project);

        Assert.Equal(totalToIncrement, organizationUsage.HourlyTotal);
        Assert.Equal(totalToIncrement, projectUsage.HourlyTotal);
        Assert.Equal(totalToIncrement, organizationUsage.MonthlyTotal);
        Assert.Equal(totalToIncrement, projectUsage.MonthlyTotal);
        Assert.Equal(0, organizationUsage.HourlyBlocked);
        Assert.Equal(0, projectUsage.HourlyBlocked);
        Assert.Equal(0, organizationUsage.MonthlyBlocked);
        Assert.Equal(0, projectUsage.MonthlyBlocked);

        Assert.True(await _usageService.IncrementUsageAsync(organization, project, 2));
        await countdown.WaitAsync(TimeSpan.FromMilliseconds(150));

        Assert.Equal(1, countdown.CurrentCount);

        organizationUsage = await _usageService.GetUsageAsync(organization);

        projectUsage = await _usageService.GetUsageAsync(organization, project);

        Assert.Equal(totalToIncrement + 2, organizationUsage.HourlyTotal);
        Assert.Equal(totalToIncrement + 2, projectUsage.HourlyTotal);
        Assert.Equal(totalToIncrement + 2, organizationUsage.MonthlyTotal);
        Assert.Equal(totalToIncrement + 2, projectUsage.MonthlyTotal);
        Assert.Equal(1, organizationUsage.HourlyBlocked);
        Assert.Equal(1, projectUsage.HourlyBlocked);
        Assert.Equal(1, organizationUsage.MonthlyBlocked);
        Assert.Equal(1, projectUsage.MonthlyBlocked);

        organization = await _organizationRepository.AddAsync(new Organization { Name = "Test", MaxEventsPerMonth = 750, PlanId = _plans.SmallPlan.Id }, o => o.ImmediateConsistency());

        project = await _projectRepository.AddAsync(new Project { Name = "Test", OrganizationId = organization.Id, NextSummaryEndOfDayTicks = SystemClock.UtcNow.Ticks }, o => o.ImmediateConsistency());

        await _cache.RemoveAllAsync();

        totalToIncrement = organization.GetHourlyEventLimit(_plans) + 20;
        Assert.True(await _usageService.IncrementUsageAsync(organization, project, totalToIncrement));

        await countdown.WaitAsync(TimeSpan.FromMilliseconds(150));

        Assert.Equal(0, countdown.CurrentCount);

        organizationUsage = await _usageService.GetUsageAsync(organization);

        projectUsage = await _usageService.GetUsageAsync(organization, project);

        Assert.Equal(totalToIncrement, organizationUsage.HourlyTotal);
        Assert.Equal(totalToIncrement, projectUsage.HourlyTotal);
        Assert.Equal(totalToIncrement, organizationUsage.MonthlyTotal);
        Assert.Equal(totalToIncrement, projectUsage.MonthlyTotal);
        Assert.Equal(20, organizationUsage.HourlyBlocked);
        Assert.Equal(20, projectUsage.HourlyBlocked);
        Assert.Equal(20, organizationUsage.MonthlyBlocked);
        Assert.Equal(20, projectUsage.MonthlyBlocked);
    }