/// <summary> /// Save a new Kit /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task <Tagge.Common.Models.KitResponse> Save(Tagge.Common.Models.KitRequest request, Guid trackingGuid) { var response = new Tagge.Common.Models.KitResponse(); var companyId = context.Security.GetCompanyId(); try { // MongoDB Settings var database = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar"); string productCollectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_Product").Name; string variantCollectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_ProductVariant").Name; // Get MongoDB var db = context.Database; var productCollection = db.GetCollection <Deathstar.Data.Models.PC_Product>(productCollectionName); var variantCollection = db.GetCollection <Deathstar.Data.Models.PC_ProductVariant>(variantCollectionName); // Word var dbKit = new Deathstar.Data.Models.PC_Kit(); // Id prefix string idPrefix = string.Empty; // Table string tableName = string.Empty; // Product var dbProduct = new Deathstar.Data.Models.PC_Product(); // Variant var dbVariant = new Deathstar.Data.Models.PC_ProductVariant(); // Variant Filter var variantFilters = Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); variantFilters = variantFilters & Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.Sku, request.Sku); variantFilters = variantFilters & Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.IsActive, true); // Filters - note always start with the company id var filters = Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); filters = filters & Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.Sku, request.Sku); filters = filters & Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.IsActive, true); // Find product first dbProduct = await productCollection.Find(filters).FirstOrDefaultAsync(); if (dbProduct != null) { idPrefix = dbProduct.Id.ToString(); tableName = "PC_Product"; } else { // Find that Variant! dbVariant = await variantCollection.Find(variantFilters).FirstOrDefaultAsync(); // Missing Variant oh noes! if (dbVariant == null) { IG2000.Data.Utilities.Logging.LogTrackingEvent($"Invalid sku: {request.Sku}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Invalid sku: {request.Sku}" }; } idPrefix = dbVariant.Id.ToString(); tableName = "PC_ProductVariant"; } // Validate Kit Type await _typeModel.ValidateKitType(request.Type, trackingGuid); // Convert request to Location dbKit.ConvertToDatabaseObject(request); // Set Primary Key dbKit.SetPrimaryKey(idPrefix, request.Sku); // Add Created By & Timestamp dbKit.CreatedBy = context.Security.GetEmail(); dbKit.CreatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz"); // IsActive dbKit.IsActive = true; // Insert if (tableName == "PC_Product") { // Custom Fields if (request.CustomFields != null && request.CustomFields.Count > 0) { dbKit.CustomFields = await _customFieldModel.SaveGenericCustomField(request.CustomFields, "PC_Kit", dbKit.PC_Kit_Id, trackingGuid); } // Components if (request.Components != null && request.Components.Count > 0) { dbKit.Components = await _kitComponentModel.Save(dbKit.PC_Kit_Id, "PC_KitComponent", request.Components, trackingGuid); } // Add dbProduct.Kit = dbKit; // So that the serializer ignores this field dbProduct.Id = 0; var serializerSettings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }; var update = new BsonDocument() { { "$set", BsonDocument.Parse(JsonConvert.SerializeObject(dbProduct, serializerSettings)) } }; // Insert await productCollection.UpdateOneAsync(filters, update); // Building the Response response = dbKit.ConvertToResponse(companyId.ToString(), "PC_Kit", db); // Add Id response.Id = dbKit.PC_Kit_Id; // ExternalIds if (request.ExternalIds != null && request.ExternalIds.Count > 0) { response.ExternalIds = await _externalIdModel.SaveOrUpdateGenericExternalId(request.ExternalIds, "PC_Kit", dbKit.PC_Kit_Id, trackingGuid); } } else { // Custom Fields if (request.CustomFields != null && request.CustomFields.Count > 0) { dbKit.CustomFields = await _customFieldModel.SaveGenericCustomField(request.CustomFields, "PC_VariantKit", dbKit.PC_Kit_Id, trackingGuid); } // Components if (request.Components != null && request.Components.Count > 0) { dbKit.Components = await _kitComponentModel.Save(dbKit.PC_Kit_Id, "PC_VariantKitComponent", request.Components, trackingGuid); } // Add dbVariant.Kit = dbKit; // So that the serializer ignores this field dbVariant.Id = 0; var serializerSettings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }; var update = new BsonDocument() { { "$set", BsonDocument.Parse(JsonConvert.SerializeObject(dbVariant, serializerSettings)) } }; // Insert await variantCollection.UpdateOneAsync(variantFilters, update); // Building the Response response = dbKit.ConvertToResponse(companyId.ToString(), "PC_VariantKit", db); // Add Id response.Id = dbKit.PC_Kit_Id; // ExternalIds if (request.ExternalIds != null && request.ExternalIds.Count > 0) { response.ExternalIds = await _externalIdModel.SaveOrUpdateGenericExternalId(request.ExternalIds, "PC_VariantKit", dbKit.PC_Kit_Id, trackingGuid); } } // Log success IG2000.Data.Utilities.Logging.LogTrackingEvent($"Kit (sku: {dbKit.Sku} successfully saved.", "Save Kit", LT319.Common.Utilities.Constants.TrackingStatus.Complete, context, trackingGuid); // Trigger the Webhook event //if (_useWebhook) //{ // var whRequest = new WebhookResponse() // { // CompanyId = companyId.ToString(), // Type = "Product", // Scope = "product/created", // Id = response.Id.ToString(), // TrackingGuid = trackingGuid // }; // WebhookModel.WebhookTriggerEvent(whRequest, trackingGuid); //} return(response); } catch (HttpResponseException webEx) { IG2000.Data.Utilities.Logging.LogTrackingEvent($"Kit ( Sku: {request.Sku}) failed to save! Reason: {webEx.ReasonPhrase}", $"Status Code: {webEx.StatusCode}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); 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, "KitModel.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message }; } }
/// <summary> /// Save a new Category /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task <Tagge.Common.Models.CategoryResponse> Save(IBaseContextModel context, Tagge.Common.Models.CategoryRequest request, Guid trackingGuid) { var response = new Tagge.Common.Models.CategoryResponse(); var companyId = context.Security.GetCompanyId(); try { //// MongoDB Settings //var database = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar"); //string collectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_Category").Name; //// Get MongoDB var db = context.Database; //var categoryCollection = db.GetCollection<Deathstar.Data.Models.PC_Category>(collectionName); var counterCollection = db.GetCollection <Deathstar.Data.Models.Counter>("Counters"); // Word var dbCategory = new Deathstar.Data.Models.PC_Category(); // Check to see if the parent id exists if (request.ParentId.HasValue && request.ParentId.Value > 0) { var parentCategoryFilter = Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.Id, request.ParentId.Value); parentCategoryFilter = parentCategoryFilter & Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); parentCategoryFilter = parentCategoryFilter & Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.IsActive, true); var parentCategory = _categoryCollection.Find(parentCategoryFilter).FirstOrDefault(); if (parentCategory == null) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Category Parent not found by Id: {request.ParentId}" } } ; } // Check to see if the Category is a duplicate var duplicatefilter = Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.Name, request.Name); duplicatefilter = duplicatefilter & Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.ParentId, request.ParentId); duplicatefilter = duplicatefilter & Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); duplicatefilter = duplicatefilter & Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.IsActive, true); var duplicateCategory = _categoryCollection.Find(duplicatefilter).FirstOrDefault(); if (duplicateCategory != null) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Category Already Exists. Use PUT to update category. (Id = {duplicateCategory.Id})!" } } ; // Validate Category Sets await _categorySetModel.Validate(context, request.CategorySets, trackingGuid); //new CategorySetModel(context).Validate(request.CategorySets, trackingGuid); // filter var filter = Builders <Deathstar.Data.Models.Counter> .Filter.Eq(x => x.Id, "category_id"); var update = Builders <Deathstar.Data.Models.Counter> .Update.Inc("Seq", 1); // Get Id var id = counterCollection.FindOneAndUpdate(filter, update).Seq; // Convert request to Category dbCategory.ConvertToDatabaseObject(companyId.ToString(), request); // Custom Fields if (request.CustomFields != null && request.CustomFields.Count > 0) { dbCategory.CustomFields = await _customFieldModel.SaveGenericCustomField(request.CustomFields, "PC_Category", id.ToString(), trackingGuid); } // Add Id dbCategory.Id = id; // Add Created By & Timestamp dbCategory.CreatedBy = context.Security.GetEmail(); dbCategory.CreatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz"); // IsActive dbCategory.IsActive = true; // Insert await _categoryCollection.InsertOneAsync(dbCategory); // Building the Response response = dbCategory.ConvertToResponse(); // Add Id response.Id = id; // ExternalIds if (request.ExternalIds != null && request.ExternalIds.Count > 0) { response.ExternalIds = await _externalIdModel.SaveOrUpdateGenericExternalId(request.ExternalIds, "PC_Category", id.ToString(), trackingGuid); } IG2000.Data.Utilities.Logging.LogTrackingEvent($"Category (id: {dbCategory.Id}, name: {dbCategory.Name}) successfully saved.", "Save Category", LT319.Common.Utilities.Constants.TrackingStatus.Complete, context, trackingGuid); // Build the Webhook event var whRequest = new Sheev.Common.Models.WebhookResponse() { CompanyId = companyId.ToString(), Type = "Product Category", Scope = "category/product/created", Id = response.Id.ToString(), TrackingGuid = trackingGuid }; // Trigger the Webhook event await _webHookModel.FireWebhookEvent(whRequest, context, trackingGuid); return(response); } catch (HttpResponseException webEx) { IG2000.Data.Utilities.Logging.LogTrackingEvent($"Category ( Name: {request.Name}) failed to save! Reason: {webEx.ReasonPhrase}", $"Status Code: {webEx.StatusCode}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); 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, "CategoryModel.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message }; } }
/// <summary> /// Save a new location group /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task <Tagge.Common.Models.LocationGroupResponse> Save(Tagge.Common.Models.LocationGroupRequest request, Guid trackingGuid) { var response = new Tagge.Common.Models.LocationGroupResponse(); var companyId = context.Security.GetCompanyId(); try { // MongoDB Settings var database = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar"); string collectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_LocationGroup").Name; // Get MongoDB var db = context.Database; var locationGroupCollection = db.GetCollection <Deathstar.Data.Models.PC_LocationGroup>(collectionName); var counterCollection = db.GetCollection <Deathstar.Data.Models.Counter>("Counters"); // filter var filter = Builders <Deathstar.Data.Models.Counter> .Filter.Eq(x => x.Id, "locationgroup_id"); var update = Builders <Deathstar.Data.Models.Counter> .Update.Inc("Seq", 1); // Word var dbLocationGroup = new Deathstar.Data.Models.PC_LocationGroup(); // Need to do this so that the lookup is not case sensitive var lowername = request.Name.ToLower(); // Check to see if the Location is a duplicate var duplicatefilter = Builders <Deathstar.Data.Models.PC_LocationGroup> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); duplicatefilter = duplicatefilter & Builders <Deathstar.Data.Models.PC_LocationGroup> .Filter.Where(x => x.Name.ToLower() == lowername); var duplicateLocation = locationGroupCollection.Find(duplicatefilter).ToList(); if (duplicateLocation != null && duplicateLocation.Count > 0) { string reason = $"Location Group ({request.Name}) already exist."; IG2000.Data.Utilities.Logging.LogTrackingEvent($"Location Group ({request.Name}) already exist! Reason: {reason}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = reason }; } // Get Id var id = counterCollection.FindOneAndUpdate(filter, update).Seq; // Convert request to Location dbLocationGroup.ConvertToDatabaseObject(companyId.ToString(), request); // Locations if (request.Locations != null && request.Locations.Count > 0) { dbLocationGroup.Locations = await LocationModel.SaveOrUpdate(request.Locations, new List <Deathstar.Data.Models.TM_GenericEntry>(), context, trackingGuid); } // Custom Fields if (request.CustomFields != null && request.CustomFields.Count > 0) { ////dbLocationGroup.CustomFields = await _customFieldModel.SaveGenericCustomField(request.CustomFields, "PC_LocationGroup", id.ToString(), trackingGuid); } // Add Id dbLocationGroup.Id = id; // Add Created By & Timestamp dbLocationGroup.CreatedBy = context.Security.GetEmail(); dbLocationGroup.CreatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz"); // IsActive dbLocationGroup.IsActive = true; // Insert await locationGroupCollection.InsertOneAsync(dbLocationGroup); // Building the Response response = dbLocationGroup.ConvertToResponse(); // Add Id response.Id = id; // ExternalIds if (request.ExternalIds != null && request.ExternalIds.Count > 0) { response.ExternalIds = await _externalIdModel.SaveOrUpdateGenericExternalId(request.ExternalIds, "PC_LocationGroup", id.ToString(), trackingGuid); } IG2000.Data.Utilities.Logging.LogTrackingEvent($"Location Group (id: {dbLocationGroup.Id}, sku: {dbLocationGroup.Name}) successfully saved.", "Save Location", LT319.Common.Utilities.Constants.TrackingStatus.Complete, context, trackingGuid); // Trigger the Webhook event //if (_useWebhook) //{ // var whRequest = new WebhookResponse() // { // CompanyId = companyId.ToString(), // Type = "Product", // Scope = "product/created", // Id = response.Id.ToString(), // TrackingGuid = trackingGuid // }; // WebhookModel.WebhookTriggerEvent(whRequest, trackingGuid); //} return(response); } catch (HttpResponseException webEx) { IG2000.Data.Utilities.Logging.LogTrackingEvent($"Location Group ( Name: {request.Name}) failed to save! Reason: {webEx.ReasonPhrase}", $"Status Code: {webEx.StatusCode}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); 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, "LocationGroupModel.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message }; } }
/// <summary> /// Internal Use Only! Save a Kit Component /// </summary> /// <param name="parentId"></param> /// <param name="request"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task <List <Deathstar.Data.Models.PC_KitComponent> > Save(string parentId, string tableName, List <Tagge.Common.Models.KitComponentRequest> request, Guid trackingGuid) { var dbKitComponents = new List <Deathstar.Data.Models.PC_KitComponent>(); try { foreach (var component in request) { // Check to see if sku is populated if not error if (string.IsNullOrEmpty(component.Sku)) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = "Sku is null or empty" } } ; // Is quantity greater than 0 if so you good if (component.Quantity <= 0) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = "Qty is less or equal to '0'" } } ; // Unit is a required field if its missing error! if (string.IsNullOrEmpty(component.Unit)) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = "Unit value not found" } } ; // Validate the sku & unit await ValidateModel.ValidateSkuAndUnit(component.Sku, component.Unit, context, trackingGuid); // Validate Kit Component Type await _typeModel.ValidateKitComponentType(component.Type, trackingGuid); // Building the component // Why not using ConvertToDatabaseObject? var dbComponent = new Deathstar.Data.Models.PC_KitComponent(); // Convert To Database object dbComponent.ConvertToDatabaseObject(component); // Set Primary Key dbComponent.SetPrimaryKey(parentId, component.Unit); if (!tableName.Contains("Component")) { tableName = tableName + "Component"; } // Custom Fields if (component.CustomFields != null && component.CustomFields.Count > 0) { dbComponent.CustomFields = await _customFieldModel.SaveGenericCustomField(component.CustomFields, tableName, dbComponent.PC_KitComponent_Id, trackingGuid); } // ExternalIds if (component.ExternalIds != null && component.ExternalIds.Count > 0) { await _externalIdModel.SaveOrUpdateGenericExternalId(component.ExternalIds, tableName, dbComponent.PC_KitComponent_Id, trackingGuid); } // Add Created By & Timestamp dbComponent.CreatedBy = context.Security.GetEmail(); dbComponent.CreatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz"); // IsActive dbComponent.IsActive = true; // Add to Response dbKitComponents.Add(dbComponent); } } catch (HttpResponseException) { throw; } return(dbKitComponents); }
/// <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 }; } }
/// <summary> /// Internal Use Only! Save an Option Value on an Product Option /// </summary> /// <param name="productId"></param> /// <param name="dbOption"></param> /// <param name="optionvalues"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task <List <Deathstar.Data.Models.PC_OptionValue> > Save(long productId, Deathstar.Data.Models.PC_Option dbOption, List <Tagge.Common.Models.OptionValueRequest> optionvalues, Guid trackingGuid) { { var dbOptionValues = new List <Deathstar.Data.Models.PC_OptionValue>(); // Company Id var companyId = context.Security.GetCompanyId(); try { if (optionvalues != null && optionvalues.Count > 0) { foreach (var optionValue in optionvalues) { var dbOptionValue = new Deathstar.Data.Models.PC_OptionValue(); dbOptionValue = dbOption.Values.FirstOrDefault(x => x.Value.ToLower() == optionValue.Value.ToLower() && x.IsActive); if (string.IsNullOrEmpty(optionValue.Value)) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = "Option Value is null or empty" } } ; if (dbOptionValue == null) { // Add dbOptionValue = new Deathstar.Data.Models.PC_OptionValue() { OptionName = dbOption.Name, Value = optionValue.Value, Detail = optionValue.Detail, Order = optionValue.Order, IsActive = true, CreatedBy = context.Security.GetEmail(), CreatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz") }; dbOptionValue.SetPrimaryKey(productId.ToString(), null, dbOption.Name, optionValue.Value); } else { // Update dbOptionValue.Value = optionValue.Value; dbOptionValue.Detail = optionValue.Detail; dbOptionValue.Order = optionValue.Order; dbOptionValue.IsActive = true; dbOptionValue.UpdatedBy = context.Security.GetEmail(); dbOptionValue.UpdatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz"); } // Custom Fields if (optionValue.CustomFields != null && optionValue.CustomFields.Count > 0) { dbOptionValue.CustomFields = await _customFieldModel.SaveGenericCustomField(optionValue.CustomFields, "PC_ProductOptionValue", dbOptionValue.PC_OptionValue_Id, trackingGuid); } // ExternalIds if (optionValue.ExternalIds != null && optionValue.ExternalIds.Count > 0) { await _externalIdModel.SaveOrUpdateGenericExternalId(optionValue.ExternalIds, "PC_ProductOptionValue", dbOptionValue.PC_OptionValue_Id, trackingGuid); } dbOptionValues.Add(dbOptionValue); } } return(dbOptionValues); } catch (HttpResponseException webEx) { 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, "OptionValueModel.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message }; } } }
/// <summary> /// Saves New Product /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task <Tagge.Common.Models.ProductResponse> Save(Tagge.Common.Models.ProductRequest request, Guid trackingGuid) { var response = new Tagge.Common.Models.ProductResponse(); var companyId = context.Security.GetCompanyId(); long id = 0; IG2000.Data.Utilities.Logging.LogTrackingEvent($"Beginning Product save by user {context.Security.GetEmail()},", "Save Product", LT319.Common.Utilities.Constants.TrackingStatus.Active, context, trackingGuid); try { // MongoDB Settings var database = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar"); string collectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_Product").Name; // Get MongoDB var db = context.Database; var productCollection = db.GetCollection <Deathstar.Data.Models.PC_Product>(collectionName); var counterCollection = db.GetCollection <Deathstar.Data.Models.Counter>("Counters"); // filter var filter = Builders <Deathstar.Data.Models.Counter> .Filter.Eq(x => x.Id, "product_id"); var update = Builders <Deathstar.Data.Models.Counter> .Update.Inc("Seq", 1); // Word var dbProduct = new Deathstar.Data.Models.PC_Product(); // Check to see if the Sku is a duplicate await CheckForDuplicateSkus(request.Sku, companyId.ToString(), productCollection, context, trackingGuid); // Validate Status await _typeModel.ValidateStatusType(request.Status, trackingGuid); // Validate Type await _typeModel.ValidateProductType(request.Type, trackingGuid); // Validate Tracking Method await _typeModel.ValidateTrackingMethodType(request.TrackingMethod, trackingGuid); // Check to see if the tracking method is set to products if it is make sure no variants are sent in as well if (request.TrackingMethod.ToLower() == "product" && request.Variants != null && request.Variants.Count > 0) { string reason = $"The Tracking Method is set to Product, which does not allow for variants."; IG2000.Data.Utilities.Logging.LogTrackingEvent($"{reason}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = reason }; } // Get Id id = counterCollection.FindOneAndUpdate(filter, update).Seq; // Convert request to Product dbProduct.ConvertToDatabaseObject(companyId.ToString(), request); // Units if (request.Units != null && request.Units.Count > 0) { dbProduct.Units = await _unitModel.Save(id, request.Units, trackingGuid); } // Save Kit if (request.Kit != null) { dbProduct.Kit = await _kitModel.Save(id, "PC_Kit", request.Kit, trackingGuid); } // Category Assignment if (request.Categories != null && request.Categories.Count > 0) { dbProduct.Categories = await _categoryAssignmentModel.Save(context, id, request.Categories, dbProduct.Categories, trackingGuid); } // Options if (request.Options != null && request.Options.Count > 0) { dbProduct.Options = await _optionModel.Save(id, request.Options, trackingGuid); } // Save Alternate Ids if (request.AlternateIds != null && request.AlternateIds.Count > 0) { dbProduct.AlternateIds = await _alternateIdModel.SaveOrUpdate(context, id, dbProduct.Sku, "PC_ProductAlternateId", request.AlternateIds, new List <Deathstar.Data.Models.PC_AlternateId>(), dbProduct, trackingGuid); } // Custom Fields if (request.CustomFields != null && request.CustomFields.Count > 0) { ////dbProduct.CustomFields = await _customFieldModel.SaveGenericCustomField(request.CustomFields, "PC_Product", id.ToString(), trackingGuid); } // Add Id dbProduct.Id = id; // Add Created By & Timestamp dbProduct.CreatedBy = context.Security.GetEmail(); dbProduct.CreatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz"); // Insert await productCollection.InsertOneAsync(dbProduct); // Building the Response response = dbProduct.ConvertToResponse(companyId.ToString(), context.Database); // If the product doesnt save then this will not be hit // Inventory if (request.Inventory != null && request.Inventory.Count > 0) { response.Inventory = new List <Common.Models.InventoryResponse>(); foreach (var inventoryRequest in request.Inventory) { response.Inventory.Add(await _inventoryModel.Save(inventoryRequest, "PC_Product", id.ToString(), trackingGuid)); } } // Variant if (request.Variants != null && request.Variants.Count > 0) { response.Variants = new List <Common.Models.ProductVariantResponse>(); foreach (var variantRequest in request.Variants) { response.Variants.Add(await _variantModel.Save(variantRequest, dbProduct, trackingGuid)); } } // ExternalIds if (request.ExternalIds != null && request.ExternalIds.Count > 0) { response.ExternalIds = await _externalIdModel.SaveOrUpdateGenericExternalId(request.ExternalIds, "PC_Product", id.ToString(), trackingGuid); } IG2000.Data.Utilities.Logging.LogTrackingEvent($"Product (id: {dbProduct.Id}, sku: {dbProduct.Sku}) successfully saved.", "Save Product", LT319.Common.Utilities.Constants.TrackingStatus.Complete, context, trackingGuid); // Build the Webhook event var whRequest = new Sheev.Common.Models.WebhookResponse() { CompanyId = companyId.ToString(), Type = "Product", Scope = "product/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($"Product (sku: {request.Sku}) failed to save! Reason: {webEx.ReasonPhrase}", $"Status Code: {webEx.StatusCode}", LT319.Common.Utilities.Constants.TrackingStatus.Complete, context, trackingGuid); await RollbackProduct(id); 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, "CatalogModel.SaveProduct()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error); await RollbackProduct(id); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message }; } }
public async Task <Tagge.Common.Models.AlternateIdTypeResponse> Save(IBaseContextModel context, Tagge.Common.Models.AlternateIdTypeRequest request, Guid trackingGuid) { var response = new Tagge.Common.Models.AlternateIdTypeResponse(); var companyId = context.Security.GetCompanyId(); try { // MongoDB Settings var database = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar"); string collectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_AlternateIdType").Name; // Get MongoDB var db = context.Database; var alternateIdTypeCollection = db.GetCollection <Deathstar.Data.Models.PC_AlternateIdType>(collectionName); var counterCollection = db.GetCollection <Deathstar.Data.Models.Counter>("Counters"); // Word var dbAlternateIdType = new Deathstar.Data.Models.PC_AlternateIdType(); // filter var filter = Builders <Deathstar.Data.Models.Counter> .Filter.Eq(x => x.Id, "alternateidtype_id"); var update = Builders <Deathstar.Data.Models.Counter> .Update.Inc("Seq", 1); // Get Id var id = counterCollection.FindOneAndUpdate(filter, update).Seq; // Convert request to AlternateIdType dbAlternateIdType.ConvertToDatabaseObject(companyId.ToString(), request); // Custom Fields if (request.CustomFields != null && request.CustomFields.Count > 0) { dbAlternateIdType.CustomFields = await _customFieldModel.SaveGenericCustomField(request.CustomFields, "PC_AlternateIdType", id.ToString(), trackingGuid); } // Add Id dbAlternateIdType.Id = id; // Add Created By & Timestamp dbAlternateIdType.CreatedBy = context.Security.GetEmail(); dbAlternateIdType.CreatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz"); dbAlternateIdType.IsActive = true; // Insert await alternateIdTypeCollection.InsertOneAsync(dbAlternateIdType); IG2000.Data.Utilities.Logging.LogTrackingEvent($"Alternate Id Type (id: {dbAlternateIdType.Id}) successfully saved.", "Save Alternate Id Type", LT319.Common.Utilities.Constants.TrackingStatus.Complete, context, trackingGuid); // Building the Response response = dbAlternateIdType.ConvertToResponse(); // ExternalIds if (request.ExternalIds != null && request.ExternalIds.Count > 0) { response.ExternalIds = await _externalIdModel.SaveOrUpdateGenericExternalId(request.ExternalIds, "PC_AlternateIdType", id.ToString(), trackingGuid); } return(response); } catch (HttpResponseException webEx) { IG2000.Data.Utilities.Logging.LogTrackingEvent($"Alternate Id Type failed to save! Reason: {webEx.ReasonPhrase}", $"Status Code: {webEx.StatusCode}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); 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, "AlternateIdTypeModel.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message }; } }
/// <summary> /// Internal Use Only! Save/Update a list of options /// </summary> /// <param name="productId"></param> /// <param name="options"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task <List <Deathstar.Data.Models.PC_Option> > Save(long productId, List <Tagge.Common.Models.OptionRequest> options, Guid trackingGuid) { var dbOptions = new List <Deathstar.Data.Models.PC_Option>(); // Company Id var companyId = context.Security.GetCompanyId(); var productCollection = context.Database.GetCollection <Deathstar.Data.Models.PC_Product>("PC_Product"); // Filters - note always start with the company id var filters = Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); filters = filters & Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.Id, productId); var dbProduct = await productCollection.FindAsync(filters).Result.FirstOrDefaultAsync(); try { if (options != null && options.Count > 0) { foreach (var option in options) { var dbOption = new Deathstar.Data.Models.PC_Option(); if (dbProduct != null && dbProduct.Options != null) { dbOption = dbProduct.Options.FirstOrDefault(x => x.Name.ToLower() == option.OptionName.ToLower() && x.IsActive); } if (dbProduct == null || dbProduct.Options == null || dbOption == null) { // Add dbOption = new Deathstar.Data.Models.PC_Option() { Name = option.OptionName, Order = option.Order, Type = option.Type, IsActive = true, CreatedBy = context.Security.GetEmail(), CreatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz") }; // Set Primary Key dbOption.SetPrimaryKey(productId.ToString(), option.OptionName); } else { // Update dbOption.Order = option.Order; dbOption.Type = option.Type; dbOption.IsActive = true; dbOption.UpdatedBy = context.Security.GetEmail(); dbOption.UpdatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz"); } // Option Values dbOption.Values = await _optionValueModel.Save(productId, dbOption, option.Values, trackingGuid); // Custom Fields if (option.CustomFields != null && option.CustomFields.Count > 0) { dbOption.CustomFields = await _customFieldModel.SaveGenericCustomField(option.CustomFields, "PC_ProductOption", dbOption.PC_Option_Id, trackingGuid); } // ExternalIds if (option.ExternalIds != null && option.ExternalIds.Count > 0) { await _externalIdModel.SaveOrUpdateGenericExternalId(option.ExternalIds, "PC_ProductOption", dbOption.PC_Option_Id, trackingGuid); } dbOptions.Add(dbOption); } } return(dbOptions); } catch (HttpResponseException webEx) { 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, "OptionModel.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message }; } }
public async Task <List <Deathstar.Data.Models.PC_ProductUnit> > Save(long productId, List <Tagge.Common.Models.ProductUnitRequest> units, Guid trackingGuid) { var dbOptions = new List <Deathstar.Data.Models.PC_ProductUnit>(); // Company Id var companyId = context.Security.GetCompanyId(); var productCollection = context.Database.GetCollection <Deathstar.Data.Models.PC_Product>("PC_Product"); // Filters - note always start with the company id var filters = Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); filters = filters & Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.Id, productId); filters = filters & Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.IsActive, true); var dbProduct = await productCollection.FindAsync(filters).Result.FirstOrDefaultAsync(); foreach (var unit in units) { // check to make sure name exists if (string.IsNullOrEmpty(unit.Name)) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Unit name is null or empty" } } ; var dbUnit = new Deathstar.Data.Models.PC_ProductUnit(); // Check to make sure the product and the unit collection are not nukll if (dbProduct != null && dbProduct.Units != null) { dbUnit = dbProduct.Units.FirstOrDefault(x => x.Name.ToLower() == unit.Name.ToLower() && x.IsActive); } // if one of these is null create a new unit if (dbProduct == null || dbProduct.Units == null || dbUnit == null) { // Add dbUnit = new Deathstar.Data.Models.PC_ProductUnit() { Name = unit.Name, Conversion = unit.Conversion, DefaultPrice = unit.DefaultPrice, MSRP = unit.MSRP, SalePrice = unit.SalePrice, IsActive = true, CreatedBy = context.Security.GetEmail(), CreatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz") }; // Set Primary Key dbUnit.SetPrimaryKey(productId.ToString(), unit.Name); } else { // Update dbUnit.Conversion = unit.Conversion; dbUnit.DefaultPrice = unit.DefaultPrice; dbUnit.MSRP = unit.MSRP; dbUnit.SalePrice = unit.SalePrice; dbUnit.IsActive = true; dbUnit.UpdatedBy = context.Security.GetEmail(); dbUnit.UpdatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz"); } // Custom Fields if (unit.CustomFields != null && unit.CustomFields.Count > 0) { dbUnit.CustomFields = await _customFieldModel.SaveGenericCustomField(unit.CustomFields, "PC_ProductUnit", dbUnit.PC_ProductUnit_Id, trackingGuid); } // ExternalIds if (unit.ExternalIds != null && unit.ExternalIds.Count > 0) { await _externalId.SaveOrUpdateGenericExternalId(unit.ExternalIds, "PC_ProductUnit", dbUnit.PC_ProductUnit_Id, trackingGuid); } dbOptions.Add(dbUnit); } return(dbOptions); }