Product controller, model, viewmodels (Before Inventory relation)

PHOTO EMBED

Fri Aug 09 2024 12:13:33 GMT+0000 (Coordinated Universal Time)

Saved by @iamkatmakhafola

//controller
namespace av_motion_api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly AppDbContext _appContext;
        public readonly IRepository _repository;
        public ProductController(AppDbContext _context, IRepository repository)
        {

            _appContext = _context;
            _repository = repository;
        }
        // GET: api/<ProductController>
        [HttpGet]
        [Route("GetAllProducts")]
        public async Task<IActionResult> GetAllProducts()
        {
            try
            {
                var products = await _appContext.Products.ToListAsync();

                return Ok(products);
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }

        // GET api/<ProductController>/5
        [HttpGet]
        [Route("GetProductById/{id}")]
        public async Task<IActionResult> GetProductById(int id)
        {
            try
            {
                var product = await _appContext.Products.FindAsync(id);
                if (product == null)
                {
                    return NotFound();
                }

                return Ok(product);
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }

        //POST api/<ProductController>
        [HttpPost]
        [DisableRequestSizeLimit]
        [Route("PostProduct")]
        public async Task<IActionResult> PostProduct([FromForm] ProductViewModel product)
        {
            var formCollection = await Request.ReadFormAsync();
            var product_Img = formCollection.Files.FirstOrDefault();

            using (var memoryStream = new MemoryStream())
            {
                await product_Img.CopyToAsync(memoryStream);
                var fileBytes = memoryStream.ToArray();
                string base64Image = Convert.ToBase64String(fileBytes);

                var newProduct = new Product()
                {
                    Product_Name = product.Product_Name,
                    Product_Description = product.Product_Description,
                    Product_Img = base64Image,
                    Quantity = product.Quantity,
                    Unit_Price = product.Unit_Price,
                    Purchase_Price = product.Purchase_Price,
                    Size = product.Size,
                    Product_Category_ID = product.Product_Category_ID,
                };

                if (_appContext.Products == null)
                {
                    return Problem("Entity set 'AppDbContext.Products' is null.");
                }
                _appContext.Products.Add(newProduct);
                await _appContext.SaveChangesAsync();

                return Ok(newProduct);
            }
        }


        // PUT api/<ProductController>/5
        [HttpPut]
        [Route("PutProduct/{id}")]
        public async Task<IActionResult> PutProduct(int id, [FromForm] ProductViewModel updatedProduct)
        {
            var existingProduct = await _appContext.Products.FindAsync(id);
            if (existingProduct == null)
            {
                return NotFound();
            }

            // Read the form data to get the photo file
            var formCollection = await Request.ReadFormAsync();
            var product_Img = formCollection.Files.FirstOrDefault();

            existingProduct.Product_Name = updatedProduct.Product_Name;
            existingProduct.Product_Description = updatedProduct.Product_Description;
            existingProduct.Quantity = updatedProduct.Quantity;
            existingProduct.Unit_Price = updatedProduct.Unit_Price;
            existingProduct.Purchase_Price = updatedProduct.Purchase_Price;
            existingProduct.Size = updatedProduct.Size;
            existingProduct.Product_Category_ID = updatedProduct.Product_Category_ID;

            if (product_Img != null && product_Img.Length > 0)
            {
                using (var memoryStream = new MemoryStream())
                {
                    await product_Img.CopyToAsync(memoryStream);
                    var fileBytes = memoryStream.ToArray();
                    string base64Image = Convert.ToBase64String(fileBytes);

                    existingProduct.Product_Img = base64Image; // Store the base64 string of the photo
                }
            }

            _appContext.Products.Update(existingProduct);
            await _appContext.SaveChangesAsync();

            return Ok(existingProduct);
        }

        // DELETE api/<ProductController>/5
        [HttpDelete]
        [Route("DeleteProduct/{id}")]

        public async Task<IActionResult> DeleteProduct(int id)
        {
            if (_appContext.Products == null)
            {
                return NotFound();
            }
            var product = await _appContext.Products.FindAsync(id);
            if (product == null)
            {
                return NotFound();
            }
            
            _appContext.Products.Remove(product);
            await _appContext.SaveChangesAsync();

            return NoContent();
        }

    }
}

//model
  namespace av_motion_api.Models
{
    public class Product
    {
        [Key]
        public int Product_ID { get; set; }

        [Required, StringLength(100)]
        public string Product_Name { get; set; }

        [Required, StringLength(100)]
        public string Product_Description { get; set; }

        [Required]
        public string Product_Img { get; set; }

        public decimal? Purchase_Price { get; set; }

        [Required]
        public int Quantity { get; set; }

        [Required]
        public decimal Unit_Price { get; set; }

        [Required]
        public string Size { get; set; }

        public int Product_Category_ID { get; set; }

        [ForeignKey(nameof(Product_Category_ID))]
        public Product_Category Product_Category { get; set; }

    }
}

//viewmodel
namespace av_motion_api.ViewModels
{
    public class ProductViewModel
    { 
        public string Product_Name { get; set; }
        public string Product_Description { get; set; }
        public IFormFile Product_Img { get; set; }
        public int Quantity { get; set; }
        public decimal Unit_Price { get; set; }
        public decimal? Purchase_Price { get; set; }
        public string Size { get; set; }
        public int Product_Category_ID { get; set; }
    }
}
content_copyCOPY