Пример #1
0
        public void GetAgencyCodes()
        {
            // Arrange
            var helper     = new TestHelper();
            var controller = helper.CreateController <LookupController>(Permissions.PropertyView);

            var mapper  = helper.GetService <IMapper>();
            var service = helper.GetService <Mock <IPimsService> >();
            var agency  = new Entity.Agency
            {
                Code        = "MOH",
                Name        = "Ministry of Health",
                Description = "The Ministry of Health"
            };

            service.Setup(m => m.Lookup.GetAgencies()).Returns(new[] { agency });

            // Act
            var result = controller.GetAgencies();

            // Assert
            var actionResult = Assert.IsType <JsonResult>(result);
            var actualResult = Assert.IsType <Models.CodeModel <int>[]>(actionResult.Value);

            Assert.Equal(new[] { mapper.Map <Models.CodeModel <int> >(agency) }, actualResult, new DeepPropertyCompare());
            service.Verify(m => m.Lookup.GetAgencies(), Times.Once());
        }
Пример #2
0
        /// <summary>
        /// Create a new instance of a Parcel.
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="lat"></param>
        /// <param name="lng"></param>
        /// <param name="agency"></param>
        /// <returns></returns>
        public static Entity.Parcel CreateParcel(int pid, double lat, double lng, Entity.Agency agency, Entity.Address address = null)
        {
            agency ??= EntityHelper.CreateAgency(pid);
            if (address == null)
            {
                address = EntityHelper.CreateAddress(pid, "1234 Street", null, "V9C9C9");
            }
            var classification = EntityHelper.CreatePropertyClassification("classification");

            return(new Entity.Parcel(pid, lat, lng)
            {
                Id = pid,
                Agency = agency,
                AgencyId = agency.Id,
                Address = address,
                AddressId = address.Id,
                Classification = classification,
                ClassificationId = classification.Id,
                Description = $"description-{pid}",
                CreatedById = Guid.NewGuid(),
                CreatedOn = DateTime.UtcNow,
                UpdatedById = Guid.NewGuid(),
                UpdatedOn = DateTime.UtcNow,
                RowVersion = new byte[] { 12, 13, 14 }
            });
        }
Пример #3
0
        public void GetAgencies_Filtered_Success()
        {
            // Arrange
            var helper     = new TestHelper();
            var controller = helper.CreateController <AgencyController>(Permissions.AdminAgencies);

            var mapper   = helper.GetService <IMapper>();
            var service  = helper.GetService <Mock <IPimsAdminService> >();
            var agencies = new Entity.Agency[] { EntityHelper.CreateAgency(1, "agency1"), EntityHelper.CreateAgency(2, "agency2") };
            var paged    = new Entity.Models.Paged <Entity.Agency>(agencies);

            service.Setup(m => m.Agency.Get(It.IsAny <Entity.Models.AgencyFilter>())).Returns(paged);
            var filter = new Entity.Models.AgencyFilter(1, 10);

            // Act
            var result = controller.GetAgencies(filter);

            // Assert
            var actionResult = Assert.IsType <JsonResult>(result);

            Assert.Null(actionResult.StatusCode);
            var actualResult = Assert.IsType <Pims.Api.Models.PageModel <Model.AgencyModel> >(actionResult.Value);

            Assert.Equal(mapper.Map <Model.AgencyModel[]>(agencies), actualResult.Items, new DeepPropertyCompare());
            service.Verify(m => m.Agency.Get(filter), Times.Once());
        }
Пример #4
0
        /// <summary>
        /// Create a new instance of a Project.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="agency"></param>
        /// <param name="tierLevel"></param>
        /// <param name="workflowStatus"></param>
        /// <returns></returns>
        public static Entity.Project CreateProject(int id, Entity.Agency agency = null, Entity.TierLevel tierLevel = null, Entity.WorkflowProjectStatus workflowStatus = null, Entity.ProjectRisk risk = null)
        {
            agency ??= EntityHelper.CreateAgency(id);
            tierLevel ??= EntityHelper.CreateTierLevel(id, "tierLevel");
            risk ??= EntityHelper.CreateProjectRisk(id, "risk", "risk", 1);
            var status   = workflowStatus?.Status ?? EntityHelper.CreateProjectStatus("Draft", "DR");
            var workflow = workflowStatus?.Workflow ?? EntityHelper.CreateWorkflow(id, "Submit", "SUBMIT-DISPOSAL", new[] { status });

            var user = CreateUser(Guid.NewGuid(), "project tester", "asasa", "asasa", null, agency);

            return(new Entity.Project($"SPP-{id:00000}", $"test-{id}", tierLevel)
            {
                ReportedFiscalYear = DateTime.UtcNow.GetFiscalYear(),
                ActualFiscalYear = DateTime.UtcNow.GetFiscalYear(),
                Risk = risk,
                RiskId = risk.Id,
                Agency = agency,
                AgencyId = agency.Id,
                Workflow = workflow,
                WorkflowId = workflow?.Id,
                Status = status,
                StatusId = status.Id,
                Description = $"description-{id}",
                CreatedBy = user,
                CreatedById = user.Id,
                CreatedOn = DateTime.UtcNow,
                UpdatedById = user.Id,
                UpdatedBy = user,
                PublicNote = $"publicNote-{id}",
                PrivateNote = $"privateNote-{id}",
                UpdatedOn = DateTime.UtcNow,
                Metadata = "{offerAmount: 123}",
                RowVersion = new byte[] { 12, 13, 14 }
            });
        }
