public async Task CreateArticle_WithSucceedingCommit_ReturnsStatusCodeNoContent()
        {
            var articleForCreationDto = new ArticleForCreationDto()
            {
                Code              = "New Test Article",
                Name1             = "1st article Updated",
                SupplierId        = "supId",
                SupplierReference = "supRef",
                PurchasePrice     = 99.99M,
                Unit              = "ST"
            };
            var newArticle          = _writeMapper.Map <Article>(articleForCreationDto);
            var articleForReturnDto = _writeMapper.Map <ArticleForReturnDto>(newArticle);

            _createCommandMock.Setup(m => m.Execute(It.IsAny <ArticleForCreationDto>())).Returns(Task.FromResult(articleForReturnDto));

            // act
            var result = await _articlesController.CreateArticle(articleForCreationDto);

            // assert
            _createCommandMock.Verify(m => m.Execute(It.IsAny <ArticleForCreationDto>()), Times.Once);
            Assert.That(result, Is.Not.Null);
            Assert.That(result.GetType(), Is.EqualTo(typeof(CreatedAtRouteResult)));
            Assert.That(((CreatedAtRouteResult)result).StatusCode, Is.EqualTo(201));
            Assert.That(((CreatedAtRouteResult)result).RouteName, Is.EqualTo("GetArticle"));
            Assert.That(((CreatedAtRouteResult)result).RouteValues.First(), Is.EqualTo(new KeyValuePair <string, int>("id", articleForReturnDto.Id)));
            Assert.That(((CreatedAtRouteResult)result).Value, Is.EqualTo(articleForReturnDto));
        }
        public async Task CreateArticle_WithFailingCommit_ReturnsStatusBadRequest()
        {
            var articleForCreationDto = new ArticleForCreationDto()
            {
                Code              = "New Test Article",
                Name1             = "1st article Updated",
                SupplierId        = "supId",
                SupplierReference = "supRef",
                PurchasePrice     = 99.99M,
                Unit              = "ST"
            };
            var newArticle          = _writeMapper.Map <Article>(articleForCreationDto);
            var articleForReturnDto = _writeMapper.Map <ArticleForReturnDto>(newArticle);

            _createCommandMock.Setup(m => m.Execute(It.IsAny <ArticleForCreationDto>())).Returns(Task.FromResult <ArticleForReturnDto>(null));

            // act
            var result = await _articlesController.CreateArticle(articleForCreationDto);

            // assert
            _createCommandMock.Verify(m => m.Execute(It.IsAny <ArticleForCreationDto>()), Times.Once);
            Assert.That(result, Is.Not.Null);
            Assert.That(result.GetType(), Is.EqualTo(typeof(BadRequestObjectResult)));
            Assert.That(((BadRequestObjectResult)result).StatusCode, Is.EqualTo(400));
            Assert.That(((BadRequestObjectResult)result).Value, Is.EqualTo("Failed to create article"));
        }
Ejemplo n.º 3
0
        public async Task Execute(ArticleForCreationDto articleForCreation)
        {
            // TODO mapping via DI !!
            // var newArticle = _mapper.Map<Article>(newArticleDto);
            var newArticle = Domain.Model.Entities.Articles.Article.Create(
                articleForCreation.Code,
                articleForCreation.SupplierId,
                articleForCreation.SupplierReference,
                articleForCreation.Name1,
                articleForCreation.PurchasePrice,
                articleForCreation.Unit
                );

            _unitOfWork.ArticleRepository.Add(newArticle);

            await _unitOfWork.Commit();

            // TODO: handle errors

            //if (await _unitOfWork.Commit())
            //{
            //    var articleToReturn = _mapper.Map<ArticleForReturnDto>(newArticle);
            //    return CreatedAtRoute("GetArticle", new { id = newArticle.Id }, articleToReturn);
            //}

            //return BadRequest("Failed to create article");


            // evt. notifications
        }
Ejemplo n.º 4
0
        public IResult InsertArticle(ArticleForCreationDto articleForCreationDto)
        {
            //TO DO: Implement transaction

            var articleToBeInserted = _mapper.Map <ArticleTranslation>(articleForCreationDto);
            var insertedArticle     = _articleTranslationRepository.Insert(articleToBeInserted);

            articleForCreationDto.Pictures.ForEach(p => p.ArticleId = insertedArticle.ArticleId);

            var result = _pictureService.InsertPicturesForArticle(articleForCreationDto.Pictures);

            if (result.Success)
            {
                var imgRegex = new Regex("<img src=\"(?<url>(data:(?<type>.+?);base64),(?<data>[^\"]+))\"");
                foreach (var picture in result.Data.Where(x => !x.IsMain))
                {
                    insertedArticle.ContentMain = imgRegex.Replace(insertedArticle.ContentMain,
                                                                   m => $"<img src=\"{picture.Url}\"", 1);
                }

                _articleTranslationRepository.Update(insertedArticle);

                return(new SuccessResult(string.Format(Messages.SuccessfulInsert, nameof(Article))));
            }
            else
            {
                return(new ErrorResult($"Picture couldn't be inserted Error Message {result.Message}"));
            }
        }
