Beispiel #1
0
        public async Task Create_Created()
        {
            //Setup
            var id = Guid.NewGuid();

            var model = new WorkExperienceCreateViewModel
            {
                CompanyName = "Some",
                Description = "Desc",
                StartWork   = DateTimeOffset.Now,
                FinishWork  = DateTimeOffset.Now.AddDays(1),
                ProfileId   = Guid.NewGuid()
            };

            var serviceMock        = new Mock <IWorkExperienceService>();
            var profileServiceMock = new Mock <IProfileService>();

            serviceMock
            .Setup(x => x.CreateAsync(model.CompanyName, model.Description, model.StartWork, model.FinishWork,
                                      model.ProfileId))
            .ReturnsAsync((DomainResult.Success(), id));

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => serviceMock.Object);
                collection.AddScoped(_ => profileServiceMock.Object);
            });

            //Act
            var response = await client.PostAsync($"/WorkExperiences", model.AsJsonContent());

            //Assert
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
        }
        public async Task <IDomainResult <BacklogItemReference> > Update <T>(string id, T dto) where T : BacklogItemAddUpdRequestBase
        {
            var entity = await DbSession.LoadAsync <BacklogItem>(GetFullId(id));

            if (entity == null)
            {
                return(DomainResult.NotFound <BacklogItemReference>());
            }

            var(_, status) = dto switch
            {
                BugAddUpdRequest bug => await _dtoToEntityConversion.ConvertToEntity(bug, entity as BacklogItemBug),
                UserStoryAddUpdRequest story => await _dtoToEntityConversion.ConvertToEntity(story, entity as BacklogItemUserStory),
                TaskAddUpdRequest task => await _dtoToEntityConversion.ConvertToEntity(task, entity as BacklogItemTask),
                FeatureAddUpdRequest feature => await _dtoToEntityConversion.ConvertToEntity(feature, entity as BacklogItemFeature),
                _ => throw new ArgumentException($"Unsupported type ${typeof(T)}", nameof(dto))
            };
            if (!status.IsSuccess)
            {
                return(status.To <BacklogItemReference>());
            }

            var ticketRef = entity.ToReference().RemoveEntityPrefixFromId();

            await UpdateRelatedItems(dto, ticketRef);

            return(DomainResult.Success(ticketRef));
        }
Beispiel #3
0
        public async Task <IDomainResult <BacklogItemCommentReference> > Update(string backlogItemId, string commentId, string message)
        {
            var ticketRes = await GetEntity(backlogItemId);

            if (!ticketRes.IsSuccess)
            {
                return(ticketRes.To <BacklogItemCommentReference>());
            }
            var ticket = ticketRes.Value;

            var comment = ticket.Comments.SingleOrDefault(c => c.Id == commentId);

            if (comment == null)
            {
                return(DomainResult.NotFound <BacklogItemCommentReference>("Comment not found"));
            }

            var currentUser = await _userResolver.GetCurrentUserReference();

            if (comment.Author.Id != currentUser.Id)
            {
                return(DomainResult.Unauthorized <BacklogItemCommentReference>("Cannot edit comments of other users"));
            }

            var mentionedUsers = await _mentionedUserResolver.GetMentionedUsers(message);

            comment.Message          = message;
            comment.MentionedUserIds = mentionedUsers.Any() ? mentionedUsers : null;
            comment.LastModified     = DateTime.UtcNow;

            ticket.AddHistoryRecord(currentUser, "Updated a comment");

            return(DomainResult.Success(GetCommentReference(ticket.Id, commentId, message)));
        }
Beispiel #4
0
        public async Task Update_NotFound()
        {
            // Setup
            const string commentId = "someId";
            var          model     = new UpdateCommentModel
            {
                Content = "New Content"
            };

            DomainResult domainResult = DomainResult.Success();

            var serviceMock = new Mock <ICommentsService>();

            serviceMock.Setup(s => s.UpdateAsync(commentId, model.Content)).ReturnsAsync(domainResult);
            serviceMock.Setup(s => s.GetByIdAsync(commentId)).ReturnsAsync(default(Comment));

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => serviceMock.Object);
            });

            // Act
            var response = await client.PutAsync($"comments/{commentId}", model.AsJsonContent());

            Assert.AreEqual(response.StatusCode, HttpStatusCode.NotFound);
        }