Пример #5
0
        /// <summary>
        /// Get or create a new agency for the specified property.
        /// </summary>
        /// <param name="property"></param>
        /// <returns></returns>
        private Entity.Agency GetOrCreateAgency(Model.ImportPropertyModel property)
        {
            // Find the parent agency.
            var agency = _agencies.FirstOrDefault(a => a.Code == property.AgencyCode) ?? throw new KeyNotFoundException($"Agency does not exist '{property.AgencyCode}'");

            // Find or create a sub-agency.
            if (!String.IsNullOrWhiteSpace(property.SubAgency))
            {
                var createCode = new string(property.SubAgency.GetFirstLetterOfEachWord(true).Take(6).ToArray()).Trim();
                var subAgency  = _agencies.FirstOrDefault(a =>
                                                          (a.ParentId == agency.Id && a.Name == property.SubAgency) ||
                                                          (a.ParentId == agency.Id && a.Code == createCode) ||
                                                          a.Code == property.SubAgency ||
                                                          a.Name == property.SubAgency);

                if (subAgency == null)
                {
                    subAgency = new Entity.Agency(createCode, property.SubAgency)
                    {
                        ParentId = agency.Id,
                        Parent   = agency
                    };
                    _pimsAdminService.Agency.Add(subAgency);
                    _agencies.Add(subAgency);
                    _logger.LogDebug($"Adding sub-agency '{subAgency.Code}' - '{agency.Name}', parent: '{subAgency.Parent.Code}'.");
                }

                return(subAgency);
            }

            return(agency);
        }
Пример #6
0
 /// <summary>
 /// Extracts the agency name, or the specified 'agency' is a child it will return the parent code.
 /// </summary>
 /// <param name="source"></param>
 /// <returns></returns>
 public static string ConvertAgencyFullName(Entity.Agency source)
 {
     if (source?.ParentId == null)
     {
         return(source?.Name);
     }
     return(source.Parent?.Name);
 }
Пример #7
0
        /// <summary>
        /// Create a new instance of a Parcel.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static Entity.Agency CreateAgency(int id = 1, string code = "AG", string name = "Agency")
        {
            var agency = new Entity.Agency(code, name)
            {
                Id         = id,
                RowVersion = new byte[] { 12, 13, 14 }
            };

            return(agency);
        }
Пример #8
0
        /// <summary>
        /// Create a new List with new instances of Projects.
        /// </summary>
        /// <param name="startId"></param>
        /// <param name="count"></param>
        /// <param name="agency"></param>
        /// <param name="tierLevel"></param>
        /// <param name="workflowStatus"></param>
        /// <param name="risk"></param>
        /// <returns></returns>
        public static List <Entity.Project> CreateProjects(int startId, int count, Entity.Agency agency = null, Entity.TierLevel tierLevel = null, Entity.WorkflowProjectStatus workflowStatus = null, Entity.ProjectRisk risk = null)
        {
            var projects = new List <Entity.Project>(count);

            for (var i = startId; i < (startId + count); i++)
            {
                projects.Add(CreateProject(i, agency, tierLevel, workflowStatus, risk));
            }
            return(projects);
        }
Пример #9
0
        /// <summary>
        /// Create a new instance of a Parcel and add it to the database context.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="id"></param>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static Entity.Agency CreateAgency(this PimsContext context, int id = 1, string code = "AG", string name = "Agency")
        {
            var agency = new Entity.Agency(code, name)
            {
                Id         = id,
                RowVersion = new byte[] { 12, 13, 14 }
            };

            context.Agencies.Add(agency);
            return(agency);
        }
Пример #10
0
        /// <summary>
        /// Create a new instance of a Project.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="id"></param>
        /// <param name="agency"></param>
        /// <param name="workflowStatus"></param>
        /// <param name="risk"></param>
        /// <returns></returns>
        public static Entity.Project CreateProject(this PimsContext context, int id, Entity.Agency agency = null, Entity.WorkflowProjectStatus workflowStatus = null, Entity.ProjectRisk risk = null)
        {
            agency ??= context.Agencies.OrderBy(a => a.Id).FirstOrDefault() ?? EntityHelper.CreateAgency(1);
            risk ??= context.ProjectRisks.FirstOrDefault() ?? EntityHelper.CreateProjectRisk(1, "risk", "risk", 1);
            workflowStatus ??= context.WorkflowProjectStatus.FirstOrDefault(ws => ws.WorkflowId == 1 && ws.StatusId == 1);
            if (workflowStatus == null)
            {
                var status   = workflowStatus?.Status ?? EntityHelper.CreateProjectStatus("Draft", "DR");
                var workflow = workflowStatus?.Workflow ?? EntityHelper.CreateWorkflow(id, "Submit", "SUBMIT-DISPOSAL", new[] { status });
                workflowStatus ??= workflow.Status.First();
            }

            var tierLevel = context.TierLevels.FirstOrDefault(s => s.Id == 1) ?? EntityHelper.CreateTierLevel("tierLevel");

            var project = EntityHelper.CreateProject(id, agency, tierLevel, workflowStatus, risk);

            context.Projects.Add(project);
            return(project);
        }