Ejemplo n.º 5
0
        public IActionResult CreateArticleForProduct(Guid productId, [FromBody] ArticleForCreationDto article)
        {
            if (article == null)
            {
                return(BadRequest());
            }

            if (!_libraryRepository.ProductExists(productId))
            {
                return(NotFound());
            }

            var articleEntity = Mapper.Map <Article>(article);

            _libraryRepository.AddArticleForProduct(productId, articleEntity);

            if (!_libraryRepository.Save())
            {
                throw new Exception("Creating an article failed on save.");
                //return StatusCode(500, "An unexpected fault happened. Try again later.");
            }

            var articleToReturn = Mapper.Map <ArticleDto>(articleEntity);

            return(CreatedAtRoute("GetArticleForProduct", new { productId = productId, id = articleToReturn.Id }, articleToReturn));
        }
        public async Task Create_ValidObject_ReturnsNewArticle()
        {
            //Arrange
            var unitOfWork = new UnitOfWork(TestContext, new ArticleRepository(TestContext), null);

            var articleForCreation = new ArticleForCreationDto()
            {
                Code              = "new code",
                Name1             = "new name",
                SupplierId        = "sup id",
                SupplierReference = "sup ref",
                PurchasePrice     = 99.99M,
                Unit              = "ST",
                PhotoUrl          = "www.retail4u.be/newarticle.jpg"
            };
            var createArticleCommand = new CreateArticleCommand(unitOfWork, _writeMapper);
            var articleCountBefore   = TestContext.Articles.Count();

            //Act
            var result = await createArticleCommand.Execute(articleForCreation);

            //Assert
            Assert.That(result, Is.Not.Null);
            Assert.That(result.GetType(), Is.EqualTo(typeof(ArticleForReturnDto)));
            Assert.That(TestContext.Articles.Count, Is.EqualTo(articleCountBefore + 1));
            Assert.That(result.Id, Is.Not.Null);
            Assert.That(result.Name1, Is.EqualTo(articleForCreation.Name1));
            Assert.That(result.Photos, Is.Not.Null);
            Assert.That(result.Photos.First(), Is.Not.Null);
            Assert.That(result.Photos.First().Url, Is.EqualTo("www.retail4u.be/newarticle.jpg"));
        }
        public async Task Create_InvalidObject_ReturnsNull()
        {
            //Arrange
            var testArticles     = ArticleList.GetDefaultList();
            var articleDbSetMock = testArticles.AsQueryable().BuildMockDbSet();
            var dataContextMock  = new Mock <CommandDbContext>();

            dataContextMock.Setup(m => m.Articles).Returns(articleDbSetMock.Object);
            var articleRepository = new Mock <IArticleRepository>();
            var unitOfWorkMock    = new Mock <IUnitOfWork>();

            unitOfWorkMock.Setup(uow => uow.ArticleRepository).Returns(articleRepository.Object);

            var articleForCreation   = new ArticleForCreationDto();
            var createArticleCommand = new CreateArticleCommand(unitOfWorkMock.Object, _writeMapper);

            unitOfWorkMock.Setup(uow => uow.Commit()).Returns(Task.FromResult(false));

            //Act
            var result = await createArticleCommand.Execute(articleForCreation);

            //Assert
            articleRepository.Verify(r => r.Add(It.IsAny <Article>()), Times.Once);
            Assert.That(result, Is.Null);
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> CreateArticle(ArticleForCreationDto articleForCreationDto)
        {
            var createdArticle = await _createCommand.Execute(articleForCreationDto);

            if (createdArticle != null)
            {
                return(CreatedAtRoute("GetArticle", new { id = createdArticle.Id }, createdArticle));
            }

            return(BadRequest("Failed to create article"));
        }
Ejemplo n.º 9
0
        public IActionResult CreateArticle([FromBody] ArticleForCreationDto articleForCreationDto)
        {
            var articleModel = _mapper.Map <Article>(articleForCreationDto);

            _articleRepository.AddArticle(articleModel);
            _articleRepository.Save();

            var articleReturn = _mapper.Map <ArticleDto>(articleModel);

            return(CreatedAtRoute(
                       "GetArticle",
                       new { articleId = articleReturn.Id },
                       articleReturn
                       ));
        }
        public async Task <IActionResult> CreateArticle(ArticleForCreationDto articleForCreationDto)
        {
            await _createCommand.Execute(articleForCreationDto);

            return(Ok());

            // TODO: handle errors & return correct status

            //if (await _unitOfWork.Commit())
            //{
            //    var articleToReturn = _mapper.Map<ArticleForReturnDto>(newArticle);
            //    return CreatedAtRoute("GetArticle", new { id = newArticle.Id }, articleToReturn);
            //}

            //return BadRequest("Failed to create article");
        }
Ejemplo n.º 11
0
        public async Task PublishArticle_Success()
        {
            var articleDto = new ArticleForCreationDto()
            {
                Title = "test"
            };
            var article = _mapper.Map <Article>(articleDto);

            _articleRepositoryMock.Setup(x => x.AddAsync(article));
            _tagsMock.Setup(x => x.TryCreateManyToMany(It.IsAny <IEnumerable <ArticleTag> >()));
            _tagsMock.Setup(x => x.SaveAsync());

            await _service.PublishArticle(articleDto);

            _tagsMock.Verify(x => x.TryCreateManyToMany(It.IsAny <IEnumerable <ArticleTag> >()), Times.Once());
            _tagsMock.Verify(x => x.SaveAsync(), Times.Once());
        }
Ejemplo n.º 12
0
        public async Task <ActionResult> Create(ArticleForCreationDto article)
        {
            try
            {
                if (article == null)
                {
                    return(BadRequest());
                }
                await _articleService.PublishArticle(article);

                return(NoContent());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Ejemplo n.º 13
0
        public async Task PublishArticle(ArticleForCreationDto articleRequest)
        {
            try
            {
                var article = _mapper.Map <Article>(articleRequest);
                await _articleRepository.AddAsync(article);

                _tags.TryCreateManyToMany(articleRequest.Tags.Select(x => new ArticleTag
                {
                    TagId     = x.Id,
                    ArticleId = article.Id
                }));
                await _tags.SaveAsync();
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(ex.Message);
            }
        }
Ejemplo n.º 14
0
        public async Task <ArticleForReturnDto> Execute(ArticleForCreationDto articleForCreation)
        {
            var newArticle = _mapper.Map <Article>(articleForCreation);

            if (!string.IsNullOrEmpty(articleForCreation.PhotoUrl))
            {
                newArticle.Photos.Add(ArticlePhoto.Create(articleForCreation.PhotoUrl, true));
            }

            _unitOfWork.ArticleRepository.Add(newArticle);

            if (await _unitOfWork.Commit())
            {
                var articleForReturnDto = _mapper.Map <ArticleForReturnDto>(newArticle);
                return(articleForReturnDto);
            }

            return(null);
        }
Ejemplo n.º 15
0
        public ActionResult <ArticleDto> CreateArticleForUser(Guid userId, ArticleForCreationDto article, Guid tagId)
        {
            if (!_articleLibraryRepository.UserExists(userId) ||
                !_tagLibraryRepository.TagExists(tagId))
            {
                return(NotFound());
            }

            var articleEntity = _mapper.Map <Entities.Article>(article);

            _articleLibraryRepository.AddArticle(userId, articleEntity, tagId);
            _articleLibraryRepository.Save();

            var articleToReturn = _mapper.Map <ArticleDto>(articleEntity);

            return(CreatedAtRoute("GetArticleForUser",
                                  new { userId = userId, articleId = articleToReturn.Id },
                                  articleToReturn));
        }
Ejemplo n.º 16
0
        public IActionResult CreateArticleForAuthor(Guid authorId,
                                                    [FromBody] ArticleForCreationDto article)
        {
            if (article == null)
            {
                return(BadRequest());
            }

            if (article.Description == article.Title)
            {
                ModelState.AddModelError(nameof(ArticleForCreationDto),
                                         "The provided description should be different from the title.");
            }

            if (!ModelState.IsValid)
            {
                // return 422
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var articleEntity = Mapper.Map <Article>(article);

            _libraryRepository.AddArticleForAuthor(authorId, articleEntity);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Creating a article for author {authorId} failed on save.");
            }

            var articleToReturn = Mapper.Map <ArticleDto>(articleEntity);

            return(CreatedAtRoute("GetArticleForAuthor",
                                  new { authorId = authorId, id = articleToReturn.Id },
                                  articleToReturn));
        }