Exemplo n.º 1
0
        public async Task Should_not_set_dates_based_on_DateRangeType(DateRangeType dateRangeType, bool asAtDate)
        {
            var startUtc = dateRangeType == DateRangeType.Custom ? new DateTime(2017, 11, 5) : (DateTime?)null;
            var endUtc   = dateRangeType == DateRangeType.Custom ? new DateTime(2017, 11, 6) : (DateTime?)null;
            //Json deserialize interprets date as mm/dd/yyyy so format date that way
            var startUtcStr = startUtc?.ToString("MM/dd/yyyy");
            var endUtcStr   = endUtc?.ToString("MM/dd/yyyy");
            var filter      = new MasterData.Repositories.DBModels.Filter
            {
                FilterJson =
                    $"{{\"dateRangeType\":\"{dateRangeType}\",\"asAtDate\":\"{asAtDate}\",\"startUTC\":\"{startUtcStr}\",\"endUTC\":\"{endUtcStr}\",\"elevationType\":null}}"
            };

            await FilterJsonHelper.ParseFilterJson(
                new ProjectData { IanaTimeZone = "America/Los_Angeles", ProjectUID = _projectGuid.ToString() }, filter,
                productivity3dV2ProxyCompaction : _mockedProductivity3dV2ProxyCompaction.Object, customHeaders : new HeaderDictionary());

            Abstractions.Models.Filter filterObj =
                JsonConvert.DeserializeObject <Abstractions.Models.Filter>(filter.FilterJson);
            Assert.Equal(dateRangeType, filterObj.DateRangeType);
            if (asAtDate)
            {
                Assert.Equal(MockedStartTime, filterObj.StartUtc);
            }
            else
            {
                Assert.Equal(startUtc, filterObj.StartUtc);
            }
            Assert.Equal(endUtc, filterObj.EndUtc);
        }
Exemplo n.º 2
0
        /// <summary>
        ///     All detail-related columns can be inserted,
        ///     but only certain columns can be updated.
        ///     on deletion, a flag will be set.
        /// </summary>
        private async Task <int> UpsertFilterDetail(MasterData.Repositories.DBModels.Filter filter, string eventType)
        {
            var upsertedCount = 0;
            var existing      = (await QueryWithAsyncPolicy <MasterData.Repositories.DBModels.Filter>(@"SELECT 
                f.FilterUID, f.fk_CustomerUid AS CustomerUID, 
                f.fk_ProjectUID AS ProjectUID, f.UserID,                                  
                f.Name, f.FilterJson, f.fk_FilterTypeID as FilterType,
                f.IsDeleted, f.LastActionedUTC
              FROM Filter f
              WHERE f.FilterUID = @FilterUid",
                                                                                                      new { filter.FilterUid })).FirstOrDefault();

            if (eventType == "CreateFilterEvent")
            {
                upsertedCount = await CreateFilter(filter, existing);
            }

            if (eventType == "UpdateFilterEvent")
            {
                upsertedCount = await UpdateFilter(filter, existing);
            }

            if (eventType == "DeleteFilterEvent")
            {
                upsertedCount = await DeleteFilter(filter, existing);
            }
            return(upsertedCount);
        }