Пример #11
0
        /// <summary>
        /// Get or create a new agency for the specified property.
        /// </summary>
        /// <param name="property"></param>
        /// <returns></returns>
        private Entity.Agency GetOrCreateAgency(Model.ImportPropertyModel property)
        {
            // Find the parent agency.
            var agencyCode    = property.AgencyCode.ConvertToUTF8();
            var subAgencyName = property.SubAgency.ConvertToUTF8();
            var agency        = _agencies.FirstOrDefault(a => a.Code == agencyCode) ?? throw new KeyNotFoundException($"Agency does not exist '{property.AgencyCode}'");

            // Find or create a sub-agency.
            if (!String.IsNullOrWhiteSpace(subAgencyName))
            {
                var createCode = new string(subAgencyName.GetFirstLetterOfEachWord(true).Take(6).ToArray()).Trim();

                //check if this agency mapping needs to be corrected.
                if (_agencyCodeCorrections.TryGetValue(createCode, out string mappedCode))
                {
                    createCode = mappedCode;
                }
                var subAgency = _agencies.FirstOrDefault(a =>
                                                         (a.ParentId == agency.Id && a.Name == subAgencyName) ||
                                                         (a.ParentId == agency.Id && a.Code == createCode) ||
                                                         a.Code == subAgencyName ||
                                                         a.Name == subAgencyName);

                if (subAgency == null)
                {
                    subAgency = new Entity.Agency(createCode, subAgencyName)
                    {
                        ParentId = agency.Id,
                        Parent   = agency
                    };
                    _pimsAdminService.Agency.Add(subAgency);
                    _agencies.Add(subAgency);
                    _logger.LogDebug($"Adding sub-agency '{subAgency.Code}' - '{agency.Name}', parent: '{subAgency.Parent.Code}'.");
                }

                return(subAgency);
            }

            return(agency);
        }
Пример #12
0
        /// <summary>
        /// Create a new instance of a Parcel.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="pid"></param>
        /// <param name="lat"></param>
        /// <param name="lng"></param>
        /// <param name="agency"></param>
        /// <returns></returns>
        public static Entity.Parcel CreateParcel(this PimsContext context, int pid, double lat = 0, double lng = 0, Entity.Agency agency = null)
        {
            agency ??= context.Agencies.FirstOrDefault() ?? EntityHelper.CreateAgency(pid);
            var address        = context.CreateAddress(pid, "1234 Street", null, "V9C9C9");
            var classification = context.PropertyClassifications.FirstOrDefault(s => s.Id == 1) ?? EntityHelper.CreatePropertyClassification("classification");

            var parcel = new Entity.Parcel(pid, lat, lng)
            {
                Id               = pid,
                Agency           = agency,
                AgencyId         = agency.Id,
                Address          = address,
                AddressId        = address.Id,
                Classification   = classification,
                ClassificationId = classification.Id,
                Description      = $"description-{pid}",
                CreatedById      = Guid.NewGuid(),
                CreatedOn        = DateTime.UtcNow,
                UpdatedById      = Guid.NewGuid(),
                UpdatedOn        = DateTime.UtcNow,
                RowVersion       = new byte[] { 12, 13, 14 }
            };

            context.Parcels.Add(parcel);
            return(parcel);
        }
Пример #13
0
        /// <summary>
        /// Create a new List with new instances of NotificationQueues.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="startId"></param>
        /// <param name="count"></param>
        /// <param name="template"></param>
        /// <param name="project"></param>
        /// <returns></returns>
        public static List <Entity.NotificationQueue> CreateNotificationQueues(this PimsContext context, int startId, int count, Entity.NotificationTemplate template, Entity.Project project, Entity.Agency agency = null)
        {
            var templates = new List <Entity.NotificationQueue>(count);

            for (var i = startId; i < (startId + count); i++)
            {
                templates.Add(context.CreateNotificationQueue(i, template, project, agency));
            }
            return(templates);
        }
Пример #14
0
 /// <summary>
 /// Create a new instance of a NotificationQueue.
 /// </summary>
 /// <param name="id"></param>
 /// <param name="template"></param>
 /// <param name="project"></param>
 /// <returns></returns>
 public static Entity.NotificationQueue CreateNotificationQueue(int id, Entity.NotificationTemplate template, Entity.Project project, Entity.Agency agency = null)
 {
     return(new Entity.NotificationQueue(template, project, agency ?? project.Agency, "test", "test")
     {
         Id = id,
         CreatedById = Guid.NewGuid(),
         CreatedOn = DateTime.UtcNow,
         RowVersion = new byte[] { 12, 13, 14 }
     });
 }
