示例#1
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
                      };
            }
        }
示例#2
0
        /// <summary>
        /// Save a new Category
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <returns></returns>
        public async Task <Tagge.Common.Models.CategoryResponse> Save(IBaseContextModel context, Tagge.Common.Models.CategoryRequest request, Guid trackingGuid)
        {
            var response  = new Tagge.Common.Models.CategoryResponse();
            var companyId = context.Security.GetCompanyId();

            try
            {
                //// MongoDB Settings
                //var database = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar");
                //string collectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_Category").Name;

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

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

                // Check to see if the parent id exists
                if (request.ParentId.HasValue && request.ParentId.Value > 0)
                {
                    var parentCategoryFilter = Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.Id, request.ParentId.Value);

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

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

                    var parentCategory = _categoryCollection.Find(parentCategoryFilter).FirstOrDefault();

                    if (parentCategory == null)
                    {
                        throw new HttpResponseException()
                              {
                                  StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = $"Category Parent not found by Id: {request.ParentId}"
                              }
                    }
                    ;
                }

                // Check to see if the Category is a duplicate
                var duplicatefilter = Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.Name, request.Name);

                duplicatefilter = duplicatefilter & Builders <Deathstar.Data.Models.PC_Category> .Filter.Eq(x => x.ParentId, request.ParentId);

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

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

                var duplicateCategory = _categoryCollection.Find(duplicatefilter).FirstOrDefault();

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

                // Validate Category Sets
                await _categorySetModel.Validate(context, request.CategorySets, trackingGuid); //new CategorySetModel(context).Validate(request.CategorySets, trackingGuid);

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

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

                // Get Id
                var id = counterCollection.FindOneAndUpdate(filter, update).Seq;

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

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

                // Add Id
                dbCategory.Id = id;

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

                // IsActive
                dbCategory.IsActive = true;

                // Insert
                await _categoryCollection.InsertOneAsync(dbCategory);

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

                // Add Id
                response.Id = id;

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

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

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

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


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