Exemple #1
0
        /// <summary>
        /// Fire a webhook event
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <param name="attempt"></param>
        /// <returns></returns>
        public async Task FireWebhookEvent(Sheev.Common.Models.WebhookResponse request, IBaseContextModel context, Guid trackingGuid, int attempt = 0)
        {
            try
            {
                // Start Log Here
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"iring webhook event: {request.Scope}. Attempt: {attempt + 1}/3 Note if webhook is not found in the receiver then this is either a clapback or the system is not subscribed to this scope.", "Trigger Webhook Event", LT319.Common.Utilities.Constants.TrackingStatus.Active, context, trackingGuid);

                // Rest Client
                var restClient = new RestSharp.RestClient(context.ApiUrlSettings.Value.Skyhook_URL);

                // Building the request and setting endpoint target
                RestSharp.RestRequest req = new RestSharp.RestRequest("/v2/Event", RestSharp.Method.POST);

                // Serializing the body
                var bodyJSON = JsonConvert.SerializeObject(request);

                // Added the application/json header
                req.AddParameter("application/json", bodyJSON, ParameterType.RequestBody);

                // Execute the request
                var resp = (RestSharp.RestResponse)restClient.Execute(req);

                // Check the response
                if (!resp.IsSuccessful)
                {
                    // Log something here
                    IG2000.Data.Utilities.ErrorLogger.Report(JsonConvert.SerializeObject(resp), "WebhookModel.FireWebhookEvent()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error);

                    if (resp.ErrorException != null)
                    {
                        IG2000.Data.Utilities.Logging.LogTrackingEvent($"Webhook was unable to be sent! Reason: {resp.ErrorException.Message}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid);
                    }

                    // Retry
                    if (attempt < 3)
                    {
                        await FireWebhookEvent(request, context, trackingGuid, attempt + 1);
                    }
                }

                // End Log Here
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"Webhook {request.Scope} successfully fired on attempt: {attempt + 1}.", "Trigger Webhook Event", LT319.Common.Utilities.Constants.TrackingStatus.Active, context, trackingGuid);
            }
            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, "WebhookModel.FireWebhookEvent()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error);

                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message
                      };
            }
        }
        public async Task DeleteOrReactivate(IBaseContextModel context, string combinedId, string tableName, bool reactivate, Guid trackingGuid)
        {
            var response = new Tagge.Common.Models.ProductCategoryResponse();

            // Company Id
            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;

                // Word
                var dbCategory = new Deathstar.Data.Models.PC_Category();

                // Id prefix
                string idPrefix = string.Empty;

                // Product Category
                var dbProductCategory = new Deathstar.Data.Models.PC_ProductCategory();

                // Product
                var dbProduct = new Deathstar.Data.Models.PC_Product();

                // Variant
                var dbVariant = new Deathstar.Data.Models.PC_ProductVariant();

                // Break combined id
                string[] ids = combinedId.Split('|');

                // Product id
                long.TryParse(ids[0], out long internalId);

                // Switch between Product & Variant
                if (tableName == "PC_Product")
                {
                    // Get the table ready
                    var productCollection = db.GetCollection <Deathstar.Data.Models.PC_Product>(productCollectionName);

                    // 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, internalId);

                    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)
                    {
                        IG2000.Data.Utilities.Logging.LogTrackingEvent($"Invalid Id: {combinedId}", $"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 Id: {combinedId}"
                              };
                    }

                    // Find the category within the product
                    dbProductCategory = dbProduct.Categories.FirstOrDefault(x => x.PC_ProductCategory_Id == combinedId);

                    if (dbProductCategory == null)
                    {
                        throw new HttpResponseException()
                              {
                                  StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = $"Product Category not found by id({combinedId}) provided"
                              }
                    }
                    ;

                    dbProduct.Categories.Remove(dbProductCategory);

                    // Set Product Id to 0 cause of the serializer
                    dbProduct.Id = 0;

                    var serializerSettings = new JsonSerializerSettings()
                    {
                        NullValueHandling    = NullValueHandling.Ignore,
                        DefaultValueHandling = DefaultValueHandling.Ignore
                    };
                    var update = new BsonDocument()
                    {
                        { "$set", BsonDocument.Parse(JsonConvert.SerializeObject(dbProduct, serializerSettings)) }
                    };

                    // Update database record
                    await productCollection.UpdateOneAsync(filters, update);

                    // Build the Webhook event
                    var whProductRequest = new Sheev.Common.Models.WebhookResponse()
                    {
                        CompanyId = companyId.ToString(),
                        Type      = "Product Category Assignment",
                        Scope     = $"product/category/deleted",
                        Id        = combinedId
                    };

                    // Trigger the Webhook event
                    await _webHookModel.FireWebhookEvent(whProductRequest, context, trackingGuid);
                }
                else
                {
                    // Get the table ready
                    var variantFilters = Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.Id, internalId);

                    // Filter building
                    var variantCollection = db.GetCollection <Deathstar.Data.Models.PC_ProductVariant>(variantCollectionName);
                    variantFilters = variantFilters & Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.IsActive, true);

                    variantFilters = variantFilters & Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString());

                    dbVariant = await variantCollection.Find(variantFilters).FirstOrDefaultAsync();

                    if (dbVariant == null)
                    {
                        IG2000.Data.Utilities.Logging.LogTrackingEvent($"Invalid Id: {combinedId}", $"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 Id: {combinedId}"
                              };
                    }

                    // Find the category
                    dbProductCategory = dbVariant.Categories.FirstOrDefault(x => x.PC_ProductCategory_Id == combinedId);

                    // Category is missing
                    if (dbProductCategory == null)
                    {
                        throw new HttpResponseException()
                              {
                                  StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = $"Product Category not found by id({combinedId}) provided"
                              }
                    }
                    ;

                    dbVariant.Categories.Remove(dbProductCategory);

                    // Set Product Id to 0 cause of the serializer
                    dbVariant.Id = 0;

                    var serializerSettings = new JsonSerializerSettings()
                    {
                        NullValueHandling    = NullValueHandling.Ignore,
                        DefaultValueHandling = DefaultValueHandling.Ignore
                    };
                    var variantUpdate = new BsonDocument()
                    {
                        { "$set", BsonDocument.Parse(JsonConvert.SerializeObject(dbVariant, serializerSettings)) }
                    };

                    await variantCollection.UpdateOneAsync(variantFilters, variantUpdate);

                    // Build the Webhook event
                    var whVariantRequest = new Sheev.Common.Models.WebhookResponse()
                    {
                        CompanyId = companyId.ToString(),
                        Type      = "Product Category Assignment",
                        Scope     = $"product/variant/category/deleted",
                        Id        = combinedId
                    };

                    // Trigger the Webhook event
                    await _webHookModel.FireWebhookEvent(whVariantRequest, context, trackingGuid);
                }
            }
            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);
                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);
                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message
                      };
            }
        }
        /// <summary>
        /// Saves a category assignment
        /// </summary>
        /// <param name="request"></param>
        /// <param name="tableName"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <returns></returns>
        public async Task <Tagge.Common.Models.ProductCategoryResponse> Save(IBaseContextModel context, Tagge.Common.Models.ProductCategoryRequest request, string tableName, Guid trackingGuid)
        {
            var response = new Tagge.Common.Models.ProductCategoryResponse();

            // Company Id
            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;

                // Word
                var dbCategory = new Deathstar.Data.Models.PC_Category();

                // Id prefix
                string idPrefix = string.Empty;

                // Validate Category
                ////Circular Reference
                string dbCategoryName = await CategoryModel.Validate(request.CategoryId, context, trackingGuid);// _new CategoryModel(context).Validate(request.CategoryId, trackingGuid);

                // Product Category
                var dbProductCategory = new Deathstar.Data.Models.PC_ProductCategory();

                // Convert To Database Object
                dbProductCategory.ConvertToDatabaseObject(dbCategoryName, request);

                // Set Primary Key
                dbProductCategory.SetPrimaryKey(request.InternalId.ToString(), request.CategoryId.ToString());

                // Set Is Active to true
                dbProductCategory.IsActive = true;

                switch (tableName)
                {
                case "PC_Product":
                    var productCollection = db.GetCollection <Deathstar.Data.Models.PC_Product>(productCollectionName);

                    // Product
                    var dbProduct = new Deathstar.Data.Models.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, request.InternalId);

                    filters = filters & Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.IsActive, true);

                    // Find the product
                    dbProduct = await productCollection.Find(filters).FirstOrDefaultAsync();

                    // The product was not valid
                    if (dbProduct == null)
                    {
                        var message = $"Product Id not valid: {request.InternalId}";

                        throw new HttpResponseException()
                              {
                                  StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = message
                              };
                    }

                    if (dbProduct.Categories != null && dbProduct.Categories.Count > 0)
                    {
                        var dbtempCategory = dbProduct.Categories.FirstOrDefault(x => x.PC_ProductCategory_Id == dbProductCategory.PC_ProductCategory_Id && x.CategoryId == request.CategoryId);

                        if (dbtempCategory == null)
                        {
                            // Add the Category Assignment
                            dbProduct.Categories.Add(dbProductCategory);
                        }
                        else
                        {
                            // Update the Category Assignment
                            dbProductCategory          = dbtempCategory;
                            dbProductCategory.IsActive = true;
                        }
                    }
                    else
                    {
                        // Add the Category Assignment
                        dbProduct.Categories.Add(dbProductCategory);
                    }

                    // Set Product Id to 0 cause of the serializer
                    var productId = dbProduct.Id;
                    dbProduct.Id = 0;

                    var serializerSettings = new JsonSerializerSettings()
                    {
                        NullValueHandling    = NullValueHandling.Ignore,
                        DefaultValueHandling = DefaultValueHandling.Ignore
                    };
                    var update = new BsonDocument()
                    {
                        { "$set", BsonDocument.Parse(JsonConvert.SerializeObject(dbProduct, serializerSettings)) }
                    };

                    // Update database record
                    await productCollection.UpdateOneAsync(filters, update);

                    response = new Common.Models.ProductCategoryResponse()
                    {
                        Id         = dbProductCategory.PC_ProductCategory_Id,
                        ProductId  = productId,
                        CategoryId = request.CategoryId,
                        Type       = "Product"
                    };

                    // Build the Webhook event
                    var whProductRequest = new Sheev.Common.Models.WebhookResponse()
                    {
                        CompanyId    = companyId.ToString(),
                        Type         = "Product Category Assignment",
                        Scope        = $"product/category/created",
                        Id           = response.Id,
                        TrackingGuid = trackingGuid
                    };

                    // Trigger the Webhook event
                    await _webHookModel.FireWebhookEvent(whProductRequest, context, trackingGuid);

                    break;

                case "PC_ProductVariant":
                    var variantCollection = db.GetCollection <Deathstar.Data.Models.PC_ProductVariant>(variantCollectionName);

                    // Variant
                    var dbVariant = new Deathstar.Data.Models.PC_ProductVariant();

                    var variantFilter = Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.Id, request.InternalId);

                    variantFilter = variantFilter & Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.IsActive, true);

                    variantFilter = variantFilter & Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString());

                    dbVariant = await variantCollection.Find(variantFilter).FirstOrDefaultAsync();

                    if (dbVariant == null)
                    {
                        var message = $"Product Variant Id not valid: {request.InternalId}";

                        throw new HttpResponseException()
                              {
                                  StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = message
                              };
                    }

                    if (dbVariant.Categories != null && dbVariant.Categories.Count > 0)
                    {
                        var dbtempCategory = dbVariant.Categories.FirstOrDefault(x => x.PC_ProductCategory_Id == dbProductCategory.PC_ProductCategory_Id && x.CategoryId == request.CategoryId && x.IsActive);

                        if (dbtempCategory == null)
                        {
                            // Add the Category Assignment
                            dbVariant.Categories.Add(dbProductCategory);
                        }
                        else
                        {
                            // Update the Category Assignment
                            dbProductCategory          = dbtempCategory;
                            dbProductCategory.IsActive = true;
                        }
                    }
                    else
                    {
                        // Add the Category Assignment
                        dbVariant.Categories.Add(dbProductCategory);
                    }

                    // Set Product Id to 0 cause of the serializer
                    var variantId = dbVariant.Id;
                    dbVariant.Id = 0;

                    var variantSerializerSettings = new JsonSerializerSettings()
                    {
                        NullValueHandling    = NullValueHandling.Ignore,
                        DefaultValueHandling = DefaultValueHandling.Ignore
                    };

                    var variantUpdate = new BsonDocument()
                    {
                        { "$set", BsonDocument.Parse(JsonConvert.SerializeObject(dbVariant, variantSerializerSettings)) }
                    };

                    // Update database record
                    await variantCollection.UpdateOneAsync(variantFilter, variantUpdate);

                    response = new Common.Models.ProductCategoryResponse()
                    {
                        Id         = dbProductCategory.PC_ProductCategory_Id,
                        ProductId  = variantId,
                        CategoryId = request.CategoryId,
                        Type       = "Variant"
                    };

                    // Build the Webhook event
                    var whVariantRequest = new Sheev.Common.Models.WebhookResponse()
                    {
                        CompanyId    = companyId.ToString(),
                        Type         = "Product Category Assignment",
                        Scope        = $"product/variant/category/created",
                        Id           = response.Id,
                        TrackingGuid = trackingGuid
                    };

                    // Trigger the Webhook event
                    await _webHookModel.FireWebhookEvent(whVariantRequest, context, trackingGuid);

                    break;

                default:
                    throw new HttpResponseException()
                          {
                              StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Invalid Type: {tableName}. Please specify a correct type: Product or Variant"
                          };
                }

                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);
                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);
                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message
                      };
            }
        }