Пример #15
0
        /// <summary>
        /// Create a new List with new instances of Projects.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="startId"></param>
        /// <param name="count"></param>
        /// <param name="agency"></param>
        /// <param name="workflowStatus"></param>
        /// <param name="risk"></param>
        /// <returns></returns>
        public static List <Entity.Project> CreateProjects(this PimsContext context, int startId, int count, Entity.Agency agency = null, Entity.WorkflowProjectStatus workflowStatus = null, Entity.ProjectRisk risk = null)
        {
            agency ??= context.Agencies.FirstOrDefault(a => a.Id == 1) ?? EntityHelper.CreateAgency(startId);
            risk ??= context.ProjectRisks.FirstOrDefault() ?? EntityHelper.CreateProjectRisk(1, "risk", "risk", 1);
            workflowStatus ??= context.WorkflowProjectStatus.FirstOrDefault(ws => ws.WorkflowId == 1 && ws.StatusId == 1);
            if (workflowStatus == null)
            {
                var status   = workflowStatus?.Status ?? EntityHelper.CreateProjectStatus("Draft", "DR");
                var workflow = workflowStatus?.Workflow ?? EntityHelper.CreateWorkflow(startId, "Submit", "SUBMIT-DISPOSAL", new[] { status });
                workflowStatus ??= workflow.Status.First();
            }

            var projects = new List <Entity.Project>(count);

            for (var i = startId; i < (startId + count); i++)
            {
                projects.Add(context.CreateProject(i, agency, workflowStatus, risk));
            }
            return(projects);
        }