Beispiel #5
0
        /// <inheritdoc/>
        public async Task <IDomainResult <BacklogItemGetResponseBase> > GetById(string id, BacklogItemCommentListGetRequest? @params = null)
        {
            @params ??= new BacklogItemCommentListGetRequest();

            var fullId = GetFullId(id);

            var ticket = await DbSession.LoadAsync <BacklogItem>(fullId);

            if (ticket == null)
            {
                return(DomainResult.NotFound <BacklogItemGetResponseBase>());
            }

            var comments      = GetCommentsList(ticket, @params);
            var pagedComments = (comments?.Any() == true) ? new ListResponse <BacklogItemCommentListGetResponse>(comments, ticket.Comments.Count, @params.PageIndex, @params.PageSize) : null;

            var dto = (ticket.Type) switch
            {
                BacklogItemType.Bug => (ticket as BacklogItemBug)?.ConvertToDto <BacklogItemBug, BugGetResponse>(pagedComments) as  BacklogItemGetResponseBase,
                BacklogItemType.UserStory => (ticket as BacklogItemUserStory)?.ConvertToDto <BacklogItemUserStory, UserStoryGetResponse>(pagedComments) as BacklogItemGetResponseBase,
                _ => throw new NotImplementedException($"Not supported Backlog Item Type: {ticket.Type}"),
            };

            if (dto == null)
            {
                throw new NotSupportedException($"Failed to return Backlog Item type of {ticket.Type}");
            }

            return(DomainResult.Success(dto));
        }
        public async Task <IDomainResult <BacklogItemReference> > Delete(string shortId)
        {
            var ticket = await DbSession.LoadAsync <BacklogItem>(GetFullId(shortId));

            if (ticket == null)
            {
                return(DomainResult.NotFound <BacklogItemReference>());
            }

            DbSession.Delete(ticket);

            // Remove references to the ticket from 'Related Items' of other tickets
            if (ticket.RelatedItems.Any())
            {
                foreach (var item in ticket.RelatedItems)
                {
                    DbSession.Advanced.Patch <BacklogItem, BacklogItemRelatedItem>(GetFullId(item.RelatedTo.Id !),
                                                                                   x => x.RelatedItems,
                                                                                   items => items.RemoveAll(i => i.RelatedTo.Id == shortId));
                }
            }

            return(DomainResult.Success(
                       ticket.ToReference().RemoveEntityPrefixFromId()
                       ));
        }
Beispiel #7
0
        public async Task <DomainResult> UpsertAsync(
            Guid userId,
            SecuritySettingsSection publications,
            SecuritySettingsSection friends)
        {
            var profile = await profileStorage.FindByIdAsync(userId);

            if (profile == null)
            {
                return(DomainResult.Error("User not found"));
            }

            var securitySettings = await securitySettingsStorage.FindByUserIdAsync(userId);

            if (securitySettings == null)
            {
                securitySettings = new SecuritySetting(userId, publications, friends);
            }
            else
            {
                securitySettings.Update(publications, friends);
            }

            await securitySettingsStorage.UpsertAsync(securitySettings);

            return(DomainResult.Success());
        }
Beispiel #8
0
        private DomainResult Validate(DateTimeOffset?date, string firstName, string lastName, string gender)
        {
            List <DomainError> results = new List <DomainError>();

            if (firstName == null || firstName.Length > 150 || string.IsNullOrEmpty(firstName))
            {
                results.Add(new DomainError($"{nameof(firstName)} can not be null, empty or more than 150 chars"));
            }

            if (lastName == null || lastName.Length > 150 || string.IsNullOrEmpty(lastName))
            {
                results.Add(new DomainError($"{nameof(lastName)} can not be null, empty or more than 150 chars"));
            }

            if (gender != null && (gender.Length > 150 || string.IsNullOrEmpty(gender)))
            {
                results.Add(new DomainError($"{nameof(gender)} can not be empty or more than 150 chars"));
            }

            if (date != null && date > DateTime.Now)
            {
                results.Add(new DomainError("Date is greater than date now"));
            }

            return(!results.Any() ? DomainResult.Success() : DomainResult.Error(results));
        }