Exemple #4
0
        /// <summary>
        /// Delete or reactivate an existing category
        /// </summary>
        /// <param name="id"></param>
        /// <param name="reactivate"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <returns></returns>
        public async Task <int> DeleteOrReactivate(IBaseContextModel context, long id, bool reactivate, Guid trackingGuid)
        {
            var companyId = context.Security.GetCompanyId();

            // MongoDB Settings
            var    database              = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar");
            string collectionName        = database.Collections.FirstOrDefault(x => x.Name == "PC_Category").Name;
            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 categoryCollection = db.GetCollection<Deathstar.Data.Models.PC_Category>(collectionName);

            // Filter
            var filters = Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.Id, id);

            filters = filters & Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString());

            var dbCategory = _categoryCollection.Find(filters).FirstOrDefault();

            if (dbCategory == null)
            {
                string reason = $"Category not found by Id:{id} provided.";

                IG2000.Data.Utilities.Logging.LogTrackingEvent($"Category was unable to be retrieved! Reason: {reason}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid);
                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = reason
                      };
            }

            // Set the updated timestamp here
            string timestamp = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz");

            // Update the Following Fields
            var update = Builders <Deathstar.Data.Models.PC_Category> .Update
                         .Set(x => x.IsActive, reactivate)
                         .Set(x => x.UpdatedBy, context.Security.GetEmail())
                         .Set(x => x.UpdatedDateTime, timestamp);

            // Update database record
            await _categoryCollection.UpdateOneAsync(filters, update);

            // Remove all category assignments only on delete
            if (!reactivate)
            {
                // Remove all category assignments
                var productCollection = db.GetCollection <Deathstar.Data.Models.PC_Product>(productCollectionName);
                var variantCollection = db.GetCollection <Deathstar.Data.Models.PC_ProductVariant>(variantCollectionName);

                // Find all Products Filter
                var productFilters = Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString());

                productFilters = productFilters & Builders <Deathstar.Data.Models.PC_Product> .Filter.ElemMatch(x => x.Categories, x => x.CategoryId == id);

                // Find all the products that have this category assignment
                var dbProducts = productCollection.FindAsync(productFilters).Result.ToList();

                // get a list of all the category assignments that match the categroy id
                var dbProductCategoryAssignments = dbProducts.SelectMany(x => x.Categories).Where(y => y.CategoryId == id).ToList();

                foreach (var dbProductCategoryAssignment in dbProductCategoryAssignments)
                {
                    //circular reference
                    await _categoryAssignment.DeleteOrReactivate(context, dbProductCategoryAssignment.PC_ProductCategory_Id, "PC_Product", false, trackingGuid);
                }

                // 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.ElemMatch(x => x.Categories, x => x.CategoryId == id);

                // Find all the variants that have this category assignment
                var dbVariants = variantCollection.FindAsync(variantFilters).Result.ToList();

                // get a list of all the category assignments that match the category id
                var dbVariantCategoryAssignments = dbVariants.SelectMany(x => x.Categories).Where(y => y.CategoryId == id).ToList();

                foreach (var dbVariantCategoryAssignment in dbVariantCategoryAssignments)
                {
                    //circular reference
                    await _categoryAssignment.DeleteOrReactivate(context, dbVariantCategoryAssignment.PC_ProductCategory_Id, "PC_ProductVariant", false, trackingGuid);
                }
            }
            else // if reactivating send update webhook
            {
                // Build the Webhook event
                var whRequest = new Sheev.Common.Models.WebhookResponse()
                {
                    CompanyId    = companyId.ToString(),
                    Type         = "Product Category",
                    Scope        = $"category/product/updated",
                    Id           = id.ToString(),
                    TrackingGuid = trackingGuid
                };

                // Trigger the Webhook event
                await _webHookModel.FireWebhookEvent(whRequest, context, trackingGuid);
            }

            // Update the corresponding External Id record(s)
            await _externalIdModel.DeleteOrReactivateByParentId(dbCategory.Id.ToString(), reactivate, "PC_Category", timestamp, dbCategory.UpdatedDateTime, trackingGuid, "category/product/deleted", true);

            return(Microsoft.AspNetCore.Http.StatusCodes.Status204NoContent);
        }