Пример #16
0
        /// <summary>
        /// Add or update the building in the datasource.
        /// Additionally it will also add building construction types and building predominate uses.
        /// </summary>
        /// <param name="property"></param>
        /// <param name="pid"></param>
        /// <param name="agency"></param>
        /// <returns></returns>
        private Entity.Parcel AddUpdateBuilding(Model.ImportPropertyModel property, int pid, Entity.Agency agency)
        {
            var name = GenerateName(property.Name, property.Description, property.LocalId);
            // Multiple buildings could be returned for the PID and Name.
            var b_e            = ExceptionHelper.HandleKeyNotFoundWithDefault(() => _pimsAdminService.Building.GetByPid(pid, name).FirstOrDefault(n => n.Name == name) ?? throw new KeyNotFoundException());
            var evaluationDate = new DateTime(property.FiscalYear, 1, 1); // Defaulting to Jan 1st because SIS data doesn't have the actual date.

            // Find parcel
            var parcel = ExceptionHelper.HandleKeyNotFound(() => _pimsAdminService.Parcel.GetByPid(pid));

            // Determine if the last evaluation or fiscal values are older than the one currently being imported.
            var fiscalNetBook      = b_e.Fiscals.OrderByDescending(f => f.FiscalYear).FirstOrDefault(f => f.Key == Entity.FiscalKeys.NetBook && f.FiscalYear > property.FiscalYear);
            var evaluationAssessed = b_e.Evaluations.OrderByDescending(e => e.Date).FirstOrDefault(e => e.Key == Entity.EvaluationKeys.Assessed && e.Date > evaluationDate);

            // If the parcel doesn't exist yet we'll need to create a temporary one.
            if (parcel == null)
            {
                parcel = AddUpdateParcel(property, pid, agency);
                _logger.LogWarning($"Parcel '{property.PID}' was generated for a building that had no parcel.");
            }

            // Only want to update the properties with the latest information.
            if (b_e.Id == 0 || fiscalNetBook == null || evaluationAssessed == null)
            {
                // Copy properties over to entity.
                b_e.AgencyId = agency?.Id ?? throw new KeyNotFoundException($"Agency '{property.Agency}' does not exist.");
                b_e.Agency   = agency;
                if (!b_e.Parcels.Any(pb => pb.ParcelId == parcel.Id))
                {
                    b_e.Parcels.Add(new Entity.ParcelBuilding(parcel, b_e)
                    {
                        Parcel = null, Building = null
                    });
                }
                b_e.Name        = name;
                b_e.Description = property.Description.ConvertToUTF8(false);
                var lng = property.Longitude != 0 ? property.Longitude : b_e.Location?.X ?? 0; // This is to stop data from some imports resulting in removing the lat/long.
                var lat = property.Latitude != 0 ? property.Latitude : b_e.Location?.Y ?? 0;
                b_e.Location = new NetTopologySuite.Geometries.Point(lng, lat)
                {
                    SRID = 4326
                };
                b_e.RentableArea        = property.BuildingRentableArea;
                b_e.BuildingFloorCount  = property.BuildingFloorCount;
                b_e.BuildingTenancy     = property.BuildingTenancy.ConvertToUTF8();
                b_e.TransferLeaseOnSale = false;

                Entity.PropertyClassification propClassification;
                if (String.Compare("Active", property.Status, true) == 0)
                {
                    propClassification = _propertyClassifications.FirstOrDefault(pc => String.Compare(pc.Name, property.Classification, true) == 0) ??
                                         throw new KeyNotFoundException($"Property Classification '{property.Classification}' does not exist.");
                }
                else
                {
                    propClassification = _propertyClassifications.FirstOrDefault(pc => pc.Name == "Disposed") ?? throw new KeyNotFoundException($"Property Classification '{property.Status}' does not exist.");
                }

                b_e.ClassificationId = propClassification.Id;
                b_e.Classification   = propClassification;

                // Find foreign key.
                var build_type = _buildingConstructionTypes.FirstOrDefault(bct => String.Compare(bct.Name, property.BuildingConstructionType, true) == 0);
                var build_use  = _buildingPredominateUses.FirstOrDefault(bpu => String.Compare(bpu.Name, property.BuildingPredominateUse, true) == 0);

                // If the building construction type doesn't exist, create it.
                if (build_type == null)
                {
                    var max_id = _buildingConstructionTypes.Max(pc => pc.Id) + 1;
                    build_type = new Entity.BuildingConstructionType(max_id, property.BuildingConstructionType);
                    _pimsAdminService.BuildingConstructionType.Add(build_type);
                    _buildingConstructionTypes.Add(build_type);
                }

                // If the building predominate use doesn't exist, create it.
                if (build_use == null)
                {
                    var max_id = _buildingPredominateUses.Max(pc => pc.Id) + 1;
                    build_use = new Entity.BuildingPredominateUse(max_id, property.BuildingPredominateUse);
                    _pimsAdminService.BuildingPredominateUse.Add(build_use);
                    _buildingPredominateUses.Add(build_use);
                }

                b_e.BuildingConstructionTypeId = build_type.Id;
                b_e.BuildingConstructionType   = build_type;
                b_e.BuildingPredominateUseId   = build_use.Id;
                b_e.BuildingPredominateUse     = build_use;


                // TODO: Handle this issue more gracefully.
                var city = _pimsAdminService.AdministrativeArea.Get(property.City.ConvertToUTF8()) ?? throw new InvalidOperationException($"Administrative area '{property.City}' does not exist in the datasource.");

                // Add/Update the address.
                if (b_e.AddressId == 0)
                {
                    _logger.LogDebug($"Adding address for building '{property.PID}'-''{property.LocalId}'.");

                    var address = new Entity.Address(property.CivicAddress.ConvertToUTF8(), null, city.Name, "BC", property.Postal.ConvertToUTF8());
                    b_e.Address = address;
                }
                else
                {
                    b_e.Address.Address1           = property.CivicAddress.ConvertToUTF8();
                    b_e.Address.AdministrativeArea = city.Name;
                    b_e.Address.Postal             = property.Postal.ConvertToUTF8();
                }
            }

            // Add a new fiscal values for each year.
            if (!b_e.Fiscals.Any(e => e.FiscalYear == property.FiscalYear))
            {
                b_e.Fiscals.Add(new Entity.BuildingFiscal(b_e, property.FiscalYear, Entity.FiscalKeys.NetBook, property.NetBook));
            }

            // Add a new evaluation if new.
            if (!b_e.Evaluations.Any(e => e.Date == evaluationDate))
            {
                b_e.Evaluations.Add(new Entity.BuildingEvaluation(b_e, evaluationDate, Entity.EvaluationKeys.Assessed, property.Assessed));
            }

            // A new building.
            if (b_e.Id == 0)
            {
                _pimsAdminService.Building.Add(b_e);
                _logger.LogDebug($"Adding building '{property.LocalId}' to parcel '{property.PID}'");
            }
            else
            {
                _pimsAdminService.Building.Update(b_e);
                _logger.LogDebug($"Updating building '{property.LocalId}' to parcel '{property.PID}'");
            }

            return(parcel);
        }