Beispiel #9
0
        public async Task <IDomainResult <BacklogItemCommentReference> > Create(string backlogItemId, string message)
        {
            var ticketRes = await GetEntity(backlogItemId);

            if (!ticketRes.IsSuccess)
            {
                return(ticketRes.To <BacklogItemCommentReference>());
            }
            var ticket = ticketRes.Value;

            var mentionedUsers = await _mentionedUserResolver.GetMentionedUsers(message);

            var currentUser = await _userResolver.GetCurrentUserReference();

            var comment = new Comment
            {
                Author           = currentUser,
                Message          = message,
                MentionedUserIds = mentionedUsers.Any() ? mentionedUsers : null,
            };

            ticket.Comments.Add(comment);

            ticket.AddHistoryRecord(currentUser, "Added a comment");

            return(DomainResult.Success(GetCommentReference(ticket.Id, comment.Id, message)));
        }
Beispiel #10
0
        public async Task Update_NoContent()
        {
            // Setup
            var id    = "some_id";
            var input = new UpdatePublicationModel
            {
                Content = "some content"
            };

            var publication = new Publication(id, input.Content, Enumerable.Empty <string>(), null, DateTimeOffset.Now, DateTimeOffset.Now);

            var serviceMock = new Mock <IPublicationService>();

            serviceMock
            .Setup(s => s.UpdateAsync(id, input.Content))
            .ReturnsAsync(DomainResult.Success());

            serviceMock
            .Setup(s => s.GetByIdAsync(id))
            .ReturnsAsync(publication);

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(provider => serviceMock.Object);
            });

            // Act
            var response = await client.PutAsync($"/publications/{id}/", input.AsJsonContent());

            // Assert
            Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode);
        }
Beispiel #11
0
        public async Task <IDomainResult <BacklogItemReference> > AssignToUser(string backlogItemId, string?userShortenId)
        {
            var backlogItem = await DbSession.LoadAsync <BacklogItem>(GetFullId(backlogItemId));

            if (backlogItem == null)
            {
                return(DomainResult.NotFound <BacklogItemReference>("The Backlog Item not found"));
            }

            if (userShortenId == null)
            {
                backlogItem.Assignee = null;
            }
            else
            {
                var userRef = await _userResolver.GetReferenceById(userShortenId);

                if (userRef == null)
                {
                    return(DomainResult.NotFound <BacklogItemReference>("The user not found"));
                }

                backlogItem.Assignee = userRef;
            }

            backlogItem.AddHistoryRecord(await _userResolver.GetCurrentUserReference(), "Assigned a user");

            return(DomainResult.Success(
                       backlogItem.ToReference().RemoveEntityPrefixFromId()
                       ));
        }
Beispiel #12
0
        public async Task <IDomainResult <BacklogItemCommentReference> > Delete(string backlogItemId, string commentId)
        {
            var ticketRes = await GetEntity(backlogItemId);

            if (!ticketRes.IsSuccess)
            {
                return(ticketRes.To <BacklogItemCommentReference>());
            }
            var ticket = ticketRes.Value;

            var comment = ticket.Comments.SingleOrDefault(c => c.Id == commentId);

            if (comment == null)
            {
                return(DomainResult.NotFound <BacklogItemCommentReference>("Comment not found"));
            }

            var currentUser = await _userResolver.GetCurrentUserReference();

            if (comment.Author.Id != currentUser.Id)
            {
                return(DomainResult.Unauthorized <BacklogItemCommentReference>("Cannot delete comments of other users"));
            }

            ticket.Comments.Remove(comment);

            ticket.AddHistoryRecord(currentUser, "Deleted a comment");

            return(DomainResult.Success(GetCommentReference(ticket.Id, null, comment.Message)));
        }
        public void Successful_IDomainResultOfT_Converts_To_IDomainResultOfV()
        {
            var domainResult    = DomainResult.Success(10);
            var domainResultOfT = domainResult.To <char>();

            Assert.True(domainResultOfT.IsSuccess);
            Assert.Equal(default(char), domainResultOfT.Value);
        }
        public void Successful_IDomainResult_Converts_To_IDomainResultOfT()
        {
            var domainResult    = DomainResult.Success();
            var domainResultOfT = domainResult.To <int>();

            Assert.True(domainResultOfT.IsSuccess);
            Assert.Equal(0, domainResultOfT.Value);
        }
