Ejemplo n.º 1
0
        public async Task TestCrowdactionCreate()
        {
            var user = await context.Users.FirstAsync();

            var claimsPrincipal = await signInManager.CreateUserPrincipalAsync(user);

            var r = new Random();

            var newCrowdaction =
                new NewCrowdaction()
            {
                Name       = "test" + Guid.NewGuid(),
                Categories = new List <Category>()
                {
                    Category.Other, Category.Health
                },
                Description          = Guid.NewGuid().ToString(),
                DescriptionVideoLink = "https://www.youtube.com/embed/xY0XTysJUDY",
                End             = DateTime.Now.AddDays(30),
                Start           = DateTime.Now.AddDays(10),
                Goal            = Guid.NewGuid().ToString(),
                CreatorComments = Guid.NewGuid().ToString(),
                Proposal        = Guid.NewGuid().ToString(),
                Target          = 40,
                Tags            = new string[3] {
                    $"a{r.Next(1000)}", $"b{r.Next(1000)}", $"c{r.Next(1000)}"
                }
            };
            CrowdactionResult crowdactionResult = await crowdactionService.CreateCrowdaction(newCrowdaction, claimsPrincipal, CancellationToken.None);

            int?crowdactionId = crowdactionResult.Crowdaction?.Id;

            Assert.NotNull(crowdactionId);
            Crowdaction retrievedCrowdaction = await context.Crowdactions.Include(c => c.Tags).ThenInclude(t => t.Tag).FirstOrDefaultAsync(c => c.Id == crowdactionId);

            Assert.NotNull(retrievedCrowdaction);

            Assert.True(crowdactionResult.Succeeded);
            Assert.False(crowdactionResult.Errors.Any());
            Assert.Equal(crowdactionResult.Crowdaction?.Name, retrievedCrowdaction.Name);
            Assert.True(Enumerable.SequenceEqual(crowdactionResult.Crowdaction?.Tags.Select(t => t.Tag.Name).OrderBy(t => t), retrievedCrowdaction.Tags.Select(t => t.Tag.Name).OrderBy(t => t)));
        }
        public async Task <CrowdactionResult> CreateCrowdaction(NewCrowdaction newCrowdaction, ClaimsPrincipal user, CancellationToken token)
        {
            logger.LogInformation("Validating new crowdaction");

            IEnumerable <ValidationResult> validationResults = ValidationHelper.Validate(newCrowdaction, serviceProvider);

            if (validationResults.Any())
            {
                return(new CrowdactionResult(validationResults));
            }

            ApplicationUser?owner = await userManager.GetUserAsync(user).ConfigureAwait(false);

            if (owner == null)
            {
                return(new CrowdactionResult(new ValidationResult("Crowdaction owner could not be found")));
            }

            if (await context.Crowdactions.AnyAsync(c => c.Name == newCrowdaction.Name, token).ConfigureAwait(false))
            {
                return(new CrowdactionResult(new ValidationResult("A crowdaction with this name already exists", new[] { nameof(Crowdaction.Name) })));
            }

            logger.LogInformation("Creating crowdaction: {0}", newCrowdaction.Name);
            var           tagMap = new Dictionary <string, int>();
            List <string> tags   = newCrowdaction.Tags.Distinct().ToList();

            if (tags.Any())
            {
                var missingTags = tags.Except(
                    await context.Tags
                    .Where(t => tags.Contains(t.Name))
                    .Select(t => t.Name)
                    .ToListAsync(token).ConfigureAwait(false))
                                  .Select(t => new Tag(t));

                if (missingTags.Any())
                {
                    context.Tags.AddRange(missingTags);
                    await context.SaveChangesAsync(token).ConfigureAwait(false);
                }

                tagMap = await context.Tags
                         .Where(t => tags.Contains(t.Name))
                         .ToDictionaryAsync(t => t.Name, t => t.Id, token).ConfigureAwait(false);
            }

            List <CrowdactionTag> crowdactionTags =
                tags.Select(t => new CrowdactionTag(tagId: tagMap[t]))
                .ToList();

            var crowdaction = new Crowdaction(
                name: newCrowdaction.Name,
                status: CrowdactionStatus.Hidden,
                ownerId: owner.Id,
                target: newCrowdaction.Target,
                start: newCrowdaction.Start,
                end: newCrowdaction.End.Date.AddHours(23).AddMinutes(59).AddSeconds(59),
                description: newCrowdaction.Description,
                goal: newCrowdaction.Goal,
                proposal: newCrowdaction.Proposal,
                creatorComments: newCrowdaction.CreatorComments,
                descriptionVideoLink: newCrowdaction.DescriptionVideoLink?.Replace("www.youtube.com", "www.youtube-nocookie.com", StringComparison.Ordinal),
                displayPriority: CrowdactionDisplayPriority.Medium,
                bannerImageFileId: newCrowdaction.BannerImageFileId,
                cardImageFileId: newCrowdaction.CardImageFileId,
                descriptiveImageFileId: newCrowdaction.DescriptiveImageFileId,
                categories: newCrowdaction.Categories.Select(c => new CrowdactionCategory((c))).ToList(),
                tags: crowdactionTags);

            context.Crowdactions.Add(crowdaction);
            await context.SaveChangesAsync(token).ConfigureAwait(false);

            await RefreshParticipantCount(token).ConfigureAwait(false);

            await emailSender.SendEmailTemplated(owner.Email, $"Thank you for submitting \"{crowdaction.Name}\" on CollAction", "CrowdactionConfirmation").ConfigureAwait(false);

            IList <ApplicationUser> administrators = await userManager.GetUsersInRoleAsync(AuthorizationConstants.AdminRole).ConfigureAwait(false);

            await emailSender.SendEmailsTemplated(administrators.Select(a => a.Email), $"A new crowdaction was submitted on CollAction: \"{crowdaction.Name}\"", "CrowdactionAddedAdmin", crowdaction.Name).ConfigureAwait(false);

            logger.LogInformation("Created crowdaction: {0}", newCrowdaction.Name);

            return(new CrowdactionResult(crowdaction));
        }