Exemplo n.º 3
0
        public async Task GetFilterExecutor(FilterType filterType)
        {
            string custUid    = Guid.NewGuid().ToString();
            string userUid    = Guid.NewGuid().ToString();
            string projectUid = Guid.NewGuid().ToString();
            string filterUid  = Guid.NewGuid().ToString();
            string name       = "blah";

            var configStore = serviceProvider.GetRequiredService <IConfigurationStore>();
            var logger      = serviceProvider.GetRequiredService <ILoggerFactory>();

            var filterRepo = new Mock <FilterRepository>(configStore, logger);
            var filter     = new MasterData.Repositories.DBModels.Filter
            {
                CustomerUid     = custUid,
                UserId          = userUid,
                ProjectUid      = projectUid,
                FilterUid       = filterUid,
                Name            = name,
                FilterJson      = "{\"dateRangeType\":\"0\",\"elevationType\":null}",
                FilterType      = filterType,
                LastActionedUtc = DateTime.UtcNow
            };

            filterRepo.As <IFilterRepository>().Setup(ps => ps.GetFilter(It.IsAny <string>())).ReturnsAsync(filter);

            var filterToTest = new FilterDescriptorSingleResult(AutoMapperUtility.Automapper.Map <FilterDescriptor>(filter));

            var request = FilterRequestFull.Create
                          (
                null,
                custUid,
                false,
                userUid,
                new ProjectData {
                ProjectUID = projectUid
            },
                new FilterRequest {
                FilterUid = filterUid
            }
                          );

            var executor =
                RequestExecutorContainer.Build <GetFilterExecutor>(configStore, logger, serviceExceptionHandler,
                                                                   filterRepo.Object, null);
            var result = await executor.ProcessAsync(request) as FilterDescriptorSingleResult;

            Assert.NotNull(result);
            Assert.Equal(filterToTest.FilterDescriptor.FilterUid, result.FilterDescriptor.FilterUid);
            Assert.Equal(filterToTest.FilterDescriptor.Name, result.FilterDescriptor.Name);
            Assert.Equal("{\"dateRangeType\":0,\"dateRangeName\":\"Today\"}", result.FilterDescriptor.FilterJson);
            Assert.Equal(filterToTest.FilterDescriptor.FilterType, result.FilterDescriptor.FilterType);
        }
Exemplo n.º 4
0
        private async Task <int> DeleteFilter(MasterData.Repositories.DBModels.Filter filter, MasterData.Repositories.DBModels.Filter existing)
        {
            Log.LogDebug($"FilterRepository/DeleteFilter: project={JsonConvert.SerializeObject(filter)})')");

            var upsertedCount = 0;

            if (existing != null)
            {
                if (filter.LastActionedUtc >= existing.LastActionedUtc)
                {
                    Log.LogDebug($"FilterRepository/DeleteFilter: updating filter");

                    const string update =
                        @"UPDATE Filter                
                  SET IsDeleted = 1,
                    LastActionedUTC = @LastActionedUtc
                  WHERE FilterUID = @FilterUid";
                    upsertedCount = await ExecuteWithAsyncPolicy(update, filter);

                    Log.LogDebug(
                        $"FilterRepository/DeleteFilter: upserted {upsertedCount} rows");
                    return(upsertedCount);
                }
            }
            else
            {
                // a delete was processed before the create, even though it's actionUTC is later (due to old kafka partioning issue?)
                Log.LogDebug(
                    $"FilterRepository/DeleteFilter: delete event where no filter exists, creating one. filter={filter.FilterUid}");

                filter.Name       = string.Empty;
                filter.FilterJson = string.Empty;

                const string delete =
                    @"INSERT Filter
                 (fk_CustomerUid, UserID, fk_ProjectUID, FilterUID,
                  Name, FilterJson, fk_FilterTypeID,
                  IsDeleted, LastActionedUTC)
              VALUES
                (@CustomerUid, @UserId, @ProjectUid, @FilterUid,  
                 @Name, @FilterJson, @FilterType,
                 1, @LastActionedUtc)";

                upsertedCount = await ExecuteWithAsyncPolicy(delete, filter);

                Log.LogDebug(
                    $"FilterRepository/DeleteFilter: inserted {upsertedCount} rows.");
                return(upsertedCount);
            }

            return(upsertedCount);
        }
