Beispiel #1
0
        /// <summary>
        /// Updates an existing location
        /// </summary>
        /// <param name="id"></param>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <returns></returns>
        public async Task <Tagge.Common.Models.LocationResponse> Update(long id, Tagge.Common.Models.LocationRequest request, Guid trackingGuid)
        {
            var response  = new Tagge.Common.Models.LocationResponse();
            var companyId = context.Security.GetCompanyId();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Convert To Response
            response = dbLocation.ConvertToResponse();

            // Add Id
            response.Id = id;

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

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

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

            return(response);
        }
Beispiel #2
0
        /// <summary>
        /// Save a new location
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <returns></returns>
        public async Task <Tagge.Common.Models.LocationResponse> Save(Tagge.Common.Models.LocationRequest request, Guid trackingGuid)
        {
            var response  = new Tagge.Common.Models.LocationResponse();
            var companyId = context.Security.GetCompanyId();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                // Add Id
                dbLocation.Id = id;

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

                // IsActive
                dbLocation.IsActive = true;

                // Insert
                await locationCollection.InsertOneAsync(dbLocation);

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

                // Add Id
                response.Id = id;

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

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

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

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


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