Пример #17
0
        /// <summary>
        /// Add or update the parcel in the datasource.
        /// </summary>
        /// <param name="property"></param>
        /// <param name="pid"></param>
        /// <param name="agency"></param>
        /// <returns></returns>
        private Entity.Parcel AddUpdateParcel(Model.ImportPropertyModel property, int pid, Entity.Agency agency)
        {
            var p_e            = ExceptionHelper.HandleKeyNotFoundWithDefault(() => _pimsAdminService.Parcel.GetByPid(pid));
            var fiscalYear     = property.FiscalYear;
            var evaluationDate = new DateTime(fiscalYear, 1, 1); // Defaulting to Jan 1st because SIS data doesn't have the actual date.

            // Copy properties over to entity.
            p_e.PID = pid;

            // Determine if the last evaluation or fiscal values in the datasource are older than the one currently being imported.
            var fiscalNetBook      = p_e.Fiscals.OrderByDescending(f => f.FiscalYear).FirstOrDefault(f => f.Key == Entity.FiscalKeys.NetBook && f.FiscalYear > fiscalYear);
            var evaluationAssessed = p_e.Evaluations.OrderByDescending(e => e.Date).FirstOrDefault(e => e.Key == Entity.EvaluationKeys.Assessed && e.Date > evaluationDate);

            // Only want to update the properties with the latest information.
            if (p_e.Id == 0 || fiscalNetBook == null || evaluationAssessed == null)
            {
                p_e.AgencyId    = agency?.Id ?? throw new KeyNotFoundException($"Agency '{property.Agency}' does not exist.");
                p_e.Agency      = agency;
                p_e.Name        = GenerateName(property.Name, property.Description);
                p_e.Description = property.Description.ConvertToUTF8(false);
                var lng = property.Longitude != 0 ? property.Longitude : p_e.Location?.X ?? 0; // This is to stop data from some imports resulting in removing the lat/long.
                var lat = property.Latitude != 0 ? property.Latitude : p_e.Location?.Y ?? 0;
                p_e.Location = new NetTopologySuite.Geometries.Point(lng, lat)
                {
                    SRID = 4326
                };
                p_e.LandArea             = property.LandArea != 0 ? property.LandArea : p_e.LandArea;
                p_e.LandLegalDescription = property.LandLegalDescription.ConvertToUTF8();

                Entity.PropertyClassification propClassification;
                if (String.Compare("Active", property.Status, true) == 0)
                {
                    propClassification = _propertyClassifications.FirstOrDefault(pc => String.Compare(pc.Name, property.Classification, true) == 0)
                                         ?? throw new KeyNotFoundException($"Property Classification '{property.Classification}' does not exist.");
                }
                else
                {
                    propClassification = _propertyClassifications.FirstOrDefault(pc => pc.Name == "Disposed") ?? throw new KeyNotFoundException($"Property Classification '{property.Status}' does not exist.");
                }

                p_e.ClassificationId = propClassification.Id;
                p_e.Classification   = propClassification;

                // TODO: Handle this issue more gracefully.
                var city = _pimsAdminService.AdministrativeArea.Get(property.City.ConvertToUTF8()) ?? throw new InvalidOperationException($"Administrative area '{property.City}' does not exist in the datasource.");

                // Add/Update the address.
                if (p_e.AddressId == 0)
                {
                    _logger.LogDebug($"Adding address for parcel '{property.PID}'.");

                    var address = new Entity.Address(property.CivicAddress.ConvertToUTF8(), null, city.Name, "BC", property.Postal.ConvertToUTF8());
                    p_e.Address = address;
                }
                else
                {
                    p_e.Address.Address1           = property.CivicAddress.ConvertToUTF8();
                    p_e.Address.AdministrativeArea = city.Name;
                    p_e.Address.Postal             = property.Postal.ConvertToUTF8();
                }
            }

            // Add a new fiscal values for each year.
            if (!p_e.Fiscals.Any(e => e.FiscalYear == fiscalYear))
            {
                p_e.Fiscals.Add(new Entity.ParcelFiscal(p_e, fiscalYear, Entity.FiscalKeys.NetBook, property.NetBook));
            }

            // Add a new evaluation if new.
            if (!p_e.Evaluations.Any(e => e.Date == evaluationDate))
            {
                p_e.Evaluations.Add(new Entity.ParcelEvaluation(p_e, evaluationDate, Entity.EvaluationKeys.Assessed, property.Assessed));
            }

            // A new parcel.
            if (p_e.Id == 0)
            {
                _pimsAdminService.Parcel.Add(p_e);
                _logger.LogDebug($"Adding parcel '{property.PID}'");
            }
            else
            {
                _pimsAdminService.Parcel.Update(p_e);
                _logger.LogDebug($"Updating parcel '{property.PID}'");
            }

            return(p_e);
        }
Пример #18
0
        /// <summary>
        /// Create a new instance of a NotificationQueue.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="id"></param>
        /// <param name="template"></param>
        /// <param name="project"></param>
        /// <returns></returns>
        public static Entity.NotificationQueue CreateNotificationQueue(this PimsContext context, int id, Entity.NotificationTemplate template, Entity.Project project, Entity.Agency agency = null)
        {
            var notification = CreateNotificationQueue(id, template, project, agency);

            context.NotificationQueue.Add(notification);
            return(notification);
        }
Пример #19
0
 /// <summary>
 /// Creates a new instance of a Building.
 /// </summary>
 /// <param name="context"></param>
 /// <param name="id"></param>
 /// <param name="name"></param>
 /// <param name="lat"></param>
 /// <param name="lng"></param>
 /// <param name="agency"></param>
 /// <returns></returns>
 public static Entity.Building CreateBuilding(this PimsContext context, int id, string projectNumber = null, string name = null, int lat = 0, int lng = 0, Entity.Agency agency = null)
 {
     return(CreateBuilding(context, null, id, projectNumber, name, lat, lng, agency));
 }