Exemplo n.º 5
0
        public async Task Should_set_dates_based_on_DateRangeType_When_using_Filter(DateRangeType dateRangeType, bool asAtDate)
        {
            var filter = new MasterData.Repositories.DBModels.Filter
            {
                FilterJson = $"{{\"dateRangeType\":\"{dateRangeType}\",\"asAtDate\":\"{asAtDate}\",\"elevationType\":null}}"
            };

            await FilterJsonHelper.ParseFilterJson(
                new ProjectData { IanaTimeZone = "America/Los_Angeles", ProjectUID = _projectGuid.ToString() }, filter,
                _mockedProductivity3dV2ProxyCompaction.Object, new HeaderDictionary());

            ValidateDates(filter.FilterJson, asAtDate);
        }
Exemplo n.º 6
0
        public async Task GetFilterExecutor_DoesntBelongToUser(FilterType filterType)
        {
            string custUid           = Guid.NewGuid().ToString();
            string requestingUserUid = Guid.NewGuid().ToString();
            string filterUserUid     = Guid.NewGuid().ToString();
            string projectUid        = Guid.NewGuid().ToString();
            string filterUid         = Guid.NewGuid().ToString();
            string name       = "blah";
            string filterJson = "{{\"dateRangeType\":\"0\",\"elevationType\":null}}";

            var configStore = serviceProvider.GetRequiredService <IConfigurationStore>();
            var logger      = serviceProvider.GetRequiredService <ILoggerFactory>();

            var filterRepo = new Mock <FilterRepository>(configStore, logger);
            var filter     = new MasterData.Repositories.DBModels.Filter
            {
                CustomerUid     = custUid,
                UserId          = filterUserUid,
                ProjectUid      = projectUid,
                FilterUid       = filterUid,
                Name            = name,
                FilterJson      = filterJson,
                FilterType      = filterType,
                LastActionedUtc = DateTime.UtcNow
            };

            filterRepo.As <IFilterRepository>().Setup(ps => ps.GetFilter(It.IsAny <string>())).ReturnsAsync(filter);

            var request = FilterRequestFull.Create
                          (
                null,
                custUid,
                false,
                requestingUserUid,
                new ProjectData {
                ProjectUID = projectUid
            },
                new FilterRequest {
                FilterUid = filterUid
            }
                          );
            var executor =
                RequestExecutorContainer.Build <GetFilterExecutor>(configStore, logger, serviceExceptionHandler,
                                                                   filterRepo.Object, null);
            var ex = await Assert.ThrowsAsync <ServiceException>(async() => await executor.ProcessAsync(request));

            Assert.Contains("2036", ex.GetContent);
            Assert.Contains("GetFilter By filterUid. The requested filter does not exist, or does not belong to the requesting customer; project or user.", ex.GetContent);
        }
Exemplo n.º 7
0
        public async Task Should_return_When_project_is_null()
        {
            try
            {
                var filter = new MasterData.Repositories.DBModels.Filter
                {
                    FilterJson = "{\"dateRangeType\":\"0\",\"elevationType\":null}"
                };
                await FilterJsonHelper.ParseFilterJson(null, filter, _mockedProductivity3dV2ProxyCompaction.Object, new HeaderDictionary());

                var filterObj = JsonConvert.DeserializeObject <Abstractions.Models.Filter>(filter.FilterJson);
                Assert.Equal(DateRangeType.Today, filterObj.DateRangeType);
            }
            catch (Exception exception)
            {
                Assert.True(false, $"Expected no exception, but got: {exception.Message}");
            }
        }
