Exemplo n.º 1
0
        public async Task <IActionResult> Add([FromForm] ProductAddRequest model)
        {
            Response oR = new Response();

            try
            {
                if (!ModelState.IsValid)
                {
                    oR.Status  = StatusCodes.Status400BadRequest;
                    oR.Message = Messages.ValidationsFailed;
                    oR.Data    = GetModelErrors(ModelState);

                    return(BadRequest(oR));
                }

                if (await _productService.ExistsCode(model.Code))
                {
                    ModelState.AddModelError("Code", Messages.ResourceCodeAlreadyExists);

                    oR.Status  = StatusCodes.Status400BadRequest;
                    oR.Message = Messages.ValidationsFailed;
                    oR.Data    = GetModelErrors(ModelState);

                    return(BadRequest(oR));
                }

                if (!await _subCategoryService.ExistsId(model.SubCategoryId))
                {
                    ModelState.AddModelError("Code", Messages.SubCategoryIdDontExists);

                    oR.Status  = StatusCodes.Status400BadRequest;
                    oR.Message = Messages.ValidationsFailed;
                    oR.Data    = GetModelErrors(ModelState);

                    return(BadRequest(oR));
                }

                var oProduct = await _productService.Add(model);

                if (oProduct != null)
                {
                    oR.Status = StatusCodes.Status201Created;
                    oR.Data   = oProduct;

                    return(CreatedAtAction(nameof(GetById), new { id = oProduct.Id }, oR));
                }
                else
                {
                    oR.Status  = StatusCodes.Status500InternalServerError;
                    oR.Message = Messages.InternalServerError;

                    return(StatusCode(StatusCodes.Status500InternalServerError, oR));
                }
            }
            catch (Exception ex)
            {
                oR.Status  = StatusCodes.Status500InternalServerError;
                oR.Message = Messages.InternalServerError;

                return(StatusCode(StatusCodes.Status500InternalServerError, oR));
            }
        }