Beispiel #15
0
        public async Task <IDomainResult <UserReference> > Create(UserAddUpdRequest dto)
        {
            var user = dto.ConvertToUser();
            await DbSession.StoreAsync(user);

            var response = user.ToReference().RemoveEntityPrefixFromId();

            return(DomainResult.Success(response));
        }
Beispiel #16
0
        private async Task <IDomainResult <BacklogItem> > GetEntity(string id)
        {
            var fullId = GetFullId(id);

            var ticket = await DbSession.LoadAsync <BacklogItem>(fullId);

            return(ticket == null
                                ? DomainResult.NotFound <BacklogItem>("Backlog item not found")
                                : DomainResult.Success(ticket));
        }
        private static object[] GetTestCase <T>(T domainValue, bool genericClass, bool wrapInTask = false)
        => wrapInTask
                                ? new object[]
        {
            genericClass?DomainResult <T> .SuccessTask(domainValue) : DomainResult.SuccessTask(domainValue)
        }

                                : new object[] {
            genericClass?DomainResult <T> .Success(domainValue) : DomainResult.Success(domainValue)
        };
Beispiel #18
0
        public void DomainResult_Can_Be_Deconstructed_Test()
        {
            var res = DomainResult.Success(10);

            var(value, details) = res;

            Assert.Equal(10, value);
            Assert.IsAssignableFrom <IDomainResult>(details);
            Assert.Equal(DomainOperationStatus.Success, details.Status);
        }
        public void DomainResultConverted_To_NoContent()
        {
            // GIVEN a successful domain result
            var domainRes = DomainResult.Success();

            // WHEN convert it to ActionResult
            var actionRes = domainRes.ToActionResult();

            // THEN the response type is correct
            Assert.IsType <NoContentResult>(actionRes);
        }
Beispiel #20
0
        public async Task <IDomainResult <CustomFieldReferenceDto> > Rename(string id, CustomFieldRenameRequest dto)
        {
            var entity = await DbSession.LoadAsync <CustomField>(GetFullId(id));

            if (entity == null)
            {
                return(DomainResult.NotFound <CustomFieldReferenceDto>());
            }

            entity.Name = dto.Name;

            return(DomainResult.Success(GetReference(entity)));
        }
        public async Task <DomainResult> UpdateAsync(string commentId, string content)
        {
            try
            {
                await commentsApi.UpdateAsync(commentId, new UpdateCommentModel(content));
            }
            catch (ApiException)
            {
                return(DomainResult.Error("API error!"));
            }

            return(DomainResult.Success());
        }
Beispiel #22
0
        public async Task <IDomainResult <UserGetByIdResponse> > GetById(string id)
        {
            var fullId = GetFullId(id);

            var user = await DbSession.LoadAsync <User>(fullId);

            if (user == null)
            {
                return(DomainResult.NotFound <UserGetByIdResponse>());
            }

            return(DomainResult.Success(user.ConvertToUserDto()));
        }
        public async Task <DomainResult> ValidateAsync(Comment comment)
        {
            if (string.IsNullOrEmpty(comment.ReplyCommentId))
            {
                return(DomainResult.Success());
            }

            var parentComment = await commentsStorage.FindOneByIdAsync(comment.ReplyCommentId);

            return(parentComment == null
                ? DomainResult.Error("Parent comment not found")
                : DomainResult.Success());
        }
Beispiel #24
0
        public async Task <IDomainResult <BacklogItemReference> > Delete(string id)
        {
            var ticket = await DbSession.LoadAsync <BacklogItem>(GetFullId(id));

            if (ticket == null)
            {
                return(DomainResult.NotFound <BacklogItemReference>());
            }

            DbSession.Delete(ticket);

            return(DomainResult.Success(
                       ticket.ToReference().RemoveEntityPrefixFromId()
                       ));
        }