Exemplo n.º 8
0
        private async Task <int> UpdateFilter(MasterData.Repositories.DBModels.Filter filter, MasterData.Repositories.DBModels.Filter existing)
        {
            Log.LogDebug($"FilterRepository/UpdateFilter: filter={JsonConvert.SerializeObject(filter)}))')");
            var upsertedCount = 0;

            // following are immutable: FilterUID, fk_CustomerUid, fk_ProjectUID, UserID, FilterType
            if (existing != null && existing.FilterType == FilterType.Transient)
            {
                return(upsertedCount);
            }

            if (existing != null)
            {
                const string update =
                    @"UPDATE Filter
              SET Name = @Name,
                  FilterJson = @FilterJson,
                  LastActionedUTC = @LastActionedUtc
              WHERE FilterUID = @FilterUid";

                upsertedCount = await ExecuteWithAsyncPolicy(update, filter);

                Log.LogDebug($"FilterRepository/UpdateFilter: updated {upsertedCount}");
                return(upsertedCount);
            }

            // update received before create
            const string insert =
                @"INSERT Filter
                 (fk_CustomerUid, UserID, fk_ProjectUID, FilterUID,
                  Name, FilterJson, fk_FilterTypeID,
                  IsDeleted, LastActionedUTC)
            VALUES
              (@CustomerUid, @UserId, @ProjectUid, @FilterUid,  
               @Name, @FilterJson, @FilterType,
               @IsDeleted, @LastActionedUtc)";

            upsertedCount = await ExecuteWithAsyncPolicy(insert, filter);

            Log.LogDebug($"FilterRepository/UpdateFilter: created {upsertedCount}");
            return(upsertedCount);
        }
Exemplo n.º 9
0
        public void MapFilterDBModelToResult(FilterType filterType)
        {
            var filter = new MasterData.Repositories.DBModels.Filter
            {
                CustomerUid     = Guid.NewGuid().ToString(),
                UserId          = Guid.NewGuid().ToString(),
                ProjectUid      = Guid.NewGuid().ToString(),
                FilterUid       = Guid.NewGuid().ToString(),
                FilterType      = filterType,
                Name            = "the name",
                FilterJson      = "the Json",
                IsDeleted       = false,
                LastActionedUtc = new DateTime(2017, 01, 21)
            };

            var result = AutoMapperUtility.Automapper.Map <FilterDescriptor>(filter);

            Assert.Equal(filter.FilterUid, result.FilterUid);
            Assert.Equal(filter.Name, result.Name);
            Assert.Equal(filter.FilterJson, result.FilterJson);
            Assert.Equal(filter.FilterType, result.FilterType);
        }
Exemplo n.º 10
0
        public void MapFilterDBModelRequestToDeleteFilterEvent(FilterType filterType)
        {
            var filter = new MasterData.Repositories.DBModels.Filter
            {
                CustomerUid     = Guid.NewGuid().ToString(),
                UserId          = Guid.NewGuid().ToString(),
                ProjectUid      = Guid.NewGuid().ToString(),
                FilterUid       = Guid.NewGuid().ToString(),
                FilterType      = filterType,
                Name            = "the name",
                FilterJson      = "the Json",
                IsDeleted       = false,
                LastActionedUtc = new DateTime(2017, 01, 21)
            };

            var result = AutoMapperUtility.Automapper.Map <DeleteFilterEvent>(filter);

            Assert.Equal(filter.CustomerUid, result.CustomerUID.ToString());
            Assert.Equal(filter.UserId, result.UserID);
            Assert.Equal(filter.ProjectUid, result.ProjectUID.ToString());
            Assert.Equal(filter.FilterUid, result.FilterUID.ToString());
        }
Exemplo n.º 11
0
        /// <summary>
        /// Processes the GetFilters Request
        /// </summary>
        /// <returns>If successful returns a <see cref="FilterDescriptorSingleResult"/> object containing the filter.</returns>
        protected override async Task <ContractExecutionResult> ProcessAsyncEx <T>(T item)
        {
            var request = CastRequestObjectTo <FilterRequestFull>(item, 5);

            if (request == null)
            {
                return(null);
            }

            MasterData.Repositories.DBModels.Filter filter = null;
            // get FilterUid where !deleted
            //   must be ok for
            //      customer /project
            //      and UserUid: If the calling context is == Application, then get all
            //                     else get only those for the calling UserUid
            try
            {
                filter = await((IFilterRepository)Repository).GetFilter(request.FilterUid);
            }
            catch (Exception e)
            {
                serviceExceptionHandler.ThrowServiceException(HttpStatusCode.InternalServerError, 6, e.Message);
            }

            if (filter == null ||
                !string.Equals(filter.CustomerUid, request.CustomerUid, StringComparison.OrdinalIgnoreCase) ||
                !string.Equals(filter.ProjectUid, request.ProjectUid, StringComparison.OrdinalIgnoreCase) ||
                !string.Equals(filter.UserId, request.UserId, StringComparison.OrdinalIgnoreCase) && !request.IsApplicationContext
                )
            {
                serviceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 36);
            }


            await FilterJsonHelper.ParseFilterJson(request.ProjectData, filter, Productivity3dV2ProxyCompaction, request.CustomHeaders);

            return(new FilterDescriptorSingleResult(AutoMapperUtility.Automapper.Map <FilterDescriptor>(filter)));
        }
