public ApiVariant PostVariant(int productId, int variantId, [FromBody] ProductApiPutVariantRequest variantData) { if (!decimal.TryParse(variantData.Quantity, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture.NumberFormat, out var quantity)) { throw new ForagerApiException(ForagerApiExceptionCode.InvalidNumberFormat); } var existingProduct = context.Products.Include(p => p.Variants).SingleOrDefault(f => f.Id == productId); if (existingProduct == null) { throw new ForagerApiException(ForagerApiExceptionCode.ProductNotFound); } var existingVariant = existingProduct.Variants.SingleOrDefault(v => v.Id == variantId); if (existingVariant == null) { throw new ForagerApiException(ForagerApiExceptionCode.VariantNotFound); } var currentUserEmail = userInformation.GetUserEmail(); var currentUser = context.GetUserByEmail(currentUserEmail); existingVariant.Brand = variantData.Brand.Trim(); existingVariant.Description = variantData.Description?.Trim(); existingVariant.Quantity = quantity; existingVariant.Container = variantData.Container?.Trim(); context.SaveChanges(); var variant = ApiVariant.FromVariant(existingVariant); return(variant); }
public ApiVariant PutVariant(int productId, [FromBody] ProductApiPutVariantRequest variantData) { if (!decimal.TryParse(variantData.Quantity, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture.NumberFormat, out var quantity)) { throw new ForagerApiException(ForagerApiExceptionCode.InvalidNumberFormat); } var existingProduct = context.Products.Find(productId); if (existingProduct == null) { throw new ForagerApiException(ForagerApiExceptionCode.ProductNotFound); } var currentUserEmail = userInformation.GetUserEmail(); var currentUser = context.GetUserByEmail(currentUserEmail); var dataVariant = new Variant() { Brand = variantData.Brand.Trim(), Description = variantData.Description?.Trim(), Quantity = quantity, Container = variantData.Container?.Trim(), CreatedBy = currentUser, CreatedOn = DateTime.Now }; existingProduct.Variants.Add(dataVariant); context.SaveChanges(); var variant = ApiVariant.FromVariant(dataVariant); return(variant); }