Example #1
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
                      };
            }
        }
Example #2
0
        /// <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>
        /// 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);
        }
Example #4
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
                      };
            }
        }
Example #5
0
        /// <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
                          };
                }
            }
        }
Example #6
0
        /// <summary>
        /// Save a new location
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <returns></returns>
        public async Task <Tagge.Common.Models.LocationResponse> Save(Tagge.Common.Models.LocationRequest request, Guid trackingGuid)
        {
            var response  = new Tagge.Common.Models.LocationResponse();
            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_Location").Name;

                // Get MongoDB
                var db = context.Database;
                var locationCollection = db.GetCollection <Deathstar.Data.Models.PC_Location>(collectionName);
                var counterCollection  = db.GetCollection <Deathstar.Data.Models.Counter>("Counters");

                // filter
                var filter = Builders <Deathstar.Data.Models.Counter> .Filter.Eq(x => x.Id, "location_id");

                var update = Builders <Deathstar.Data.Models.Counter> .Update.Inc("Seq", 1);

                // Word
                var dbLocation = new Deathstar.Data.Models.PC_Location();

                // 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_Location> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString());

                duplicatefilter = duplicatefilter & Builders <Deathstar.Data.Models.PC_Location> .Filter.Where(x => x.Name.ToLower() == lowername);

                var duplicateLocation = locationCollection.Find(duplicatefilter).ToList();

                if (duplicateLocation != null && duplicateLocation.Count > 0)
                {
                    string reason = $"Location ({request.Name}) already exist.";

                    IG2000.Data.Utilities.Logging.LogTrackingEvent($"Location ({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
                dbLocation.ConvertToDatabaseObject(companyId.ToString(), request);

                // Location Groups
                if (request.LocationGroups != null && request.LocationGroups.Count > 0)
                {
                    dbLocation.LocationGroups = await LocationGroupModel.SaveOrUpdate(request.LocationGroups, new List <Deathstar.Data.Models.TM_GenericEntry>(), context, trackingGuid);
                }

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

                // Add Id
                dbLocation.Id = id;

                // Add Created By & Timestamp
                dbLocation.CreatedBy       = context.Security.GetEmail();
                dbLocation.CreatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz");

                // IsActive
                dbLocation.IsActive = true;

                // Insert
                await locationCollection.InsertOneAsync(dbLocation);

                // Building the Response
                response = dbLocation.ConvertToResponse();

                // Add Id
                response.Id = id;

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

                IG2000.Data.Utilities.Logging.LogTrackingEvent($"Location (id: {dbLocation.Id}, sku: {dbLocation.Name}) successfully saved.", "Save Location", LT319.Common.Utilities.Constants.TrackingStatus.Complete, context, trackingGuid);

                // Trigger the Webhook event
                //var whRequest = new Sheev.Common.Models.WebhookResponse()
                //{
                //    CompanyId = companyId.ToString(),
                //    Type = "Location",
                //    Scope = "location/created",
                //    Id = response.Id.ToString(),
                //    TrackingGuid = trackingGuid
                //};

                //await Models.WebhookModel.FireWebhookEvent(whRequest, context, trackingGuid);


                return(response);
            }
            catch (HttpResponseException webEx)
            {
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"Location ( 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, "LocationModel.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error);
                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message
                      };
            }
        }
Example #7
0
        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
                      };
            }
        }
Example #8
0
        /// <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
                      };
            }
        }
Example #9
0
        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);
        }