Exemplo n.º 12
0
        private Task <int> CreateFilter(MasterData.Repositories.DBModels.Filter filter, MasterData.Repositories.DBModels.Filter existing)
        {
            Log.LogDebug($"{nameof(FilterRepository)}/{nameof(CreateFilter)}: filter={JsonConvert.SerializeObject(filter)}))')");

            if (existing == null)
            {
                const string insert =
                    @"INSERT Filter
                 (fk_CustomerUid, UserID, fk_ProjectUID, FilterUID,
                  Name, FilterJson, fk_FilterTypeID,
                  IsDeleted, LastActionedUTC)
              VALUES
                (@CustomerUid, @UserId, @ProjectUid, @FilterUid,  
                    @Name, @FilterJson, @FilterType,
                    @IsDeleted, @LastActionedUtc)";

                return(ExecuteWithAsyncPolicy(insert, filter));
            }

            // a delete was processed before the create, even though it's actionUTC is later (due to old kafka partioning issue?)
            //       update everything but ActionUTC from the create
            if (existing.LastActionedUtc >= filter.LastActionedUtc && existing.IsDeleted)
            {
                filter.IsDeleted = true;
                Log.LogDebug("FilterRepository/CreateFilter: going to update filter if received after a delete");
                const string update =
                    @"UPDATE Filter
              SET Name = @Name,
                  FilterJson = @FilterJson,
                  fk_FilterTypeID = @FilterType,
              WHERE FilterUID = @FilterUid";

                return(ExecuteWithAsyncPolicy(update, filter));
            }

            // If Create received after it's been deleted then ignore it as Name; BoundaryJson and actionUtc will be more recent.
            return(Task.FromResult(0));
        }