Exemple #5
0
        /// <summary>
        /// Update an existing category
        /// </summary>
        /// <param name="id"></param>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <returns></returns>
        public async Task <Tagge.Common.Models.CategoryResponse> Update(IBaseContextModel context, long id, 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);

                // Word
                var dbCategory = new Deathstar.Data.Models.PC_Category();

                // Check to see if the Category exists
                var existsfilter = Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.Id, id);

                existsfilter = existsfilter & Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString());

                existsfilter = existsfilter & Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.IsActive, true);

                var existsCategory = _categoryCollection.Find(existsfilter).FirstOrDefault();

                if (existsCategory == null)
                {
                    throw new HttpResponseException()
                          {
                              StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = $"Category not found by Id: {id}. Use Post to create a new 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}"
                              }
                    }
                    ;
                }

                // Convert to DB Object
                dbCategory.ConvertToDatabaseObject(companyId.ToString(), request);

                // Check for empty collections and null them
                //dbCategory.CheckForEmptyCollections();

                // Add Updated By & Timestamp
                dbCategory.UpdatedBy       = context.Security.GetEmail();
                dbCategory.UpdatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz");

                // Custom Fields
                if (request.CustomFields != null && request.CustomFields.Count > 0)
                {
                    dbCategory.CustomFields = await _customFieldModel.SaveOrUpdateGenericCustomFields(request.CustomFields, dbCategory.CustomFields, "PC_Category", id.ToString(), trackingGuid);
                }

                // Filter
                var filters = Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.Id, id);

                filters = filters & Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.IsActive, true);

                filters = filters & Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString());

                // Update
                var serializerSettings = new JsonSerializerSettings()
                {
                    NullValueHandling    = NullValueHandling.Ignore,
                    DefaultValueHandling = DefaultValueHandling.Ignore
                };

                var update = new BsonDocument()
                {
                    { "$set", BsonDocument.Parse(JsonConvert.SerializeObject(dbCategory, serializerSettings)) }
                };

                // Update database record
                await _categoryCollection.UpdateOneAsync(filters, update);

                // Convert To 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);
                }

                // Build the Webhook event
                var whRequest = new Sheev.Common.Models.WebhookResponse()
                {
                    CompanyId    = companyId.ToString(),
                    Type         = "Product Category",
                    Scope        = "category/product/updated",
                    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($"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, "CategoryModel.Update()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error);
                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message
                      };
            }
        }