Пример #20
0
        /// <summary>
        /// Creates a new instance of a Building.
        /// </summary>
        /// <param name="parcel"></param>
        /// <param name="id"></param>
        /// <param name="projectNumber"></param>
        /// <param name="name"></param>
        /// <param name="lat"></param>
        /// <param name="lng"></param>
        /// <param name="agency"></param>
        /// <returns></returns>
        public static Entity.Building CreateBuilding(Entity.Parcel parcel, int id, string projectNumber = null, string name = null, int lat = 0, int lng = 0, Entity.Agency agency = null)
        {
            projectNumber ??= $"p{id}";
            agency ??= parcel?.Agency ?? EntityHelper.CreateAgency(id);
            var address = parcel != null?EntityHelper.CreateAddress(++parcel.AddressId, parcel.Address.Address1, parcel.Address.Address2, parcel.Address.AdministrativeArea, parcel.Address.Province, parcel.Address.Postal) :
                              EntityHelper.CreateAddress(id, "1234 Street", null, "V9C9C9");

            var predominateUse   = EntityHelper.CreateBuildingPredominateUse("use");
            var constructionType = EntityHelper.CreateBuildingConstructionType("type");
            var occupantType     = EntityHelper.CreateBuildingOccupantType("occupant");
            var classification   = EntityHelper.CreatePropertyClassification("classification");

            return(new Entity.Building(parcel, lat, lng)
            {
                Id = id,
                ProjectNumbers = $"[\"{projectNumber}\"]",
                AgencyId = agency.Id,
                Agency = agency,
                Name = name,
                AddressId = address.Id,
                Address = address,
                Classification = classification,
                ClassificationId = classification.Id,
                Description = $"description-{id}",
                BuildingPredominateUse = predominateUse,
                BuildingPredominateUseId = predominateUse.Id,
                BuildingConstructionType = constructionType,
                BuildingConstructionTypeId = constructionType.Id,
                BuildingOccupantType = occupantType,
                BuildingOccupantTypeId = occupantType.Id,
                CreatedById = Guid.NewGuid(),
                CreatedOn = DateTime.UtcNow,
                UpdatedById = Guid.NewGuid(),
                UpdatedOn = DateTime.UtcNow,
                RowVersion = new byte[] { 12, 13, 14 },
                PropertyTypeId = 1,
            });
        }
Пример #21
0
        /// <summary>
        /// Creates a new instance of a Building.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="parcel"></param>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="lat"></param>
        /// <param name="lng"></param>
        /// <param name="agency"></param>
        /// <returns></returns>
        public static Entity.Building CreateBuilding(this PimsContext context, Entity.Parcel parcel, int id, string projectNumber = null, string name = null, int lat = 0, int lng = 0, Entity.Agency agency = null)
        {
            name ??= $"l{id}";
            agency ??= parcel.Agency;
            var address          = EntityHelper.CreateAddress(id, parcel.Address.Address1, parcel.Address.Address2, parcel.Address.AdministrativeArea, parcel.Address.Province, parcel.Address.Postal);
            var predominateUse   = context.BuildingPredominateUses.FirstOrDefault(b => b.Id == 1) ?? EntityHelper.CreateBuildingPredominateUse("use");;
            var constructionType = context.BuildingConstructionTypes.FirstOrDefault(b => b.Id == 1) ?? EntityHelper.CreateBuildingConstructionType("type");
            var occupantType     = context.BuildingOccupantTypes.FirstOrDefault(b => b.Id == 1) ?? EntityHelper.CreateBuildingOccupantType("occupant");
            var classification   = context.PropertyClassifications.FirstOrDefault(b => b.Id == 1) ?? EntityHelper.CreatePropertyClassification("classification");

            var building = new Entity.Building(parcel, lat, lng)
            {
                Id                         = id,
                Name                       = name,
                ProjectNumber              = projectNumber,
                AgencyId                   = agency.Id,
                Agency                     = agency,
                AddressId                  = address.Id,
                Address                    = address,
                Classification             = classification,
                ClassificationId           = classification.Id,
                Description                = $"description-{id}",
                BuildingPredominateUse     = predominateUse,
                BuildingPredominateUseId   = predominateUse.Id,
                BuildingConstructionType   = constructionType,
                BuildingConstructionTypeId = constructionType.Id,
                BuildingOccupantType       = occupantType,
                BuildingOccupantTypeId     = occupantType.Id,
                CreatedById                = Guid.NewGuid(),
                CreatedOn                  = DateTime.UtcNow,
                UpdatedById                = Guid.NewGuid(),
                UpdatedOn                  = DateTime.UtcNow,
                RowVersion                 = new byte[] { 12, 13, 14 }
            };
            var parcelBuilding = new Entity.ParcelBuilding(parcel, building);

            context.Buildings.Add(building);
            return(building);
        }