Exemplo n.º 13
0
        public async Task UpsertFilterExecutor_Persistent_WithCombiningWidgetFilters_CreateOnly()
        {
            // this scenario, the FilterUid is supplied, and is provided in Request
            // so this will result in an updated filter
            string custUid    = Guid.NewGuid().ToString();
            string userUid    = Guid.NewGuid().ToString();
            string projectUid = Guid.NewGuid().ToString();
            string name       = "not entry";

            string designUid  = Guid.NewGuid().ToString();
            string designName = $"Name-{designUid}";

            string startVolumeDate = DateTime.UtcNow.AddHours(-1).ToIso8601DateTimeString();
            string endVolumeDate   = DateTime.UtcNow.ToIso8601DateTimeString();

            string filterUid  = Guid.NewGuid().ToString();
            string filterJson = "{\"vibeStateOn\":\"false\", \"designName\":\"" + designName + "\", \"designUid\":\"" + designUid + "\", \"dateRangeType\":\"Custom\", \"startUTC\": \"" + startVolumeDate + "\", \"endUTC\":\"" + endVolumeDate + "\"}";

            string filterUid_Master  = Guid.NewGuid().ToString();
            string filterJson_Master = "{\"vibeStateOn\":true}";

            string filterUid_Widget  = Guid.NewGuid().ToString();
            string filterJson_Widget = "{\"vibeStateOn\":false}";

            string filterUid_Volume  = Guid.NewGuid().ToString();
            string filterJson_Volume = "{\"designUid\":\"" + designUid + "\", \"dateRangeType\":\"Custom\", \"startUTC\": \"" + startVolumeDate + "\", \"endUTC\":\"" + endVolumeDate + "\"}";

            var configStore = serviceProvider.GetRequiredService <IConfigurationStore>();
            var logger      = serviceProvider.GetRequiredService <ILoggerFactory>();

            var productivity3dV2ProxyNotification = new Mock <IProductivity3dV2ProxyNotification>();

            productivity3dV2ProxyNotification.Setup(ps => ps.NotifyFilterChange(It.IsAny <Guid>(), It.IsAny <Guid>(), null)).ReturnsAsync(new BaseMasterDataResult());

            var fileImportProxy = new Mock <IFileImportProxy>();

            fileImportProxy.Setup(x => x.GetFiles(It.IsAny <string>(), It.IsAny <string>(), null)).ReturnsAsync
                (new List <FileData>
            {
                new FileData {
                    CustomerUid = custUid, ProjectUid = projectUid, Name = designName, ImportedFileUid = designUid
                }
            });

            var filterRepo = new Mock <FilterRepository>(configStore, logger);
            var filter     = new MasterData.Repositories.DBModels.Filter
            {
                CustomerUid     = custUid,
                UserId          = userUid,
                ProjectUid      = projectUid,
                FilterUid       = filterUid,
                Name            = name,
                FilterJson      = filterJson,
                FilterType      = FilterType.Widget,
                LastActionedUtc = DateTime.UtcNow
            };

            var filters = new List <MasterData.Repositories.DBModels.Filter>
            {
                new MasterData.Repositories.DBModels.Filter
                {
                    CustomerUid     = custUid,
                    UserId          = userUid,
                    ProjectUid      = projectUid,
                    FilterUid       = filterUid_Master,
                    Name            = name,
                    FilterJson      = filterJson_Master,
                    FilterType      = FilterType.Widget,
                    LastActionedUtc = DateTime.UtcNow
                },
                new MasterData.Repositories.DBModels.Filter
                {
                    CustomerUid     = custUid,
                    UserId          = userUid,
                    ProjectUid      = projectUid,
                    FilterUid       = filterUid_Widget,
                    Name            = name,
                    FilterJson      = filterJson_Widget,
                    FilterType      = FilterType.Widget,
                    LastActionedUtc = DateTime.UtcNow
                },
                new MasterData.Repositories.DBModels.Filter
                {
                    CustomerUid     = custUid,
                    UserId          = userUid,
                    ProjectUid      = projectUid,
                    FilterUid       = filterUid_Volume,
                    Name            = name,
                    FilterJson      = filterJson_Volume,
                    FilterType      = FilterType.Widget,
                    LastActionedUtc = DateTime.UtcNow
                }
            };

            filterRepo.As <IFilterRepository>().Setup(ps => ps.GetFiltersForProjectUser(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), true)).ReturnsAsync(filters);
            filterRepo.As <IFilterRepository>().Setup(ps => ps.StoreEvent(It.IsAny <UpdateFilterEvent>())).ReturnsAsync(1);
            filterRepo.As <IFilterRepository>().Setup(ps => ps.StoreEvent(It.IsAny <CreateFilterEvent>())).ReturnsAsync(1);

            var geofenceRepo = new Mock <GeofenceRepository>(configStore, logger);

            var filterToTest = new FilterDescriptorSingleResult(AutoMapperUtility.Automapper.Map <FilterDescriptor>(filter));

            var request =
                FilterRequestFull.Create(
                    null,
                    custUid,
                    false,
                    userUid,
                    new ProjectData {
                ProjectUID = projectUid
            },
                    new FilterRequest
            {
                Name                 = name,
                FilterJson           = string.Empty,
                FilterType           = FilterType.Widget,
                HierarchicFilterUids = new List <HierarchicFilterElement>
                {
                    new HierarchicFilterElement {
                        FilterUid = filterUid_Master, Role = FilterCombinationRole.MasterFilter
                    },
                    new HierarchicFilterElement {
                        FilterUid = filterUid_Widget, Role = FilterCombinationRole.WidgetFilter
                    },
                    new HierarchicFilterElement {
                        FilterUid = filterUid_Volume, Role = FilterCombinationRole.VolumesFilter
                    }
                }
            });

            var executor = RequestExecutorContainer.Build <UpsertFilterExecutor>(configStore, logger, serviceExceptionHandler,
                                                                                 filterRepo.Object, geofenceRepo.Object,
                                                                                 productivity3dV2ProxyNotification: productivity3dV2ProxyNotification.Object,
                                                                                 fileImportProxy: fileImportProxy.Object);
            var result = await executor.ProcessAsync(request) as FilterDescriptorSingleResult;

            Assert.NotNull(result);
            result.FilterDescriptor.FilterUid.Should().NotBeNullOrEmpty();
            Assert.Equal(filterToTest.FilterDescriptor.Name, result.FilterDescriptor.Name);
            Assert.Equal(filterToTest.FilterDescriptor.FilterType, result.FilterDescriptor.FilterType);

            var testFilter     = JsonConvert.DeserializeObject <Abstractions.Models.Filter>(filterToTest.FilterDescriptor.FilterJson);
            var combinedFilter = JsonConvert.DeserializeObject <Abstractions.Models.Filter>(result.FilterDescriptor.FilterJson);

            testFilter.Should().BeEquivalentTo(combinedFilter);
        }
