public InventoryModel(ICustomFieldModel customFieldModel, IExternalIdModel externalIdModel, IWebhookModel webHookModel, IBaseContextModel contextModel, ICategoryAssignmentModel categoryAssignmentModel) { _webHookModel = webHookModel; context = contextModel; _externalIdModel = externalIdModel; _customFieldModel = customFieldModel; }
public CategoryAssignmentModel(IBaseContextModel contextModel, IWebhookModel webHookModel) ////public CategoryAssignmentModel(IBaseContextModel contextModel, IWebhookModel webHookModel, IOptions<Sheev.Common.Models.MongoDbSetting> mongoDbSettings, IOptions<Sheev.Common.Models.ApiUrlSetting> apiSettings) { _webHookModel = webHookModel; context = contextModel; //context = new Models.ContextModel(mongoDbSettings, apiSettings); }
/// <summary> /// Saves a product category assignment when attached to a product /// Internal Use Only! /// </summary> /// <param name="internalId">Parent id like product or variant id</param> /// <param name="request"></param> /// <param name="existingCategories"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task <List <Deathstar.Data.Models.PC_ProductCategory> > Save(IBaseContextModel context, long internalId, List <Sheev.Common.Models.GenericRequest> request, List <Deathstar.Data.Models.PC_ProductCategory> existingCategories, Guid trackingGuid) { List <Deathstar.Data.Models.PC_ProductCategory> dbProductCategories = new List <Deathstar.Data.Models.PC_ProductCategory>(); try { // Verify that the category exists ////Circular Reference await CategoryModel.Validate(request, context, trackingGuid); // if null then create an empty list if (existingCategories == null) { existingCategories = new List <Deathstar.Data.Models.PC_ProductCategory>(); } else // Add existing kids to the group so they are not left at the park { dbProductCategories = existingCategories; } foreach (var productCategoryRequest in request) { // make sure the id is a big int long.TryParse(productCategoryRequest.Id, out long categoryId); // Check to see if it already exists on the product/variant var duplicateCategory = existingCategories.FirstOrDefault(x => x.CategoryId == categoryId); // If its not already on the parent then add it else ignore if (duplicateCategory == null) { var dbProductCategory = new Deathstar.Data.Models.PC_ProductCategory(); dbProductCategory.ConvertToGenericDatabaseObject(productCategoryRequest); // Set Primary Key dbProductCategory.SetPrimaryKey(internalId.ToString(), productCategoryRequest.Id); dbProductCategory.IsActive = true; dbProductCategories.Add(dbProductCategory); } } return(dbProductCategories); } catch (HttpResponseException) { 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, "CategoryAssignmentModel.SaveToProduct()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message }; } throw new NotImplementedException(); }
public KitComponentModel(ICustomFieldModel customFieldModel, IBaseContextModel contextModel, ITypeModel typeModel, IExternalIdModel externalIdModel) { _customFieldModel = customFieldModel; _externalIdModel = externalIdModel; _typeModel = typeModel; context = contextModel; }
public LocationGroupModel(ICustomFieldModel customFieldModel, IExternalIdModel externalIdModel, IBaseContextModel contextModel, ICategoryAssignmentModel categoryAssignmentModel, IOptions <Sheev.Common.Models.MongoDbSetting> mongoDbSettings, IOptions <Sheev.Common.Models.ApiUrlSetting> apiSettings) { ////context = contextModel; context = new Models.ContextModel(mongoDbSettings, apiSettings); _externalIdModel = externalIdModel; _customFieldModel = customFieldModel; }
public LocationModel(ICustomFieldModel customFieldModel, IExternalIdModel externalIdModel, IBaseContextModel contextModel, IOptions <Sheev.Common.Models.MongoDbSetting> mongoDbSettings, IOptions <Sheev.Common.Models.ApiUrlSetting> apiSettings) { context = new Models.ContextModel(mongoDbSettings, apiSettings); //context = contextModel; _externalIdModel = externalIdModel; _customFieldModel = customFieldModel; }
/// <summary> /// Validate by Id /// </summary> /// <param name="locationGroups"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public static async Task <string> Validate(long locationGroupId, IBaseContextModel context, Guid trackingGuid) { // Company Id var companyId = context.Security.GetCompanyId(); // Location Group Table var locationGroupCollection = context.Database.GetCollection <Deathstar.Data.Models.PC_LocationGroup>("PC_LocationGroup"); // Filter var filters = Builders <Deathstar.Data.Models.PC_LocationGroup> .Filter.Eq(x => x.Id, locationGroupId); filters = filters & Builders <Deathstar.Data.Models.PC_LocationGroup> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); var dbLocationGroup = await locationGroupCollection.FindAsync(filters).Result.FirstOrDefaultAsync(); if (dbLocationGroup == null) { string reason = $"Location group not found by Id:{locationGroupId} provided."; IG2000.Data.Utilities.Logging.LogTrackingEvent($"Location group was unable to be retrieved! 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 }; } return(dbLocationGroup.Name); }
/// <summary> /// Validate a single Alternate Id Type by id /// </summary> /// <param name="alternateIdTypeId"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task Validate(IBaseContextModel context, long alternateIdTypeId, Guid trackingGuid) { // Company Id var companyId = context.Security.GetCompanyId(); var alternateIdTypeCollection = context.Database.GetCollection <Deathstar.Data.Models.PC_AlternateIdType>("PC_AlternateIdType"); // Filter var filters = Builders <Deathstar.Data.Models.PC_AlternateIdType> .Filter.Eq(x => x.Id, alternateIdTypeId); filters = filters & Builders <Deathstar.Data.Models.PC_AlternateIdType> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); var dbAlternateIdType = await alternateIdTypeCollection.FindAsync(filters).Result.FirstOrDefaultAsync(); if (dbAlternateIdType == null) { string reason = $"Alternate Id Type not found by Id:{alternateIdTypeId} provided."; IG2000.Data.Utilities.Logging.LogTrackingEvent($"Alternate Id Type was unable to be retrieved! 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 }; } }
/// <summary> /// Validates a set of generic request category sets /// </summary> /// <param name="categorySets"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task Validate(IBaseContextModel context, List <Sheev.Common.Models.GenericRequest> categorySets, Guid trackingGuid) { // Company Id var companyId = context.Security.GetCompanyId(); //var categorySetCollection = context.Database.GetCollection<Deathstar.Data.Models.PC_CategorySet>("PC_CategorySet"); if (categorySets != null && categorySets.Count > 0) { foreach (var categorySet in categorySets) { Int64.TryParse(categorySet.Id, out long longId); // Filter var filters = Builders <Deathstar.Data.Models.PC_CategorySet> .Filter.Eq(x => x.Id, longId); filters = filters & Builders <Deathstar.Data.Models.PC_CategorySet> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); var dbCategory = await _categorySetCollection.FindAsync(filters).Result.FirstOrDefaultAsync(); if (dbCategory == null) { string reason = $"Category Set not found by Id:{longId} provided."; IG2000.Data.Utilities.Logging.LogTrackingEvent($"Category Set was unable to be retrieved! 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 }; } } } }
public OptionModel(IExternalIdModel externalIdModel, ICustomFieldModel customFieldModel, IOptionValueModel optionValueModel, IBaseContextModel contextModel) { context = contextModel; _optionValueModel = optionValueModel; _customFieldModel = customFieldModel; _externalIdModel = externalIdModel; }
public AlternateIdTypeModel(ICustomFieldModel customFieldModel, IExternalIdModel externalIdModel, IBaseContextModel contextModel, IOptions <Sheev.Common.Models.MongoDbSetting> mongoDbSettings, IOptions <Sheev.Common.Models.ApiUrlSetting> apiSettings) { //context = contextModel; context = new Models.ContextModel(mongoDbSettings, apiSettings); _alternateIdTypeCollection = context.Database.GetCollection <Deathstar.Data.Models.PC_AlternateIdType>("PC_AlternateIdType"); _externalIdModel = externalIdModel; _customFieldModel = customFieldModel; }
////public CategorySetModel(ICustomFieldModel customFielModel, IExternalIdModel externalIdModel, IBaseContextModel contextModel)//, ICategorySetModel categorySet) public CategorySetModel(ICustomFieldModel customFielModel, IExternalIdModel externalIdModel, IBaseContextModel contextModel)//, ICategorySetModel categorySet) { context = contextModel; _categorySetCollection = context.Database.GetCollection <Deathstar.Data.Models.PC_CategorySet>("PC_CategorySet"); //_categorySet = categorySet; _externalIdModel = externalIdModel; _customFielModel = customFielModel; }
//cr (circular reference) ////public CategoryModel(ICustomFieldModel customFieldModel, IBaseContextModel contextModel, IExternalIdModel externalIdModel, IWebhookModel webHookModel, ICategoryAssignmentModel categoryAssignment, ICategorySetModel categorySetModel, IOptions<Sheev.Common.Models.MongoDbSetting> mongoDbSettings, IOptions<Sheev.Common.Models.ApiUrlSetting> apiSettings) public CategoryModel(ICategoryAssignmentModel categoryAssignment, ICustomFieldModel customFieldModel, IBaseContextModel contextModel, IExternalIdModel externalIdModel, IWebhookModel webHookModel, ICategorySetModel categorySetModel, IOptions <Sheev.Common.Models.MongoDbSetting> mongoDbSettings, IOptions <Sheev.Common.Models.ApiUrlSetting> apiSettings) { context = contextModel; /////context = new Models.ContextModel(mongoDbSettings, apiSettings); _categoryCollection = contextModel.Database.GetCollection <Deathstar.Data.Models.PC_Category>("PC_Category"); _categorySetModel = categorySetModel; _categoryAssignment = categoryAssignment; _webHookModel = webHookModel; _externalIdModel = externalIdModel; _customFieldModel = customFieldModel; }
////public ProductModel(ITypeModel typeModel, IAlternateIdModel alternateIdModel, IKitModel kitModel, ICustomFieldModel customFieldModel, IOptionModel optionModel, IUnitModel unitModel, IInventoryModel inventoryModel, IExternalIdModel externalIdModel, IVariantModel variantModel, IWebhookModel webHookModel, IBaseContextModel contextModel, ICategoryAssignmentModel categoryAssignmentModel) public ProductModel(ICustomFieldModel customFieldModel, ITypeModel typeModel, IAlternateIdModel alternateIdModel, IKitModel kitModel, IOptionModel optionModel, IUnitModel unitModel, IInventoryModel inventoryModel, IExternalIdModel externalIdModel, IVariantModel variantModel, IWebhookModel webHookModel, IBaseContextModel contextModel, ICategoryAssignmentModel categoryAssignmentModel, IOptions <Sheev.Common.Models.MongoDbSetting> mongoDbSettings, IOptions <Sheev.Common.Models.ApiUrlSetting> apiSettings) { _categoryAssignmentModel = categoryAssignmentModel; _webHookModel = webHookModel; context = new Models.ContextModel(mongoDbSettings, apiSettings); ////context = contextModel; _variantModel = variantModel; _externalIdModel = externalIdModel; _inventoryModel = inventoryModel; _unitModel = unitModel; _optionModel = optionModel; _customFieldModel = customFieldModel; _kitModel = kitModel; _alternateIdModel = alternateIdModel; _typeModel = typeModel; }
/// <summary> /// Get an existing category by its id /// </summary> /// <param name="id"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task <Tagge.Common.Models.CategoryResponse> GetById(IBaseContextModel context, long id, Guid trackingGuid) { // Company Id var companyId = context.Security.GetCompanyId(); //// MongoDB Settings //var database = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar"); //string collectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_Category").Name; //// Get MongoDB //var db = context.Database; //var categoryCollection = db.GetCollection<Deathstar.Data.Models.PC_Category>(collectionName); // Filter var filters = Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.Id, id); filters = filters & Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); var dbCategory = await _categoryCollection.FindAsync(filters).Result.FirstOrDefaultAsync(); if (dbCategory == null) { string reason = $"Category not found by Id:{id} provided."; IG2000.Data.Utilities.Logging.LogTrackingEvent($"Category was unable to be retrieved! Reason: {reason}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = reason }; } IG2000.Data.Utilities.Logging.LogTrackingEvent($"Category (id: {dbCategory.Id}, name: {dbCategory.Name}) successfully retrieved.", "Get Category", LT319.Common.Utilities.Constants.TrackingStatus.Complete, context, trackingGuid); // Build the Response var response = dbCategory.ConvertToResponse(); // Add Id response.Id = dbCategory.Id; // External Ids response.ExternalIds = await _externalIdModel.GetByParentId(dbCategory.Id.ToString(), "PC_Category", trackingGuid); return(response); }
/// <summary> /// Delete or Reactivate a category set /// </summary> /// <param name="id"></param> /// <param name="reactivate"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task <int> DeleteOrReactivate(IBaseContextModel context, long id, bool reactivate, Guid trackingGuid) { var companyId = context.Security.GetCompanyId(); //// MongoDB Settings //var database = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar"); //string collectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_CategorySet").Name; //// Get MongoDB //var db = context.Database; //var categorySetCollection = db.GetCollection<Deathstar.Data.Models.PC_CategorySet>(collectionName); // 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.DV_CompanyId, companyId.ToString()); var dbCategorySet = _categorySetCollection.Find(filters).FirstOrDefault(); if (dbCategorySet == null) { string reason = $"Location Group not found by Id:{id} provided."; IG2000.Data.Utilities.Logging.LogTrackingEvent($"Location Group was unable to be retrieved! Reason: {reason}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = reason }; } // Update the Following Fields var update = Builders <Deathstar.Data.Models.PC_CategorySet> .Update .Set(x => x.IsActive, reactivate) .Set(x => x.UpdatedBy, context.Security.GetEmail()) .Set(x => x.UpdatedDateTime, DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz")); // Update database record await _categorySetCollection.UpdateOneAsync(filters, update); return(Microsoft.AspNetCore.Http.StatusCodes.Status204NoContent); }
/// <summary> /// Validates a sku at either the product/variant level then validates the unit at the parent level /// </summary> /// <param name="sku"></param> /// <param name="unitName"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> internal static async Task ValidateSkuAndUnit(string sku, string unitName, IBaseContextModel context, Guid trackingGuid) { // Create a product to test for Units var dbProduct = new Deathstar.Data.Models.PC_Product(); // Product Component dbProduct = await ProductModel.ValidateBySku(sku, context, trackingGuid); if (dbProduct == null) { var dbVariant = await VariantModel.ValidateBySku(sku, context, trackingGuid); if (dbVariant == null) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Invalid sku: {sku}" } } ; dbProduct = await ProductModel.ValidateById(dbVariant.ParentId.ToString(), context, trackingGuid); } // Validate Unit var dbProductUnit = dbProduct.Units.FirstOrDefault(x => x.Name.ToLower() == unitName.ToLower() && x.IsActive); if (dbProductUnit == null) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"FOR GLORY AND HONOR {unitName}" } } ; } #endregion } }
public TypeModel(IBaseContextModel contextModel) { context = contextModel; }
/// <summary> /// Checks for duplicate skus /// </summary> /// <param name="id"></param> /// <param name="sku"></param> /// <returns></returns> public static async Task CheckForDuplicateSkus(string sku, string companyId, IMongoCollection <Deathstar.Data.Models.PC_Product> productCollection, IBaseContextModel context, Guid trackingGuid) { var duplicatefilter = Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.Sku, sku); duplicatefilter = duplicatefilter & Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.DV_CompanyId, companyId); var duplicateSku = await productCollection.Find(duplicatefilter).ToListAsync(); if (duplicateSku != null && duplicateSku.Count > 0) { string reason = $"Duplicate Sku ({sku}) found on another Product"; IG2000.Data.Utilities.Logging.LogTrackingEvent($"Product was unable to be saved! 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 }; } }
/// <summary> /// Save or Update Locations /// </summary> /// <param name="request"></param> /// <param name="existingLocations"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public static async Task <List <Deathstar.Data.Models.TM_GenericEntry> > SaveOrUpdate(List <Sheev.Common.Models.GenericRequest> request, List <Deathstar.Data.Models.TM_GenericEntry> existingLocations, IBaseContextModel context, Guid trackingGuid) { // Initialize the new collection var dbLocations = new List <Deathstar.Data.Models.TM_GenericEntry>(); try { // Null check so we dont throw an error after this when we try to access the collection if (existingLocations == null || existingLocations.Count <= 0) { existingLocations = new List <Deathstar.Data.Models.TM_GenericEntry>(); } foreach (var locationGroupRequest in request) { // Check to see if there is a duplicate custom field already in the list var dupLocationGroup = dbLocations.FirstOrDefault(x => x.InternalId.ToLower() == locationGroupRequest.Id.ToLower()); // if so error! if (dupLocationGroup != null) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Duplicate location group '{locationGroupRequest.Id}' is not allowed" } } ; // Check to see if the location already exists on the collection var dbLocationGroup = existingLocations.FirstOrDefault(x => x.InternalId.ToLower() == locationGroupRequest.Id.ToLower()); // Validate Id if (!long.TryParse(locationGroupRequest.Id, out long locationId)) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Invalid location id group '{locationGroupRequest.Id}'" } } ; // Validate Location Group string locationGroupName = await Validate(locationId, context, trackingGuid); // if it does then update else add <- yes that is backwards from the logic below... deal with it if (dbLocationGroup == null) { dbLocationGroup = new Deathstar.Data.Models.TM_GenericEntry(); dbLocationGroup.ConvertToDatabaseObject(locationGroupRequest); dbLocationGroup.Name = locationGroupName; } else { dbLocationGroup.InternalId = locationGroupRequest.Id; dbLocationGroup.Name = locationGroupName; } // Add the custom field back into the collection dbLocations.Add(dbLocationGroup); } return(dbLocations); } catch (HttpResponseException) { 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.UpdateGenericCustomField()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message }; } }
/// <summary> /// Validates a Product by Sku and unit (actually validates the unit seperately) /// </summary> /// <param name="sku"></param> /// <param name="unitName"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public static async Task <Deathstar.Data.Models.PC_Product> ValidateBySku(string sku, IBaseContextModel context, Guid trackingGuid) { // 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.Sku, sku); filters = filters & Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.IsActive, true); var dbProduct = await productCollection.FindAsync(filters).Result.FirstOrDefaultAsync(); if (dbProduct == null) { string reason = $"Product not found by Sku:{sku} provided."; IG2000.Data.Utilities.Logging.LogTrackingEvent($"Product was unable to be retrieved! 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 }; } return(dbProduct); }
public async Task DeleteOrReactivate(IBaseContextModel context, string combinedId, string tableName, bool reactivate, Guid trackingGuid) { var response = new Tagge.Common.Models.ProductCategoryResponse(); // Company Id var companyId = context.Security.GetCompanyId(); try { // MongoDB Settings var database = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar"); string productCollectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_Product").Name; string variantCollectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_ProductVariant").Name; // Get MongoDB var db = context.Database; // Word var dbCategory = new Deathstar.Data.Models.PC_Category(); // Id prefix string idPrefix = string.Empty; // Product Category var dbProductCategory = new Deathstar.Data.Models.PC_ProductCategory(); // Product var dbProduct = new Deathstar.Data.Models.PC_Product(); // Variant var dbVariant = new Deathstar.Data.Models.PC_ProductVariant(); // Break combined id string[] ids = combinedId.Split('|'); // Product id long.TryParse(ids[0], out long internalId); // Switch between Product & Variant if (tableName == "PC_Product") { // Get the table ready var productCollection = db.GetCollection <Deathstar.Data.Models.PC_Product>(productCollectionName); // Filters - note always start with the company id var filters = Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); filters = filters & Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.Id, internalId); filters = filters & Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.IsActive, true); // Find product first dbProduct = await productCollection.Find(filters).FirstOrDefaultAsync(); if (dbProduct == null) { IG2000.Data.Utilities.Logging.LogTrackingEvent($"Invalid Id: {combinedId}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Invalid Id: {combinedId}" }; } // Find the category within the product dbProductCategory = dbProduct.Categories.FirstOrDefault(x => x.PC_ProductCategory_Id == combinedId); if (dbProductCategory == null) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = $"Product Category not found by id({combinedId}) provided" } } ; dbProduct.Categories.Remove(dbProductCategory); // Set Product Id to 0 cause of the serializer dbProduct.Id = 0; var serializerSettings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }; var update = new BsonDocument() { { "$set", BsonDocument.Parse(JsonConvert.SerializeObject(dbProduct, serializerSettings)) } }; // Update database record await productCollection.UpdateOneAsync(filters, update); // Build the Webhook event var whProductRequest = new Sheev.Common.Models.WebhookResponse() { CompanyId = companyId.ToString(), Type = "Product Category Assignment", Scope = $"product/category/deleted", Id = combinedId }; // Trigger the Webhook event await _webHookModel.FireWebhookEvent(whProductRequest, context, trackingGuid); } else { // Get the table ready var variantFilters = Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.Id, internalId); // Filter building var variantCollection = db.GetCollection <Deathstar.Data.Models.PC_ProductVariant>(variantCollectionName); variantFilters = variantFilters & Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.IsActive, true); variantFilters = variantFilters & Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); dbVariant = await variantCollection.Find(variantFilters).FirstOrDefaultAsync(); if (dbVariant == null) { IG2000.Data.Utilities.Logging.LogTrackingEvent($"Invalid Id: {combinedId}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Invalid Id: {combinedId}" }; } // Find the category dbProductCategory = dbVariant.Categories.FirstOrDefault(x => x.PC_ProductCategory_Id == combinedId); // Category is missing if (dbProductCategory == null) { throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = $"Product Category not found by id({combinedId}) provided" } } ; dbVariant.Categories.Remove(dbProductCategory); // Set Product Id to 0 cause of the serializer dbVariant.Id = 0; var serializerSettings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }; var variantUpdate = new BsonDocument() { { "$set", BsonDocument.Parse(JsonConvert.SerializeObject(dbVariant, serializerSettings)) } }; await variantCollection.UpdateOneAsync(variantFilters, variantUpdate); // Build the Webhook event var whVariantRequest = new Sheev.Common.Models.WebhookResponse() { CompanyId = companyId.ToString(), Type = "Product Category Assignment", Scope = $"product/variant/category/deleted", Id = combinedId }; // Trigger the Webhook event await _webHookModel.FireWebhookEvent(whVariantRequest, context, trackingGuid); } } catch (HttpResponseException webEx) { IG2000.Data.Utilities.Logging.LogTrackingEvent($"Inventory failed to save! Reason: {webEx.ReasonPhrase}", $"Status Code: {webEx.StatusCode}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); throw; } catch (Exception ex) { IG2000.Data.Utilities.Logging.LogTrackingEvent($"See logs for additional details", "Failed", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); IG2000.Data.Utilities.ErrorLogger.Report(ex.Message, "InventoryModel.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message }; } }
public KitController(IKitModel kitModel, ILoggerManager logger, IOptions <Sheev.Common.Models.MongoDbSetting> mongoDbSettings, IOptions <Sheev.Common.Models.ApiUrlSetting> apiSettings) { _context = new Models.ContextModel(mongoDbSettings, apiSettings, logger); _kitModel = kitModel; }
/// <summary> /// Get a Category Assignment by its id /// </summary> /// <param name="id"></param> /// <param name="tableName"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task <Tagge.Common.Models.ProductCategoryResponse> GetById(IBaseContextModel context, string id, string tableName, Guid trackingGuid) { // Response var response = new Tagge.Common.Models.ProductCategoryResponse(); // Company Id var companyId = context.Security.GetCompanyId(); // 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; // DB Object var dbProductCategory = new Deathstar.Data.Models.PC_ProductCategory(); // Break combined id string[] ids = id.Split('|'); // Parent id long.TryParse(ids[0], out long parentId); // Switch determined by tablename sent in if (tableName == "PC_Product") { var productCollection = db.GetCollection <Deathstar.Data.Models.PC_Product>(productCollectionName); // Filters - note always start with the company id var filters = Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); filters = filters & Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.Id, parentId); filters = filters & Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.IsActive, true); // Find the product var dbProduct = await productCollection.FindAsync(filters).Result.FirstOrDefaultAsync(); // Product not found if true if (dbProduct == null) { string reason = $"Product Category not found by Id:{id} provided."; IG2000.Data.Utilities.Logging.LogTrackingEvent($"Product Category was unable to be retrieved! Reason: {reason}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = reason }; } dbProductCategory = dbProduct.Categories.FirstOrDefault(x => x.PC_ProductCategory_Id == id && x.IsActive); } else { var variantCollection = db.GetCollection <Deathstar.Data.Models.PC_ProductVariant>(variantCollectionName); // Filter var variantFilters = Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.Id, parentId); variantFilters = variantFilters & Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.IsActive, true); variantFilters = variantFilters & Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); var dbVariant = await variantCollection.FindAsync(variantFilters).Result.FirstOrDefaultAsync(); if (dbVariant == null) { string reason = $"Product Category not found by Id:{id} provided."; IG2000.Data.Utilities.Logging.LogTrackingEvent($"Product Category was unable to be retrieved! Reason: {reason}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = reason }; } dbProductCategory = dbVariant.Categories.FirstOrDefault(x => x.PC_ProductCategory_Id == id && x.IsActive); } if (dbProductCategory == null) { string reason = $"Product Category not found by Id:{id} provided."; IG2000.Data.Utilities.Logging.LogTrackingEvent($"Product Category was unable to be retrieved! Reason: {reason}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = reason }; } IG2000.Data.Utilities.Logging.LogTrackingEvent($"Product Category Type (id: {dbProductCategory.PC_ProductCategory_Id}) successfully retrieved.", "Get Alternate Id Type", LT319.Common.Utilities.Constants.TrackingStatus.Complete, context, trackingGuid); response = new Common.Models.ProductCategoryResponse() { Id = dbProductCategory.PC_ProductCategory_Id, ProductId = parentId, CategoryId = dbProductCategory.CategoryId, Type = "Variant" }; return(response); }
/// <summary> /// Saves a category assignment /// </summary> /// <param name="request"></param> /// <param name="tableName"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task <Tagge.Common.Models.ProductCategoryResponse> Save(IBaseContextModel context, Tagge.Common.Models.ProductCategoryRequest request, string tableName, Guid trackingGuid) { var response = new Tagge.Common.Models.ProductCategoryResponse(); // Company Id var companyId = context.Security.GetCompanyId(); try { // MongoDB Settings var database = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar"); string productCollectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_Product").Name; string variantCollectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_ProductVariant").Name; // Get MongoDB var db = context.Database; // Word var dbCategory = new Deathstar.Data.Models.PC_Category(); // Id prefix string idPrefix = string.Empty; // Validate Category ////Circular Reference string dbCategoryName = await CategoryModel.Validate(request.CategoryId, context, trackingGuid);// _new CategoryModel(context).Validate(request.CategoryId, trackingGuid); // Product Category var dbProductCategory = new Deathstar.Data.Models.PC_ProductCategory(); // Convert To Database Object dbProductCategory.ConvertToDatabaseObject(dbCategoryName, request); // Set Primary Key dbProductCategory.SetPrimaryKey(request.InternalId.ToString(), request.CategoryId.ToString()); // Set Is Active to true dbProductCategory.IsActive = true; switch (tableName) { case "PC_Product": var productCollection = db.GetCollection <Deathstar.Data.Models.PC_Product>(productCollectionName); // Product var dbProduct = new Deathstar.Data.Models.PC_Product(); // Filters - note always start with the company id var filters = Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); filters = filters & Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.Id, request.InternalId); filters = filters & Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.IsActive, true); // Find the product dbProduct = await productCollection.Find(filters).FirstOrDefaultAsync(); // The product was not valid if (dbProduct == null) { var message = $"Product Id not valid: {request.InternalId}"; throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = message }; } if (dbProduct.Categories != null && dbProduct.Categories.Count > 0) { var dbtempCategory = dbProduct.Categories.FirstOrDefault(x => x.PC_ProductCategory_Id == dbProductCategory.PC_ProductCategory_Id && x.CategoryId == request.CategoryId); if (dbtempCategory == null) { // Add the Category Assignment dbProduct.Categories.Add(dbProductCategory); } else { // Update the Category Assignment dbProductCategory = dbtempCategory; dbProductCategory.IsActive = true; } } else { // Add the Category Assignment dbProduct.Categories.Add(dbProductCategory); } // Set Product Id to 0 cause of the serializer var productId = dbProduct.Id; dbProduct.Id = 0; var serializerSettings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }; var update = new BsonDocument() { { "$set", BsonDocument.Parse(JsonConvert.SerializeObject(dbProduct, serializerSettings)) } }; // Update database record await productCollection.UpdateOneAsync(filters, update); response = new Common.Models.ProductCategoryResponse() { Id = dbProductCategory.PC_ProductCategory_Id, ProductId = productId, CategoryId = request.CategoryId, Type = "Product" }; // Build the Webhook event var whProductRequest = new Sheev.Common.Models.WebhookResponse() { CompanyId = companyId.ToString(), Type = "Product Category Assignment", Scope = $"product/category/created", Id = response.Id, TrackingGuid = trackingGuid }; // Trigger the Webhook event await _webHookModel.FireWebhookEvent(whProductRequest, context, trackingGuid); break; case "PC_ProductVariant": var variantCollection = db.GetCollection <Deathstar.Data.Models.PC_ProductVariant>(variantCollectionName); // Variant var dbVariant = new Deathstar.Data.Models.PC_ProductVariant(); var variantFilter = Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.Id, request.InternalId); variantFilter = variantFilter & Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.IsActive, true); variantFilter = variantFilter & Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); dbVariant = await variantCollection.Find(variantFilter).FirstOrDefaultAsync(); if (dbVariant == null) { var message = $"Product Variant Id not valid: {request.InternalId}"; throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = message }; } if (dbVariant.Categories != null && dbVariant.Categories.Count > 0) { var dbtempCategory = dbVariant.Categories.FirstOrDefault(x => x.PC_ProductCategory_Id == dbProductCategory.PC_ProductCategory_Id && x.CategoryId == request.CategoryId && x.IsActive); if (dbtempCategory == null) { // Add the Category Assignment dbVariant.Categories.Add(dbProductCategory); } else { // Update the Category Assignment dbProductCategory = dbtempCategory; dbProductCategory.IsActive = true; } } else { // Add the Category Assignment dbVariant.Categories.Add(dbProductCategory); } // Set Product Id to 0 cause of the serializer var variantId = dbVariant.Id; dbVariant.Id = 0; var variantSerializerSettings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }; var variantUpdate = new BsonDocument() { { "$set", BsonDocument.Parse(JsonConvert.SerializeObject(dbVariant, variantSerializerSettings)) } }; // Update database record await variantCollection.UpdateOneAsync(variantFilter, variantUpdate); response = new Common.Models.ProductCategoryResponse() { Id = dbProductCategory.PC_ProductCategory_Id, ProductId = variantId, CategoryId = request.CategoryId, Type = "Variant" }; // Build the Webhook event var whVariantRequest = new Sheev.Common.Models.WebhookResponse() { CompanyId = companyId.ToString(), Type = "Product Category Assignment", Scope = $"product/variant/category/created", Id = response.Id, TrackingGuid = trackingGuid }; // Trigger the Webhook event await _webHookModel.FireWebhookEvent(whVariantRequest, context, trackingGuid); break; default: throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Invalid Type: {tableName}. Please specify a correct type: Product or Variant" }; } return(response); } catch (HttpResponseException webEx) { IG2000.Data.Utilities.Logging.LogTrackingEvent($"Inventory failed to save! Reason: {webEx.ReasonPhrase}", $"Status Code: {webEx.StatusCode}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); throw; } catch (Exception ex) { IG2000.Data.Utilities.Logging.LogTrackingEvent($"See logs for additional details", "Failed", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); IG2000.Data.Utilities.ErrorLogger.Report(ex.Message, "InventoryModel.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message }; } }
/// <summary> /// Get all categories /// </summary> /// <param name="queryString"></param> /// <param name="context"></param> /// <param name="count"></param> /// <param name="pageNumber"></param> /// <param name="pageSize"></param> /// <returns></returns> public List <Sheev.Common.Models.GetAllResponse> GetAll(IBaseContextModel context, string queryString, ref long count, int?pageNumber = 1, int?pageSize = 100) { // Paging int limit = (int)pageSize; int start = (int)pageNumber == 1 ? 0 : (int)(pageNumber - 1) * limit; // Response List <Sheev.Common.Models.GetAllResponse> response = new List <Sheev.Common.Models.GetAllResponse>(); // Company Id var companyId = context.Security.GetCompanyId(); // Dictonary Dictionary <string, string> dictionary = new Dictionary <string, string>(); // Action string action = string.Empty; //// 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); // Add Company Id filter dictionary.Add("DV_CompanyId", companyId.ToString()); // Filter if (!string.IsNullOrEmpty(queryString)) { Utilities.MongoFilter.BuildFilterDictionary(queryString, ref action, ref dictionary); } // Check for invalid filters //CheckForInvalidFilters(dictionary); // Filter Builder FilterDefinition <Deathstar.Data.Models.PC_Category> filters; // Handle Action switch (action.ToLower()) { case "contains": filters = Utilities.MongoFilter.BuildFilters <Deathstar.Data.Models.PC_Category>(fieldContainsValue: dictionary); break; default: filters = Utilities.MongoFilter.BuildFilters <Deathstar.Data.Models.PC_Category>(fieldEqValue: dictionary); break; } count = _categoryCollection.Find(filters).CountDocuments(); var dbCategories = _categoryCollection.Find(filters).SortByDescending(x => x.CreatedDateTime).Skip(start).Limit(limit).ToList(); foreach (var dbCategory in dbCategories) { var singleResponse = new Sheev.Common.Models.GetAllResponse() { Id = dbCategory.Id, Name = dbCategory.Name, Description = dbCategory.Description }; response.Add(singleResponse); } return(response); }
/// <summary> /// Delete or reactivate an existing category /// </summary> /// <param name="id"></param> /// <param name="reactivate"></param> /// <param name="context"></param> /// <param name="trackingGuid"></param> /// <returns></returns> public async Task <int> DeleteOrReactivate(IBaseContextModel context, long id, bool reactivate, Guid trackingGuid) { var companyId = context.Security.GetCompanyId(); // MongoDB Settings var database = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar"); string collectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_Category").Name; string productCollectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_Product").Name; string variantCollectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_ProductVariant").Name; // Get MongoDB var db = context.Database; //var categoryCollection = db.GetCollection<Deathstar.Data.Models.PC_Category>(collectionName); // Filter var filters = Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.Id, id); filters = filters & Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); var dbCategory = _categoryCollection.Find(filters).FirstOrDefault(); if (dbCategory == null) { string reason = $"Category not found by Id:{id} provided."; IG2000.Data.Utilities.Logging.LogTrackingEvent($"Category was unable to be retrieved! Reason: {reason}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid); throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = reason }; } // Set the updated timestamp here string timestamp = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz"); // Update the Following Fields var update = Builders <Deathstar.Data.Models.PC_Category> .Update .Set(x => x.IsActive, reactivate) .Set(x => x.UpdatedBy, context.Security.GetEmail()) .Set(x => x.UpdatedDateTime, timestamp); // Update database record await _categoryCollection.UpdateOneAsync(filters, update); // Remove all category assignments only on delete if (!reactivate) { // Remove all category assignments var productCollection = db.GetCollection <Deathstar.Data.Models.PC_Product>(productCollectionName); var variantCollection = db.GetCollection <Deathstar.Data.Models.PC_ProductVariant>(variantCollectionName); // Find all Products Filter var productFilters = Builders <Deathstar.Data.Models.PC_Product> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); productFilters = productFilters & Builders <Deathstar.Data.Models.PC_Product> .Filter.ElemMatch(x => x.Categories, x => x.CategoryId == id); // Find all the products that have this category assignment var dbProducts = productCollection.FindAsync(productFilters).Result.ToList(); // get a list of all the category assignments that match the categroy id var dbProductCategoryAssignments = dbProducts.SelectMany(x => x.Categories).Where(y => y.CategoryId == id).ToList(); foreach (var dbProductCategoryAssignment in dbProductCategoryAssignments) { //circular reference await _categoryAssignment.DeleteOrReactivate(context, dbProductCategoryAssignment.PC_ProductCategory_Id, "PC_Product", false, trackingGuid); } // Variant Filter var variantFilters = Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString()); variantFilters = variantFilters & Builders <Deathstar.Data.Models.PC_ProductVariant> .Filter.ElemMatch(x => x.Categories, x => x.CategoryId == id); // Find all the variants that have this category assignment var dbVariants = variantCollection.FindAsync(variantFilters).Result.ToList(); // get a list of all the category assignments that match the category id var dbVariantCategoryAssignments = dbVariants.SelectMany(x => x.Categories).Where(y => y.CategoryId == id).ToList(); foreach (var dbVariantCategoryAssignment in dbVariantCategoryAssignments) { //circular reference await _categoryAssignment.DeleteOrReactivate(context, dbVariantCategoryAssignment.PC_ProductCategory_Id, "PC_ProductVariant", false, trackingGuid); } } else // if reactivating send update webhook { // Build the Webhook event var whRequest = new Sheev.Common.Models.WebhookResponse() { CompanyId = companyId.ToString(), Type = "Product Category", Scope = $"category/product/updated", Id = id.ToString(), TrackingGuid = trackingGuid }; // Trigger the Webhook event await _webHookModel.FireWebhookEvent(whRequest, context, trackingGuid); } // Update the corresponding External Id record(s) await _externalIdModel.DeleteOrReactivateByParentId(dbCategory.Id.ToString(), reactivate, "PC_Category", timestamp, dbCategory.UpdatedDateTime, trackingGuid, "category/product/deleted", true); return(Microsoft.AspNetCore.Http.StatusCodes.Status204NoContent); }
/// <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 }; } }
/// <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 }; } }
/// <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 }; } }