Пример #22
0
        /// <summary>
        /// Creates a new instance of a Building.
        /// </summary>
        /// <param name="parcel"></param>
        /// <param name="id"></param>
        /// <param name="localId"></param>
        /// <param name="lat"></param>
        /// <param name="lng"></param>
        /// <param name="agency"></param>
        /// <returns></returns>
        public static Entity.Building CreateBuilding(Entity.Parcel parcel, int id, string projectNumber = null, string localId = null, int lat = 0, int lng = 0, Entity.Agency agency = null)
        {
            localId ??= $"l{id}";
            projectNumber ??= $"p{id}";
            agency ??= parcel.Agency;
            var address          = EntityHelper.CreateAddress(++parcel.AddressId, parcel.Address.Address1, parcel.Address.Address2, parcel.Address.City, parcel.Address.Province, parcel.Address.Postal);
            var predominateUse   = EntityHelper.CreateBuildingPredominateUse("use");
            var constructionType = EntityHelper.CreateBuildingConstructionType("type");
            var occupantType     = EntityHelper.CreateBuildingOccupantType("occupant");
            var classification   = EntityHelper.CreatePropertyClassification("classification");

            return(new Entity.Building(parcel, lat, lng)
            {
                Id = id,
                LocalId = localId,
                ProjectNumber = projectNumber,
                AgencyId = agency.Id,
                Agency = agency,
                AddressId = address.Id,
                Address = address,
                Classification = classification,
                ClassificationId = classification.Id,
                Description = $"description-{id}",
                BuildingPredominateUse = predominateUse,
                BuildingPredominateUseId = predominateUse.Id,
                BuildingConstructionType = constructionType,
                BuildingConstructionTypeId = constructionType.Id,
                BuildingOccupantType = occupantType,
                BuildingOccupantTypeId = occupantType.Id,
                CreatedById = Guid.NewGuid(),
                CreatedOn = DateTime.UtcNow,
                UpdatedById = Guid.NewGuid(),
                UpdatedOn = DateTime.UtcNow,
                RowVersion = new byte[] { 12, 13, 14 }
            });
        }
Пример #23
0
 /// <summary>
 /// Create a new instance of a ProjectAgencyResponse class, initializes with specified arguments.
 /// </summary>
 /// <param name="project"></param>
 /// <param name="agency"></param>
 /// <param name="notification"></param>
 /// <param name="response"></param>
 /// <param name="receivedOn"></param>
 public ProjectAgencyResponse(Project project, Agency agency, NotificationQueue notification, NotificationResponses response, DateTime?receivedOn = null)
     : this(project, agency, response, receivedOn)
 {
     this.NotificationId = notification?.Id ?? throw new ArgumentNullException(nameof(notification));
     this.Notification   = notification;
 }
Пример #24
0
        /// <summary>
        /// Create a new instance of an AccessRequest for a default user.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="username"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="role"></param>
        /// <param name="agency"></param>
        /// <returns></returns>
        public static Entity.User CreateUser(Guid id, string username, string firstName = "given name", string lastName = "surname", Entity.Role role = null, Entity.Agency agency = null)
        {
            var user = new Entity.User(id, username, $"{firstName}.{lastName}@email.com")
            {
                DisplayName = $"{lastName}, {firstName}",
                RowVersion  = new byte[] { 12, 13, 14 }
            };

            user.Roles.Add(new Entity.UserRole(user, role ?? EntityHelper.CreateRole("Real Estate Manager")));
            user.Agencies.Add(new Entity.UserAgency(user, agency ?? EntityHelper.CreateAgency()));

            return(user);
        }
Пример #25
0
        /// <summary>
        /// Create a new List with new instances of NotificationQueues.
        /// </summary>
        /// <param name="startId"></param>
        /// <param name="count"></param>
        /// <param name="template"></param>
        /// <param name="project"></param>
        /// <returns></returns>
        public static List <Entity.NotificationQueue> CreateNotificationQueues(int startId, int count, Entity.NotificationTemplate template, Entity.Project project, Entity.Agency agency = null)
        {
            var notifications = new List <Entity.NotificationQueue>(count);

            for (var i = startId; i < (startId + count); i++)
            {
                notifications.Add(CreateNotificationQueue(i, template, project, agency));
            }
            return(notifications);
        }
Пример #26
0
 /// <summary>
 /// Extract the sub-agency name.
 /// If the specified 'agency' is a parent it will return null.
 /// </summary>
 /// <param name="source"></param>
 /// <returns></returns>
 public static string ConvertSubAgencyFullName(Entity.Agency source)
 {
     return(source?.ParentId == null ? null : source.Name);
 }
Пример #27
0
 /// <summary>
 /// Create a new instance of a Parcel.
 /// </summary>
 /// <param name="context"></param>
 /// <param name="pid"></param>
 /// <param name="agency"></param>
 /// <returns></returns>
 public static Entity.Parcel CreateParcel(this PimsContext context, int pid, Entity.Agency agency)
 {
     return(context.CreateParcel(pid, 0, 0, agency));
 }