Exemplo n.º 14
0
        public async Task UpsertFilterExecutor_Persistent(FilterType filterType)
        {
            // this scenario, the FilterUid is supplied, and is provided in Request
            // so this will result in an updated filter
            string custUid    = Guid.NewGuid().ToString();
            string userUid    = Guid.NewGuid().ToString();
            string projectUid = Guid.NewGuid().ToString();
            string filterUid  = Guid.NewGuid().ToString();
            string name       = "not entry";
            string filterJson = "{\"vibeStateOn\":true}";

            var configStore = serviceProvider.GetRequiredService <IConfigurationStore>();
            var logger      = serviceProvider.GetRequiredService <ILoggerFactory>();

            var productivity3dV2ProxyNotification = new Mock <IProductivity3dV2ProxyNotification>();

            productivity3dV2ProxyNotification.Setup(ps => ps.NotifyFilterChange(It.IsAny <Guid>(), It.IsAny <Guid>(), null)).ReturnsAsync(new BaseMasterDataResult());

            var filterRepo = new Mock <FilterRepository>(configStore, logger);
            var filter     = new MasterData.Repositories.DBModels.Filter
            {
                CustomerUid     = custUid,
                UserId          = userUid,
                ProjectUid      = projectUid,
                FilterUid       = filterUid,
                Name            = name,
                FilterJson      = filterJson,
                FilterType      = filterType,
                LastActionedUtc = DateTime.UtcNow
            };
            var filters = new List <MasterData.Repositories.DBModels.Filter>
            {
                new MasterData.Repositories.DBModels.Filter
                {
                    CustomerUid     = custUid,
                    UserId          = userUid,
                    ProjectUid      = projectUid,
                    FilterUid       = filterUid,
                    Name            = name,
                    FilterJson      = filterJson,
                    FilterType      = filterType,
                    LastActionedUtc = DateTime.UtcNow
                }
            };

            filterRepo.As <IFilterRepository>().Setup(ps => ps.GetFiltersForProjectUser(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), true)).ReturnsAsync(filters);
            filterRepo.As <IFilterRepository>().Setup(ps => ps.StoreEvent(It.IsAny <UpdateFilterEvent>())).ReturnsAsync(1);
            filterRepo.As <IFilterRepository>().Setup(ps => ps.StoreEvent(It.IsAny <CreateFilterEvent>())).ReturnsAsync(1);

            var geofenceRepo = new Mock <GeofenceRepository>(configStore, logger);

            var filterToTest = new FilterDescriptorSingleResult(AutoMapperUtility.Automapper.Map <FilterDescriptor>(filter));

            var request =
                FilterRequestFull.Create(
                    null,
                    custUid,
                    false,
                    userUid,
                    new ProjectData {
                ProjectUID = projectUid
            },
                    new FilterRequest {
                FilterUid = filterUid, Name = name, FilterJson = filterJson, FilterType = filterType
            });

            var executor = RequestExecutorContainer.Build <UpsertFilterExecutor>(configStore, logger, serviceExceptionHandler,
                                                                                 filterRepo.Object, geofenceRepo.Object,
                                                                                 productivity3dV2ProxyNotification: productivity3dV2ProxyNotification.Object);
            var result = await executor.ProcessAsync(request) as FilterDescriptorSingleResult;

            Assert.NotNull(result);
            Assert.Equal(filterToTest.FilterDescriptor.FilterUid, result.FilterDescriptor.FilterUid);
            Assert.Equal(filterToTest.FilterDescriptor.Name, result.FilterDescriptor.Name);
            Assert.Equal(filterToTest.FilterDescriptor.FilterJson, result.FilterDescriptor.FilterJson);
            Assert.Equal(filterToTest.FilterDescriptor.FilterType, result.FilterDescriptor.FilterType);
        }