Beispiel #25
0
        public async Task <IDomainResult <CustomFieldReferenceDto> > Delete(string id)
        {
            // TODO: Prohibit deletion if there are any references

            var cf = await DbSession.LoadAsync <CustomField>(GetFullId(id));

            if (cf == null)
            {
                return(DomainResult.NotFound <CustomFieldReferenceDto>());
            }

            DbSession.Delete(cf);

            return(DomainResult.Success(GetReference(cf)));
        }
Beispiel #26
0
        public async Task Create_Ok()
        {
            // Setup
            const string commentId     = "commentId";
            const string publicationId = "publicationId";
            const string content       = "asd";
            const string authorId      = "3fa85f64-5717-4562-b3fc-2c963f66afa7";

            var author = new UserInfo(new Guid(authorId), "FName LName", null);

            var model = new CreateCommentModel()
            {
                Key            = publicationId,
                Content        = content,
                ReplyCommentId = null,
                AuthorId       = authorId
            };

            var commentServiceMock = new Mock <ICommentsService>();

            commentServiceMock
            .Setup(s => s.CreateAsync(publicationId, content, null, author))
            .ReturnsAsync((DomainResult.Success(), "commentId"));

            commentServiceMock
            .Setup(s => s.GetByIdAsync(commentId))
            .ReturnsAsync(new Comment(commentId, content, DateTimeOffset.Now, publicationId, null, author));

            var userProvideMock = new Mock <IUserProvider>();

            userProvideMock
            .Setup(s => s.GetByIdAsync(model.AuthorId))
            .ReturnsAsync(author);

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => commentServiceMock.Object);
                collection.AddScoped(_ => userProvideMock.Object);
            });

            // Act
            var response = await client.PostAsync("comments", model.AsJsonContent());

            // Asser
            Assert.AreEqual(response.StatusCode, HttpStatusCode.Created);
        }
Beispiel #27
0
        public async Task <IDomainResult <CustomFieldReferenceDto> > Create(CustomFieldAddRequest dto)
        {
            if (await DbSession.Query <CustomFieldIndexedForList, CustomFields_ForList>()
                .Where(cf => cf.Name == dto.Name)
                .AnyAsync())
            {
                return(DomainResult.Failed <CustomFieldReferenceDto>($"Custom Field with name '{dto.Name}' already exist"));
            }

            var entity = new CustomField
            {
                Name      = dto.Name,
                FieldType = dto.Type
            };
            await DbSession.StoreAsync(entity);

            return(DomainResult.Success(GetReference(entity)));
        }
        public async Task <DomainResult> ValidateAsync(TContext context)
        {
            var errors = new List <DomainError>();

            foreach (var validator in validators)
            {
                var result = await validator.ValidateAsync(context);

                if (!result.Successed)
                {
                    errors.AddRange(result.Errors);
                }
            }

            return(errors.Any()
                ? DomainResult.Error(errors)
                : DomainResult.Success());
        }
        public async Task <IDomainResult <CustomFieldReferenceDto> > Delete(string id)
        {
            var cf = await DbSession.LoadAsync <CustomField>(GetFullId(id));

            if (cf == null)
            {
                return(DomainResult.NotFound <CustomFieldReferenceDto>());
            }

            DbSession.Delete(cf);

            // Delete the ID in all references
            foreach (var clearFieldRef in _clearFieldReferences)
            {
                clearFieldRef.ClearCustomFieldId(id);
            }

            return(DomainResult.Success(GetReference(cf)));
        }
        public async Task <IDomainResult <CustomFieldReferenceDto> > Create(CustomFieldAddRequest dto)
        {
            var verificationResult = await VerifyName(null, dto.Name);

            if (!verificationResult.IsSuccess)
            {
                return(verificationResult.To <CustomFieldReferenceDto>());
            }

            var entity = new CustomField
            {
                Name             = dto.Name,
                FieldType        = dto.FieldType,
                BacklogItemTypes = dto.BacklogItemTypes,
                IsMandatory      = dto.IsMandatory.HasValue && dto.IsMandatory.Value
            };
            await DbSession.StoreAsync(entity);

            return(DomainResult.Success(GetReference(entity)));
        }