Exemple #6
0
        /// <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
                      };
            }
        }
Exemple #7
0
        /// <summary>
        /// Updates an existing inventory
        /// </summary>
        /// <param name="id"></param>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <param name="fromController"></param>
        /// <returns></returns>
        public async Task <Tagge.Common.Models.InventoryResponse> Update(InventoryRequest request, long id, Guid trackingGuid, bool fromController = false)
        {
            var response  = new Tagge.Common.Models.InventoryResponse();
            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_Inventory").Name;

                // Get MongoDB
                var db = context.Database;
                var inventoryCollection = db.GetCollection <Deathstar.Data.Models.PC_Inventory>(collectionName);

                // Filter
                var filters = Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.Id, id);

                filters = filters & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.IsActive, true);

                filters = filters & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString());

                // Inventory table
                string inventoryTable = string.Empty;

                // Webhook Scope
                string scope = string.Empty;

                // Word
                var dbInventory = new Deathstar.Data.Models.PC_Inventory();

                // 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.Id, id);

                existsfilter = existsfilter & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.IsActive, true);

                var existsInventory = inventoryCollection.Find(existsfilter).FirstOrDefault();

                if (existsInventory == null)
                {
                    throw new HttpResponseException()
                          {
                              StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = $"Inventory not found by Id: {id}"
                          }
                }
                ;

                // Validate Product/Variant and set inventory table
                if (existsInventory.ST_TableName == "PC_Product")
                {
                    inventoryTable = "PC_ProductInventory";
                    scope          = "product";
                }
                else
                {
                    inventoryTable = "PC_ProductVariantInventory";
                    scope          = "product/variant";
                }

                // Verify Locations
                await LocationModel.Validate(request.LocationId, context, trackingGuid);

                // Convert to DB Object
                dbInventory.ConvertToDatabaseObject(companyId.ToString(), existsInventory.ST_TableName, request);

                // Add Updated By & Timestamp
                dbInventory.UpdatedBy       = context.Security.GetEmail();
                dbInventory.UpdatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz");

                // Custom Fields
                if (request.CustomFields != null && request.CustomFields.Count > 0)
                {
                    dbInventory.CustomFields = await _customFieldModel.SaveOrUpdateGenericCustomFields(request.CustomFields, dbInventory.CustomFields, inventoryTable, id.ToString(), trackingGuid);
                }

                // Update
                var serializerSettings = new JsonSerializerSettings()
                {
                    NullValueHandling    = NullValueHandling.Ignore,
                    DefaultValueHandling = DefaultValueHandling.Ignore
                };

                var update = new BsonDocument()
                {
                    { "$set", BsonDocument.Parse(JsonConvert.SerializeObject(dbInventory, serializerSettings)) }
                };

                // Update database record
                await inventoryCollection.UpdateOneAsync(filters, update);

                // Convert To Response
                response = dbInventory.ConvertToResponse();

                // Add Id
                response.Id = id;

                // Add back the Parent Id
                response.ParentId = Convert.ToInt64(existsInventory.InternalId);

                // ExternalIds
                if (request.ExternalIds != null && request.ExternalIds.Count > 0)
                {
                    response.ExternalIds = await _externalIdModel.SaveOrUpdateGenericExternalId(request.ExternalIds, inventoryTable, id.ToString(), trackingGuid);
                }

                // Only send webhooks when making a direct call from the controller
                if (fromController)
                {
                    // Build the Webhook event
                    var whRequest = new Sheev.Common.Models.WebhookResponse()
                    {
                        CompanyId = companyId.ToString(),
                        Type      = "Inventory",
                        Scope     = $"{scope}/inventory/updated",
                        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);
                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);
                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message
                      };
            }
        }
Exemple #8
0
        /// <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
                      };
            }
        }