Exemplo n.º 15
0
        public Task <int> StoreEvent(IFilterEvent evt)
        {
            // following are immutable: FilterUID, fk_CustomerUid, fk_ProjectUID, UserID
            // filterJson is only updateable if transient

            if (evt == null)
            {
                Log.LogWarning("Unsupported Filter event type");
                return(Task.FromResult(0));
            }

            Log.LogDebug($"Event type is {evt.GetType()}");
            switch (evt)
            {
            case CreateFilterEvent @event:
            {
                var filter = new MasterData.Repositories.DBModels.Filter
                {
                    CustomerUid     = @event.CustomerUID.ToString(),
                    UserId          = @event.UserID,
                    ProjectUid      = @event.ProjectUID.ToString(),
                    FilterUid       = @event.FilterUID.ToString(),
                    Name            = @event.Name,
                    FilterJson      = @event.FilterJson,
                    FilterType      = @event.FilterType,
                    LastActionedUtc = @event.ActionUTC
                };

                return(@event.FilterType == FilterType.Transient
              ? CreateFilter(filter, null)
              : UpsertFilterDetail(filter, "CreateFilterEvent"));
            }

            case UpdateFilterEvent @event:
            {
                var filter = new MasterData.Repositories.DBModels.Filter
                {
                    CustomerUid     = @event.CustomerUID.ToString(),
                    UserId          = @event.UserID,
                    ProjectUid      = @event.ProjectUID.ToString(),
                    FilterUid       = @event.FilterUID.ToString(),
                    Name            = @event.Name,
                    FilterJson      = @event.FilterJson,
                    FilterType      = @event.FilterType,
                    LastActionedUtc = @event.ActionUTC
                };

                return(UpsertFilterDetail(filter, "UpdateFilterEvent"));
            }

            case DeleteFilterEvent @event:
            {
                var filter = new MasterData.Repositories.DBModels.Filter
                {
                    CustomerUid     = @event.CustomerUID.ToString(),
                    UserId          = @event.UserID,
                    ProjectUid      = @event.ProjectUID.ToString(),
                    FilterUid       = @event.FilterUID.ToString(),
                    LastActionedUtc = @event.ActionUTC
                };

                return(UpsertFilterDetail(filter, "DeleteFilterEvent"));
            }

            default:
            {
                Log.LogWarning("Unsupported Filter event type");
                return(Task.FromResult(0));
            }
            }
        }