public HttpResponseMessage Post(VariantModel variant) { HttpResponseMessage response; ModelsValidation validation = new ModelsValidation(); VariantData data = new VariantData(); if (ModelState.IsValid) { if (validation.DoesProductExist(variant.ProductId) == true) { data.SaveVariant(variant); response = Request.CreateResponse(HttpStatusCode.Created); } else { response = Request.CreateResponse(HttpStatusCode.NotFound, new { Message = "There is no product with given Id parameter." }); } } else { response = Request.CreateResponse(HttpStatusCode.NotFound, new { Message = "Model is invalid.", ModelValidation = "Product's id must be greater than 0. BasePrice, Tax and InStock must be a positive numbers." }); } return(response); }
//public void AddPhone(ProductModel model, PhoneModel p) //{ // string imageName = UploadImage(model.proName, "chung", model.proImageStream); // Product product = _mapper.Map<Product>(model); // product.ProVisible = false; // product.ProTypeId = null; // product.ProImage = imageName; // int proId = _repo.AddProduct(product); // int index = 1; // Type type = typeof(PhoneModel); // PropertyInfo[] properties = type.GetProperties(); // foreach (PropertyInfo property in properties) // { // ProSpecification spec = new ProSpecification() // { // ProId = proId, // SpecIndex = index, // SpecValue = property.GetValue(p, null).ToString() // }; // _repo.AddProductSpec(spec); // _repo.SaveChanges(); // index++; // } //} public void AddVariant(VariantModel v) { string _iconImage = UploadImageAsync(v.proColorIcon); ProVariant proVariant = new ProVariant() { ProId = v.proId, VarColor = v.color, VarQty = v.proQty, VarColorIcon = _iconImage, VarStatus = v.proStatus, DateCreated = DateTime.Now }; _repo.AddPhoneVariant(proVariant); _repo.SaveChanges(); for (int i = 0; i < v.proColorImage.Length; i++) { VarImages varImages = new VarImages() { ImgPath = UploadImageAsync(v.proColorImage[i]), VarId = proVariant.VarId, Index = i + 1, }; _repo.AddVariantImages(varImages); _repo.SaveChanges(); } }
public HttpResponseMessage Put(int id, [FromBody][System.Web.Mvc.Bind(Include = "ProductId, BasePrice, Tax, InStock")] VariantModel variant) { HttpResponseMessage response; ModelsValidation validation = new ModelsValidation(); VariantData data = new VariantData(); if (ModelState.IsValid) { if (validation.DoesVariantExist(id) == false) { response = Request.CreateResponse(HttpStatusCode.NotFound, new { Message = "There is no variant with given Id parameter." }); } else { if (validation.DoesProductExist(variant.ProductId) == false) { response = Request.CreateResponse(HttpStatusCode.NotFound, new { Message = "There is no product with given Id parameter." }); } else { data.UpdateVariantById(id, variant); response = Request.CreateResponse(HttpStatusCode.NoContent); } } } else { response = Request.CreateResponse(HttpStatusCode.NotFound, new { Message = "Model is invalid.", ModelValidation = "Product's id must be greater than 0. BasePrice, Tax and InStock must be a positive numbers." }); } return(response); }
private void InitQuestions(List <Question> questions) { foreach (var questionItem in questions) { QuestionModel questionModel = new QuestionModel(); questionModel.QuestionText = questionItem.QuestionText; foreach (var variantItem in questionItem.Variants) { var variant = new VariantModel(); if (variantItem.Type == "Image") { FileTransferClient fileTransfer = new FileTransferClient(); TransferedImage img = fileTransfer.DownloadImage(variantItem.ImageUri); var path = SaveImage(img.data, img.Filename); variant.ImageUri = path; variant.Type = variantItem.Type; } else { variant.VariantText = variantItem.VariantText; } questionModel.Variants.Add(variant); } _questions.Add(questionModel); } }
public void UpdateVariantById(int id, VariantModel variant) { SqlDataAccess sql = new SqlDataAccess(); var parameters = new { Id = id, ProductId = variant.ProductId, BasePrice = variant.BasePrice, Tax = variant.Tax, InStock = variant.InStock }; sql.UpdateData("dbo.spVariantUpdateById", parameters, "DefaultConnection"); }
private VariantModel CreateVariant(SimpleProductModel currentSimpleProduct) { var variant = new VariantModel { PimArticleNumber = currentSimpleProduct.SimpleProductID.ToString(CultureInfo.InvariantCulture).Wrap(30), VariantDescription = currentSimpleProduct.SimpleVendorItemNumber.Wrap(50), BarcodeInfo = CreateBarcodeInformation(currentSimpleProduct), ColorInfo = CreateColorInformation(currentSimpleProduct), SizeInfo = CreateSizeInformation(currentSimpleProduct) }; return(variant); }
public ArticleModel Parse(string data) { var articleModel = new ArticleModel(); //create empty model var variantModel = new VariantModel(); articleModel.Variants = new List <VariantModel>() { variantModel }; if (string.IsNullOrEmpty(data)) //if data is empty return empty model { return(articleModel); } var dataArray = data.Split(','); if (KeysPositions != null && KeysPositions.Count > 0) //if keys are no set return empty model { //parse data to proper type and fill model int tmpInt; double tmpDouble; //Varaint variantModel.Key = dataArray[KeysPositions["Key"]]; variantModel.ArticleCode = dataArray[KeysPositions["ArtikelCode"]]; variantModel.Color = dataArray[KeysPositions["Color"]]; variantModel.DeliveredIn = dataArray[KeysPositions["DeliveredIn"]]; if (int.TryParse(dataArray[KeysPositions["Size"]], out tmpInt)) { variantModel.Size = tmpInt; } if (double.TryParse(dataArray[KeysPositions["Price"]], out tmpDouble)) { variantModel.Price = tmpDouble; } if (double.TryParse(dataArray[KeysPositions["DiscountPrice"]], out tmpDouble)) { variantModel.DiscountPrice = tmpDouble; } //Article articleModel.ArticleCode = dataArray[KeysPositions["ArtikelCode"]]; articleModel.Description = dataArray[KeysPositions["Description"]]; articleModel.Q1 = dataArray[KeysPositions["Q1"]]; articleModel.ColorCode = dataArray[KeysPositions["ColorCode"]]; } return(articleModel); }
public ActionResult InsertTrait(InsertTraitModel Model) { try { SearchHelper.DecodeModel(Model); if (string.IsNullOrWhiteSpace(Model.NewTraitName)) { return(Json(new { Status = "Error", Message = "Please fill in all fields." })); } if (Model.StyleClass == null) { return(Json(new { Status = "Error", Message = "Please select a variant parent." })); } var StyleTraitID = _db.InsertStyleTrait(Model.StyleClass, Model.NewTraitName, Model.NewTraitPosition, _UserName).FirstOrDefault()?.StyleTraitID; var variant = new VariantModel() { ID = StyleTraitID, Name = Model.NewTraitName, Description = Model.NewTraitName, Values = new List <VariantValueModel>() }; return(Json(new { Status = "Successful", Html = RenderPartialViewToString("_ProductVariant", variant) })); } catch (Exception ex) { LoggingHelper.LogError(ex); return(Json(new { Status = "Error", Message = ex.Message })); } }
public IHttpActionResult CreateNewVariant([FromBody] VariantModel request) { if (!ModelState.IsValid) return BadRequest("Invalid data."); IList<FolderStructureModel> folderstructure = new List<FolderStructureModel>(); using (var entities = new Dirico_DatabaseEntities()) { try { //STEP 1 : Insert into File structure var file = entities.FolderStructures.Add(new FolderStructure() { Name = request.name, ParentID = request.parent_id, IsDirectory = true }); entities.SaveChanges(); ////STEP 2: Insert into Variant table the specific info entities.Variants.Add(new Variant() { FileObjectId = file.ID, //Properties=request.properties }); entities.SaveChanges(); } catch (DbEntityValidationException ex) { foreach (DbEntityValidationResult item in ex.EntityValidationErrors) { DbEntityEntry entry = item.Entry; string entityTypeName = entry.Entity.GetType().Name; foreach (DbValidationError subItem in item.ValidationErrors) { string message = string.Format("Error '{0}' occurred in {1} at {2}", subItem.ErrorMessage, entityTypeName, subItem.PropertyName); return BadRequest(message); } } } } return Ok(folderstructure); }
public List <int> Resolve(VariantItem source, VariantModel destination, List <int> destMember, ResolutionContext context) { var flagList = new List <int>(); if (string.IsNullOrWhiteSpace(source.FlagIdSeed)) { return(flagList); } foreach (var flag in source.FlagIdSeed.Split(',')) { int id; if (int.TryParse(flag.Trim(), out id) && !flagList.Contains(id)) { flagList.Add(id); } } return(flagList); }
private void MapVariantParametrics(Product variant, VariantModel modelVariant) { if (variant.VariantParametrics == null || variant.VariantParametrics.Count <= 0) { return; } foreach (var parametric in variant.VariantParametrics) { var parametricModel = MapParametric(parametric); if (parametricModel == null) { continue; } modelVariant.VariantParametrics.Add(parametricModel); var productModelParametric = model.VariantParametrics.Find(v => v.Id == parametricModel.Id); if (productModelParametric == null) { productModelParametric = MapParametric(parametric); model.VariantParametrics.Add(productModelParametric); } //add value to the product model level parametric if the parametric does not already contain that value foreach (var parametricValue in parametricModel.Values) { //the value has an id, i.e it is of list type. Use that for uniqueness. if (parametric.ValueId.HasValue && !productModelParametric.Values.Exists(value => value.Id == parametricValue.Id)) { productModelParametric.Values.Add(parametricValue); } else if (!productModelParametric.Values.Exists(value => value.Value == parametricValue.Value)) //we don't have an id, use value for uniqueness { productModelParametric.Values.Add(parametricValue); } } productModelParametric.Values.Sort((p1, p2) => p1.SortOrder.CompareTo(p2.SortOrder)); } }
/// <summary> /// Validates a sku at either the product/variant level then validates the unit at the parent level /// </summary> /// <param name="sku"></param> /// <param name="unitName"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> internal static async Task ValidateSkuAndUnit(string sku, string unitName, IBaseContextModel context, Guid trackingGuid) { // Create a product to test for Units var dbProduct = new Deathstar.Data.Models.PC_Product(); // Product Component dbProduct = await ProductModel.ValidateBySku(sku, context, trackingGuid); if (dbProduct == null) { var dbVariant = await VariantModel.ValidateBySku(sku, context, trackingGuid); if (dbVariant == null) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Invalid sku: {sku}" } } ; dbProduct = await ProductModel.ValidateById(dbVariant.ParentId.ToString(), context, trackingGuid); } // Validate Unit var dbProductUnit = dbProduct.Units.FirstOrDefault(x => x.Name.ToLower() == unitName.ToLower() && x.IsActive); if (dbProductUnit == null) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"FOR GLORY AND HONOR {unitName}" } } ; } #endregion } }
public IActionResult AddVariant(VariantModel vm) { _productService.AddVariant(vm); return(Ok()); }
public void SaveVariant(VariantModel variant) { SqlDataAccess sql = new SqlDataAccess(); sql.SaveData("dbo.spVariantInsert", variant, "DefaultConnection"); }
/// <summary> /// Save a new inventory /// </summary> /// <param name="request"></param> /// <param name="tableName"></param> /// <param name="internalId"></param> /// <param name="trackingGuid"></param> /// <param name="context"></param> /// <param name="fromController"></param> /// <returns></returns> public async Task <Tagge.Common.Models.InventoryResponse> Save(InventoryRequest request, string tableName, string internalId, Guid trackingGuid, bool fromController = false) { var response = new Tagge.Common.Models.InventoryResponse(); var companyId = context.Security.GetCompanyId(); long id = 0; try { // MongoDB Settings var database = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar"); string collectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_Inventory").Name; // Get MongoDB var db = context.Database; var inventoryCollection = db.GetCollection <Deathstar.Data.Models.PC_Inventory>(collectionName); var counterCollection = db.GetCollection <Deathstar.Data.Models.Counter>("Counters"); // Inventory table string inventoryTable = string.Empty; // Webhook Scope string scope = string.Empty; // Verify Locations await LocationModel.Validate(request.LocationId, context, trackingGuid); // Validate Product/Variant and set inventory table if (tableName == "PC_Product") { await ProductModel.ValidateById(internalId, context, trackingGuid); inventoryTable = "PC_ProductInventory"; scope = "product"; } else { await VariantModel.ValidateById(internalId, context, trackingGuid); inventoryTable = "PC_ProductVariantInventory"; scope = "product/variant"; } // Check to see if the Inventory exists var existsfilter = Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); existsfilter = existsfilter & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.InternalId, internalId); // Product/Variant Id existsfilter = existsfilter & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.PC_LocationId, request.LocationId); existsfilter = existsfilter & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.ST_TableName, inventoryTable); existsfilter = existsfilter & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.IsActive, true); var dbExistingInventory = inventoryCollection.Find(existsfilter).FirstOrDefault(); if (dbExistingInventory != null) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = $"Inventory record already exists. Use PUT to update the inventory. (Id = {dbExistingInventory.Id})!" } } ; // Word var dbInventory = new Deathstar.Data.Models.PC_Inventory(); // Save Inventory // filter var filter = Builders <Deathstar.Data.Models.Counter> .Filter.Eq(x => x.Id, "inventory_id"); var update = Builders <Deathstar.Data.Models.Counter> .Update.Inc("Seq", 1); // Get Id id = counterCollection.FindOneAndUpdate(filter, update).Seq; // Convert request to Inventory dbInventory.ConvertToDatabaseObject(companyId.ToString(), tableName, request); // Custom Fields if (request.CustomFields != null && request.CustomFields.Count > 0) { dbInventory.CustomFields = await _customFieldModel.SaveGenericCustomField(request.CustomFields, inventoryTable, id.ToString(), trackingGuid); } // Add Id dbInventory.Id = id; // Add Product/Variant Id dbInventory.InternalId = internalId; // Add Created By & Timestamp dbInventory.CreatedBy = context.Security.GetEmail(); dbInventory.CreatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz"); dbInventory.IsActive = true; // Insert await inventoryCollection.InsertOneAsync(dbInventory); IG2000.Data.Utilities.Logging.LogTrackingEvent($"Inventory (id: {dbInventory.Id}) successfully saved.", "Save Inventory", LT319.Common.Utilities.Constants.TrackingStatus.Complete, context, trackingGuid); // Building the Response response = dbInventory.ConvertToResponse(); // ExternalIds if (request.ExternalIds != null && request.ExternalIds.Count > 0) { response.ExternalIds = await _externalIdModel.SaveOrUpdateGenericExternalId(request.ExternalIds, inventoryTable, id.ToString(), trackingGuid); } // Build the Webhook event if (fromController) { var whRequest = new Sheev.Common.Models.WebhookResponse() { CompanyId = companyId.ToString(), Type = "Inventory", Scope = $"{scope}/inventory/created", Id = response.Id.ToString() }; // Trigger the Webhook event await _webHookModel.FireWebhookEvent(whRequest, context, trackingGuid); } return(response); } catch (HttpResponseException webEx) { IG2000.Data.Utilities.Logging.LogTrackingEvent($"Inventory failed to save! Reason: {webEx.ReasonPhrase}", $"Status Code: {webEx.StatusCode}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); // Rollback the inventory to a failure await RollbackInventory(id, tableName); throw; } catch (Exception ex) { IG2000.Data.Utilities.Logging.LogTrackingEvent($"See logs for additional details", "Failed", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); IG2000.Data.Utilities.ErrorLogger.Report(ex.Message, "InventoryModel.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error); // Rollback the inventory due to a failure await RollbackInventory(id, tableName); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message }; } }
public Variant(VariantModel model) { Model = model; }
public List <ProductFileModel> Resolve(VariantItem source, VariantModel destination, List <ProductFileModel> destMember, ResolutionContext context) { return(ResolveBase(source.ImageKey, source.Name, source.AdditionalImageKeySeed, ProductFileType.VariantImage)); }
public async Task <IActionResult> Create(CreateProductViewModel model) { if (!ModelState.IsValid) { return(View(model)); } using (var Transaction = Db.Database.BeginTransaction()) { var product = new ProductModel() { Name = model.Name, Description = model.Description, StoreID = model.StoreID, Store = Db.Stores.Where(s => s.ID == model.StoreID).FirstOrDefault(), DateCreated = DateTime.Now, Status = ProductStatus.Available, Images = new List <ImageModel>(), Variants = new List <VariantModel>() }; foreach (var formFile in model.Images) { if (formFile.Length > 0) { var image = ImageUpload.ImageToByte(formFile); image.Product = product; product.Images.Add(image); } } await Db.Images.AddRangeAsync(product.Images); foreach (var variant in model.Variants) { var temp = new VariantModel() { Name = variant.Name, Description = variant.Description, Stock = variant.Stock, Price = variant.Price, Currency = CultureInfo.CurrentCulture, Images = new List <ImageModel>(), DateCreated = DateTime.Now }; foreach (var formFile in variant.Images) { if (formFile.Length > 0) { var image = ImageUpload.ImageToByte(formFile); image.Variant = temp; temp.Images.Add(image); } } product.Variants.Add(temp); await Db.Variants.AddAsync(temp); await Db.Images.AddRangeAsync(temp.Images); } await Db.Products.AddAsync(product); await Db.SaveChangesAsync(); Transaction.Commit(); } return(RedirectToAction("List")); }