Пример #1
0
        /// <summary>
        /// Internal Use Only! saves or Updates a Kit
        /// </summary>
        /// <param name="request"></param>
        /// <param name="dbExistingKit"></param>
        /// <param name="internalId"></param>
        /// <param name="tableName"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <returns></returns>
        public async Task <Deathstar.Data.Models.PC_Kit> SaveOrUpdate(long internalId, string tableName, Deathstar.Data.Models.PC_Kit dbExistingKit, Tagge.Common.Models.KitRequest request, Guid trackingGuid)
        {
            // Is update or new?
            bool isUpdate = true;

            // INitialize the kit
            var dbKit = new Deathstar.Data.Models.PC_Kit();

            // Word
            if (dbExistingKit == null)
            {
                dbKit    = new Deathstar.Data.Models.PC_Kit();
                isUpdate = false;
            }

            try
            {
                if (isUpdate)
                {
                    // Setting the Primary Key or Id field to check if the existing kit matches the incoming update kit
                    dbKit.SetPrimaryKey(internalId.ToString(), request.Sku);

                    if (dbExistingKit.PC_Kit_Id != dbKit.PC_Kit_Id)
                    {
                        throw new HttpResponseException()
                              {
                                  StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Kit Id does not found"
                              }
                    }
                    ;

                    // Set Existing Kit to the new one
                    dbKit = dbExistingKit;

                    // Validate Kit Type
                    await _typeModel.ValidateKitType(request.Type, trackingGuid);

                    // Update
                    // Convert request to Location
                    dbKit.ConvertToDatabaseObject(request);

                    // Components
                    if (request.Components != null && request.Components.Count > 0)
                    {
                        dbKit.Components = await _kitComponentModel.SaveOrUpdate(dbKit.PC_Kit_Id, tableName, request.Components, dbExistingKit.Components, trackingGuid);
                    }

                    // Custom Fields
                    if (request.CustomFields != null && request.CustomFields.Count > 0)
                    {
                        dbKit.CustomFields = await _customFieldModel.SaveOrUpdateGenericCustomFields(request.CustomFields, dbKit.CustomFields, tableName, dbKit.PC_Kit_Id, trackingGuid);
                    }

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

                    // IsActive
                    dbKit.IsActive = true;

                    IG2000.Data.Utilities.Logging.LogTrackingEvent($"Kit (sku: {dbKit.Sku} successfully updated.", "Update Kit", LT319.Common.Utilities.Constants.TrackingStatus.Complete, context, trackingGuid);

                    // ExternalIds
                    if (request.ExternalIds != null && request.ExternalIds.Count > 0)
                    {
                        await _externalIdModel.SaveOrUpdateGenericExternalId(request.ExternalIds, tableName, dbKit.PC_Kit_Id, trackingGuid);
                    }
                }
                else
                {
                    // Add
                    dbKit = await Save(internalId, tableName, request, trackingGuid);
                }

                return(dbKit);
            }
            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, "LocationModel.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error);
                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message
                      };
            }
        }
        /// <summary>
        /// Updates an existing category set
        /// </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.CategorySetResponse> Update(long id, Tagge.Common.Models.CategorySetRequest request, Models.ContextModel context, Guid trackingGuid)
        public async Task <Tagge.Common.Models.CategorySetResponse> Update(IBaseContextModel context, long id, Tagge.Common.Models.CategorySetRequest request, Guid trackingGuid)
        {
            var response  = new Tagge.Common.Models.CategorySetResponse();
            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_CategorySet").Name;

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

                // Word
                var dbCategorySet = new Deathstar.Data.Models.PC_CategorySet();

                // Check to see if the Category Set is a duplicate
                var duplicatefilter = Builders <Deathstar.Data.Models.PC_CategorySet> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString());

                duplicatefilter = duplicatefilter & Builders <Deathstar.Data.Models.PC_CategorySet> .Filter.Eq(x => x.Id, id);

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

                var categoryExists = _categorySetCollection.Find(duplicatefilter).FirstOrDefault();

                if (categoryExists == null)
                {
                    throw new HttpResponseException()
                          {
                              StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Category Set Already Exists. Use PUT to update category. (Id = {categoryExists.Id})!"
                          }
                }
                ;

                // Validate Category Sets
                await Validate(context, request.Categories, trackingGuid);////new CategoryModel(context).Validate(request.Categories, trackingGuid);

                // Convert request to Category
                dbCategorySet.ConvertToDatabaseObject(companyId.ToString(), request);

                // Categories
                if (request.Categories != null && request.Categories.Count > 0)
                {
                    foreach (var category in request.Categories)
                    {
                        dbCategorySet.Categories.Add(new Deathstar.Data.Models.TM_GenericEntry()
                        {
                            Name       = category.Name,
                            InternalId = category.Id
                        });
                    }
                }

                // Custom Fields
                if (request.CustomFields != null && request.CustomFields.Count > 0)
                {
                    dbCategorySet.CustomFields = await _customFielModel.SaveOrUpdateGenericCustomFields(request.CustomFields, categoryExists.CustomFields, "PC_CategorySet", id.ToString(), trackingGuid);
                }

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

                dbCategorySet.IsActive = true;

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

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

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

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

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


                // Save or Update database record
                await _categorySetCollection.UpdateOneAsync(filters, update);

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

                // Add Id
                response.Id = id;

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


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

                // Trigger the Webhook event
                //if (_useWebhook)
                //{
                //    var whRequest = new WebhookResponse()
                //    {
                //        CompanyId = companyId.ToString(),
                //        Type = "Product Category",
                //        Scope = "category/product/created",
                //        Id = response.Id.ToString(),
                //        TrackingGuid = trackingGuid
                //    };

                //    WebhookModel.WebhookTriggerEvent(whRequest, trackingGuid);
                //}

                return(response);
            }
            catch (HttpResponseException webEx)
            {
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"Category Set ( 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, "CategorySet.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error);
                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message
                      };
            }
        }
