コード例 #1
0
        /// <summary>
        /// Updates an existing location group
        /// </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.LocationGroupResponse> Update(long id, Tagge.Common.Models.LocationGroupRequest request, Guid trackingGuid)
        {
            var response  = new Tagge.Common.Models.LocationGroupResponse();
            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_LocationGroup").Name;

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

                // Word
                var dbLocationGroup = new Deathstar.Data.Models.PC_LocationGroup();

                // Check to see if the Location is a duplicate
                var filters = Builders <Deathstar.Data.Models.PC_LocationGroup> .Filter.Eq(x => x.Id, id);

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

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

                // Does the location group already exist
                var dbExistingLocationGroup = await locationGroupCollection.Find(filters).FirstOrDefaultAsync();

                if (dbExistingLocationGroup == null)
                {
                    string reason = $"Location Group not found by Id: {id}. Use Post to create a new location group";

                    //IG2000.Data.Utilities.Logging.LogTrackingEvent($"Location Group ({request.Name}) already exist! Reason: {reason}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid);
                    throw new HttpResponseException()
                          {
                              StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = reason
                          };
                }

                // Convert request to Location
                dbLocationGroup.ConvertToDatabaseObject(companyId.ToString(), request);

                // Locations
                if (request.Locations != null && request.Locations.Count > 0)
                {
                    dbLocationGroup.Locations = await LocationModel.SaveOrUpdate(request.Locations, dbExistingLocationGroup.Locations, context, trackingGuid);
                }

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

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

                // IsActive
                dbLocationGroup.IsActive = true;

                // Set id to 0 due to serializer
                dbLocationGroup.Id = 0;

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

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

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

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

                // Add Id
                response.Id = id;

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

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

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

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

                return(response);
            }
            catch (HttpResponseException webEx)
            {
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"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
                      };
            }
        }
コード例 #2
0
        /// <summary>
        /// Save a new location group
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <returns></returns>
        public async Task <Tagge.Common.Models.LocationGroupResponse> Save(Tagge.Common.Models.LocationGroupRequest request, Guid trackingGuid)
        {
            var response  = new Tagge.Common.Models.LocationGroupResponse();
            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_LocationGroup").Name;

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

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

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

                // Word
                var dbLocationGroup = new Deathstar.Data.Models.PC_LocationGroup();

                // Need to do this so that the lookup is not case sensitive
                var lowername = request.Name.ToLower();

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

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

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

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

                    IG2000.Data.Utilities.Logging.LogTrackingEvent($"Location Group ({request.Name}) already exist! Reason: {reason}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid);
                    throw new HttpResponseException()
                          {
                              StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest, ReasonPhrase = reason
                          };
                }

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

                // Convert request to Location
                dbLocationGroup.ConvertToDatabaseObject(companyId.ToString(), request);

                // Locations
                if (request.Locations != null && request.Locations.Count > 0)
                {
                    dbLocationGroup.Locations = await LocationModel.SaveOrUpdate(request.Locations, new List <Deathstar.Data.Models.TM_GenericEntry>(), context, trackingGuid);
                }

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

                // Add Id
                dbLocationGroup.Id = id;

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

                // IsActive
                dbLocationGroup.IsActive = true;

                // Insert
                await locationGroupCollection.InsertOneAsync(dbLocationGroup);

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

                // Add Id
                response.Id = id;

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

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

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

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

                return(response);
            }
            catch (HttpResponseException webEx)
            {
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"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
                      };
            }
        }