Пример #3
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
                      };
            }
        }
Пример #4
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
                      };
            }
        }
        /// <summary>
        /// Internal Use Only! Save a Kit Component
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="tableName"></param>
        /// <param name="request"></param>
        /// <param name="dbExistingComponents"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <returns></returns>
        public async Task <List <Deathstar.Data.Models.PC_KitComponent> > SaveOrUpdate(string parentId, string tableName, List <Tagge.Common.Models.KitComponentRequest> request, List <Deathstar.Data.Models.PC_KitComponent> dbExistingComponents, Guid trackingGuid)
        {
            try
            {
                foreach (var requestComponent in request)
                {
                    // Check to see if sku is populated if not error
                    if (string.IsNullOrEmpty(requestComponent.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 (requestComponent.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(requestComponent.Unit))
                    {
                        throw new HttpResponseException()
                              {
                                  StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = "Unit value not found"
                              }
                    }
                    ;

                    // Validate Kit Component Type
                    await _typeModel.ValidateKitComponentType(requestComponent.Type, trackingGuid);

                    // Validate the sku & unit
                    await ValidateModel.ValidateSkuAndUnit(requestComponent.Sku, requestComponent.Unit, context, trackingGuid);

                    // Building the component
                    // Why not using ConvertToDatabaseObject?
                    var dbComponent = new Deathstar.Data.Models.PC_KitComponent();

                    // Convert To Database object
                    dbComponent.ConvertToDatabaseObject(requestComponent);

                    // Set Primary Key
                    dbComponent.SetPrimaryKey(parentId, requestComponent.Unit);

                    // Check to see if the component already exists on this kit
                    var dbExistingComponent = dbExistingComponents.FirstOrDefault(x => x.PC_KitComponent_Id == dbComponent.PC_KitComponent_Id);

                    // Set correct tablename
                    if (!tableName.Contains("Component"))
                    {
                        tableName = tableName + "Component";
                    }

                    // Add the Component
                    if (dbExistingComponent == null)
                    {
                        // Custom Fields
                        if (requestComponent.CustomFields != null && requestComponent.CustomFields.Count > 0)
                        {
                            dbComponent.CustomFields = await _customFieldModel.SaveGenericCustomField(requestComponent.CustomFields, tableName, dbComponent.PC_KitComponent_Id, trackingGuid);
                        }

                        // ExternalIds
                        if (requestComponent.ExternalIds != null && requestComponent.ExternalIds.Count > 0)
                        {
                            await _externalIdModel.SaveOrUpdateGenericExternalId(requestComponent.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
                        dbExistingComponents.Add(dbComponent);
                    }
                    else // Update the Component
                    {
                        // Set existing component to current component
                        dbExistingComponent.Quantity = requestComponent.Quantity;
                        dbExistingComponent.Type     = requestComponent.Type;

                        // Custom Fields
                        if (requestComponent.CustomFields != null && requestComponent.CustomFields.Count > 0)
                        {
                            dbExistingComponent.CustomFields = await _customFieldModel.SaveOrUpdateGenericCustomFields(requestComponent.CustomFields, dbExistingComponent.CustomFields, tableName, dbComponent.PC_KitComponent_Id, trackingGuid);
                        }

                        // ExternalIds
                        if (requestComponent.ExternalIds != null && requestComponent.ExternalIds.Count > 0)
                        {
                            await _externalIdModel.SaveOrUpdateGenericExternalId(requestComponent.ExternalIds, tableName, dbComponent.PC_KitComponent_Id, trackingGuid);
                        }

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

                        // IsActive
                        dbExistingComponent.IsActive = true;
                    }
                }
            }
            catch (HttpResponseException)
            {
                throw;
            }

            return(dbExistingComponents);
        }
Пример #6
0
        /// <summary>
        /// Internal Use Only! Save variant options
        /// </summary>
        /// <param name="variantId"></param>
        /// <param name="dbProduct"></param>
        /// <param name="request"></param>
        /// <param name="dbExistingVariantOptions"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <returns></returns>
        public async Task <List <Deathstar.Data.Models.PC_OptionValue> > SaveOrUpdateVariantOptions(long variantId, Deathstar.Data.Models.PC_Product dbProduct, List <Tagge.Common.Models.OptionValueRequest> request, List <Deathstar.Data.Models.PC_OptionValue> dbExistingVariantOptions, Guid trackingGuid)
        {
            // The Response
            var dbOptionValues = new List <Deathstar.Data.Models.PC_OptionValue>();

            try
            {
                foreach (var optionValue in request)
                {
                    // Product Option
                    var dbProductOption = new Deathstar.Data.Models.PC_Option();

                    // Look up existing options for parent product
                    var dbProductOptions = dbProduct.Options.Where(x => x.IsActive).ToList();

                    // Check request option against parent product options based on Name
                    if (string.IsNullOrEmpty(optionValue.OptionName))
                    {
                        throw new HttpResponseException()
                              {
                                  StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Variant Option Name is Required"
                              };
                    }

                    dbProductOption = dbProductOptions.FirstOrDefault(x => x.Name.ToLower() == optionValue.OptionName.ToLower());

                    if (dbProductOption == null)
                    {
                        throw new HttpResponseException()
                              {
                                  StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"The Product(Id: {dbProduct.Id}) this Variant(Id: {variantId}) is a part of does not have any Product Options set that match the Variant Option Request. Please add options at the product level first."
                              };
                    }

                    // Check request option value against parent product option values- Bug 3199
                    if (!string.IsNullOrEmpty(optionValue.Value))
                    {
                        var dbProductOptionValue = dbProductOption.Values.FirstOrDefault(x => x.Value.ToLower() == optionValue.Value.ToLower() && x.IsActive);

                        if (dbProductOptionValue == null)
                        {
                            throw new HttpResponseException()
                                  {
                                      StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Product Variant Option Value: {optionValue.Value} must first be set as Option Value for parent Product Id: {dbProduct.Id}, Option: {dbProductOption.Name}."
                                  };
                        }
                    }

                    // Bug: 3198, 3398 <- See pervious version of the api for these bugs
                    if (string.IsNullOrEmpty(optionValue.Value))
                    {
                        throw new HttpResponseException()
                              {
                                  StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Variant Option Value is Required"
                              };
                    }

                    // Look up if Variant Option already exists in the db
                    var dbOptionValue = new Deathstar.Data.Models.PC_OptionValue();

                    // Convert Request to database object
                    dbOptionValue.ConvertToDatabaseObject(optionValue);

                    // Set Primary Key
                    dbOptionValue.SetPrimaryKey(dbProduct.Id.ToString(), variantId.ToString(), optionValue.OptionName, optionValue.Value);

                    // Check to see if the variant option already exists
                    var dbExistingOptionValue = dbExistingVariantOptions.FirstOrDefault(x => x.PC_OptionValue_Id == dbOptionValue.PC_OptionValue_Id);

                    // Add existing option value
                    if (dbExistingOptionValue == null)
                    {
                        // Set Created By & Created Date Time
                        dbOptionValue.CreatedBy       = context.Security.GetEmail();
                        dbOptionValue.CreatedDateTime = 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_ProductVariantOption", dbOptionValue.PC_OptionValue_Id, trackingGuid);
                        }

                        // ExternalIds
                        if (optionValue.ExternalIds != null && optionValue.ExternalIds.Count > 0)
                        {
                            await _externalIdModel.SaveOrUpdateGenericExternalId(optionValue.ExternalIds, "PC_ProductVariantOption", dbOptionValue.PC_OptionValue_Id, trackingGuid);
                        }
                    }
                    else // Update existing option value
                    {
                        // Set existing option value to current option value
                        dbOptionValue = dbExistingOptionValue;

                        // Set Updated By & Updated Date Time
                        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.SaveOrUpdateGenericCustomFields(optionValue.CustomFields, dbExistingOptionValue.CustomFields, "PC_ProductVariantOption", dbOptionValue.PC_OptionValue_Id, trackingGuid);
                        }

                        // ExternalIds
                        if (optionValue.ExternalIds != null && optionValue.ExternalIds.Count > 0)
                        {
                            await _externalIdModel.SaveOrUpdateGenericExternalId(optionValue.ExternalIds, "PC_ProductVariantOption", dbOptionValue.PC_OptionValue_Id, trackingGuid);
                        }
                    }

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

                    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, "CatalogModel.SaveProduct()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error);

                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message
                      };
            }
        }
Пример #7
0
        /// <summary>
        /// Updates an existing location
        /// </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.LocationResponse> Update(long id, Tagge.Common.Models.LocationRequest request, Guid trackingGuid)
        {
            var response  = new Tagge.Common.Models.LocationResponse();
            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_Location").Name;

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

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

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

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

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

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

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

            var dbExistingLocation = await locationCollection.FindAsync(existsfilter).Result.FirstOrDefaultAsync();

            if (dbExistingLocation == null)
            {
                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = $"Location ({id}) Not Found."
                      }
            }
            ;

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

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

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

            // Location Groups
            if (request.LocationGroups != null && request.LocationGroups.Count > 0)
            {
                dbLocation.LocationGroups = await LocationGroupModel.SaveOrUpdate(request.LocationGroups, dbExistingLocation.LocationGroups, context, trackingGuid);
            }

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

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

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

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

            // Update database record
            await locationCollection.UpdateOneAsync(filter, update);

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

            ////Trigger the Webhook event
            //if (_useWebhook)
            //{
            //    var whRequest = new WebhookResponse()
            //    {
            //        CompanyId = companyId.ToString(),
            //        Type = "Product",
            //        Scope = "product/updated",
            //        Id = response.Id.ToString()
            //    };

            //    Models.WebhookModel.WebhookTriggerEvent(whRequest, trackingGuid);
            //}

            return(response);
        }
Пример #8
0
        /// <summary>
        /// Updates an existing Alternate Id Type
        /// </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.AlternateIdTypeResponse> Update(IBaseContextModel context, long id, Tagge.Common.Models.AlternateIdTypeRequest request, Guid trackingGuid)
        {
            // Response
            var response = new Tagge.Common.Models.AlternateIdTypeResponse();

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

                // Word
                var dbAlternateIdType = new Deathstar.Data.Models.PC_AlternateIdType();

                // Build the filters that will be used for both updating the record and checking to see if it exists
                // Check to see if the Alternate Id Type exists
                var filters = Builders <Deathstar.Data.Models.PC_AlternateIdType> .Filter.Eq(x => x.Id, id);

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

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

                // Find that alternate id type
                var dbExistingAlternateIdType = alternateIdTypeCollection.Find(filters).FirstOrDefault();

                // Could it be missing? if so throw error
                if (dbExistingAlternateIdType == null)
                {
                    throw new HttpResponseException()
                          {
                              StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = $"Alternate Id Type not found by Id: {id}"
                          }
                }
                ;

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

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

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

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

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

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

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

                // Add Id
                response.Id = id;

                ////Trigger the Webhook event
                //if (_useWebhook)
                //{
                //    var whRequest = new WebhookResponse()
                //    {
                //        CompanyId = companyId.ToString(),
                //        Type = "Product",
                //        Scope = "product/updated",
                //        Id = response.Id.ToString()
                //    };

                //    Models.WebhookModel.WebhookTriggerEvent(whRequest, trackingGuid);
                //}

                return(response);
            }
            catch (HttpResponseException webEx)
            {
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"Location Group ( Name: {request.Name}) failed to save! Reason: {webEx.ReasonPhrase}", $"Status Code: {webEx.StatusCode}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid);
                throw;
            }
            catch (Exception ex)
            {
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"See logs for additional details", "Failed", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid);
                IG2000.Data.Utilities.ErrorLogger.Report(ex.Message, "LocationGroupModel.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error);
                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message
                      };
            }
        }