public virtual HttpResponseMessage DeleteByAdviceId(int adviceId)
 {
     try
     {
         foreach (var d in _repository.AsQueryable().Where(d => d.AdviceId == adviceId).ToList())
         {
             if (AllowDelete(d))
             {
                 _repository.Delete(d);
                 _repository.Save();
             }
             else
             {
                 return(Forbidden());
             }
         }
         return(Ok());
     }
     catch (Exception e)
     {
         return(LogError(e));
     }
 }
示例#2
0
        public void SetUp()
        {
            _idCounter = 0;
            var routeList = new List <PersonalRoute>();

            _coordinatesMock = NSubstitute.Substitute.For <IAddressCoordinates>();
            _coordinatesMock.GetAddressCoordinates(new Address()).ReturnsForAnyArgs(new Point
            {
                Latitude  = "1",
                Longitude = "1"
            });


            _routeRepoMock = NSubstitute.Substitute.For <IGenericRepository <PersonalRoute> >();
            _routeRepoMock.Insert(new PersonalRoute()).ReturnsForAnyArgs(x => x.Arg <PersonalRoute>()).AndDoes(x => routeList.Add(x.Arg <PersonalRoute>())).AndDoes(x => x.Arg <PersonalRoute>().Id = _idCounter).AndDoes(x => _idCounter++);
            _routeRepoMock.AsQueryable().ReturnsForAnyArgs(routeList.AsQueryable());

            _uut        = new PersonalRouteService(_coordinatesMock, _routeRepoMock);
            _testPerson = new Person
            {
                Id = 1
            };
        }
        public void SetUp()
        {
            var orgList = new List <OrgUnit>();

            var orgIdCount = 0;

            var cachedAddressList = new List <CachedAddress>();
            var cachedIdCount     = 0;

            _emplRepoMock            = NSubstitute.Substitute.For <IGenericRepository <Employment> >();
            _orgUnitRepoMock         = NSubstitute.Substitute.For <IGenericRepository <OrgUnit> >();
            _personRepoMock          = NSubstitute.Substitute.For <IGenericRepository <Person> >();
            _cachedAddressRepoMock   = NSubstitute.Substitute.For <IGenericRepository <CachedAddress> >();
            _personalAddressRepoMock = NSubstitute.Substitute.For <IGenericRepository <PersonalAddress> >();
            _actualLaunderer         = NSubstitute.Substitute.For <IAddressLaunderer>();
            _coordinates             = NSubstitute.Substitute.For <IAddressCoordinates>();
            _dataProvider            = NSubstitute.Substitute.For <IDbUpdaterDataProvider>();
            _mailSender = NSubstitute.Substitute.For <IMailSender>();

            _orgUnitRepoMock.AsQueryable().Returns(orgList.AsQueryable());

            _orgUnitRepoMock.Insert(new OrgUnit()).ReturnsForAnyArgs(x => x.Arg <OrgUnit>()).AndDoes(x => orgList.Add(x.Arg <OrgUnit>())).AndDoes(x => x.Arg <OrgUnit>().Id = orgIdCount).AndDoes(x => orgIdCount++);

            _cachedAddressRepoMock.Insert(new CachedAddress()).ReturnsForAnyArgs(x => x.Arg <CachedAddress>()).AndDoes(x => cachedAddressList.Add(x.Arg <CachedAddress>())).AndDoes(x => x.Arg <CachedAddress>().Id = cachedIdCount).AndDoes(x => cachedIdCount++);

            _cachedAddressRepoMock.AsQueryable().Returns(cachedAddressList.AsQueryable());

            _subRepo      = NSubstitute.Substitute.For <IGenericRepository <Core.DomainModel.Substitute> >();
            _reportRepo   = NSubstitute.Substitute.For <IGenericRepository <DriveReport> >();
            _driveService = NSubstitute.Substitute.For <IDriveReportService>();
            _subservice   = NSubstitute.Substitute.For <ISubstituteService>();

            _actualLaunderer.Launder(new Address()).ReturnsForAnyArgs(x => x.Arg <CachedAddress>());

            _uut = new UpdateService(_emplRepoMock, _orgUnitRepoMock, _personRepoMock, _cachedAddressRepoMock,
                                     _personalAddressRepoMock, _actualLaunderer, _coordinates, _dataProvider, _mailSender, NSubstitute.Substitute.For <IAddressHistoryService>(), _reportRepo, _driveService, _subservice, _subRepo);
        }
示例#4
0
        public void SetUp()
        {
            _dmzGPSRepoMock = NSubstitute.Substitute.For <IGenericRepository <Core.DmzModel.GPSCoordinate> >();
            _logger         = NSubstitute.Substitute.For <ILogger>();

            _dmzGPSRepoMock.WhenForAnyArgs(x => x.Delete(new Core.DmzModel.GPSCoordinate())).Do(p => _dmzGPSList.Remove(p.Arg <Core.DmzModel.GPSCoordinate>()));
            _dmzGPSRepoMock.WhenForAnyArgs(x => x.Insert(new Core.DmzModel.GPSCoordinate())).Do(t => _dmzGPSList.Add(t.Arg <Core.DmzModel.GPSCoordinate>()));


            _dmzGPSList = new List <GPSCoordinate>()
            {
                new GPSCoordinate()
                {
                    Latitude  = StringCipher.Encrypt("1", Encryptor.EncryptKey),
                    Longitude = StringCipher.Encrypt("1", Encryptor.EncryptKey),
                },
                new GPSCoordinate()
                {
                    Latitude  = StringCipher.Encrypt("2", Encryptor.EncryptKey),
                    Longitude = StringCipher.Encrypt("2", Encryptor.EncryptKey),
                },
                new GPSCoordinate()
                {
                    Latitude  = "57.0482206",
                    Longitude = "9.9193939",
                },
                new GPSCoordinate()
                {
                    Latitude  = "A",
                    Longitude = "9.9193939",
                }
            };

            _dmzGPSRepoMock.AsQueryable().ReturnsForAnyArgs(_dmzGPSList.AsQueryable());
            _gpsEncryptService = new GPSEncryptService(_logger);
        }
        public async Task <List <SportsmanSupplementedGetAllRecords> > GetAllSportsmanSupplementedAsync()      //+
        {
            List <Sportsman> sportsman = await sportsmanRepository.AsQueryable()
                                         .Include(l => l.Federation)
                                         .Include(q => q.Sport)
                                         .Include(q => q.Student)
                                         .ToListAsync();

            List <SportsmanSupplementedGetAllRecords> resultModel = new List <SportsmanSupplementedGetAllRecords>();

            foreach (var item in sportsman)
            {
                resultModel.Add(new SportsmanSupplementedGetAllRecords
                {
                    FIO            = item.Student.FIO,
                    Status         = item.Status,
                    FederationName = item.Federation.FederationName,
                    DataBasis      = item.Federation.DataBasis,
                    NameSport      = item.Sport.NameSport
                });
            }

            return(resultModel);
        }
        public async Task <List <TeacherSupplementedGetAllRecords> > GetAllTeacherSupplementedAsync()
        {
            List <Teacher> teacher = await teacherRepository.AsQueryable()
                                     .Include(q => q.Employee)
                                     .Include(q => q.Experience)
                                     .Include(q => q.Position)
                                     .ToListAsync();

            List <TeacherSupplementedGetAllRecords> resultModel = new List <TeacherSupplementedGetAllRecords>();

            foreach (var item in teacher)
            {
                resultModel.Add(new TeacherSupplementedGetAllRecords
                {
                    FIO            = item.FIO,
                    DateOfEmployee = item.Employee.DateOfEmployee,
                    Specialization = item.Employee.Specialization,
                    ExperienceYear = item.Experience.ExperienceYear,
                    PositionName   = item.Position.PositionName
                });
            }

            return(resultModel);
        }
示例#7
0
        public async Task <List <ShopServiceModel> > GetAllShopServicesAsync()
        {
            var entity = await shopServicesRepository.AsQueryable()
                         .OrderByDescending(s => s.Id)
                         .ToListAsync();

            List <ShopServiceModel> result = new List <ShopServiceModel>();

            foreach (var item in entity)
            {
                result.Add(
                    new ShopServiceModel()
                {
                    Id = item.Id,
                    DescriptionService = item.DescriptionService,
                    PriceService       = item.Discounts == null ? item.PriceService : PriceHelper.GetPriceWithDiscount(item.PriceService, item.Discounts),
                    ServicesName       = item.ServicesName,
                    Discount           = PriceHelper.IsDiscountExpired(item.Discounts)
                }
                    );
            }

            return(result);
        }
        /// <summary>
        /// Syncs all rates from OS2 database to DMZ database.
        /// </summary>
        public void SyncToDmz()
        {
            var i           = 0;
            var currentYear = DateTime.Now.Year;
            var rateList    = _masterRateRepo.AsQueryable().Where(x => x.Active && x.Year == currentYear).ToList();
            var max         = rateList.Count;

            foreach (var masterRate in rateList)
            {
                i++;
                if (i % 10 == 0)
                {
                    Console.WriteLine("Syncing rate " + i + " of " + max);
                }

                var rate = new Core.DmzModel.Rate()
                {
                    Id          = masterRate.Id,
                    Description = masterRate.Type.Description,
                    Year        = masterRate.Year.ToString()
                };

                var dmzRate = _dmzRateRepo.AsQueryable().FirstOrDefault(x => x.Id == rate.Id);

                if (dmzRate == null)
                {
                    _dmzRateRepo.Insert(rate);
                }
                else
                {
                    dmzRate.Description = rate.Description;
                    dmzRate.Year        = rate.Year;
                }
            }
            _dmzRateRepo.Save();
        }
        public void SetUp()
        {
            var personList = new List <Person>();
            var emplList   = new List <Employment>();

            var emplIdCount   = 0;
            var personIdCount = 0;

            var cachedAddressList   = new List <CachedAddress>();
            var cachedIdCount       = 0;
            var personalAddressList = new List <PersonalAddress>();
            var personalIdCount     = 0;

            _emplRepoMock            = NSubstitute.Substitute.For <IGenericRepository <Employment> >();
            _orgUnitRepoMock         = NSubstitute.Substitute.For <IGenericRepository <OrgUnit> >();
            _personRepoMock          = NSubstitute.Substitute.For <IGenericRepository <Person> >();
            _cachedAddressRepoMock   = NSubstitute.Substitute.For <IGenericRepository <CachedAddress> >();
            _personalAddressRepoMock = NSubstitute.Substitute.For <IGenericRepository <PersonalAddress> >();
            _actualLaundererMock     = NSubstitute.Substitute.For <IAddressLaunderer>();
            _coordinatesMock         = NSubstitute.Substitute.For <IAddressCoordinates>();
            _dataProviderMock        = NSubstitute.Substitute.For <IDbUpdaterDataProvider>();
            _workAddressRepoMock     = NSubstitute.Substitute.For <IGenericRepository <WorkAddress> >();
            _mailServiceMock         = NSubstitute.Substitute.For <IMailService>();
            _actualLaunderer         = NSubstitute.Substitute.For <IAddressLaunderer>();
            _coordinates             = NSubstitute.Substitute.For <IAddressCoordinates>();
            _dataProvider            = NSubstitute.Substitute.For <IDbUpdaterDataProvider>();


            _subRepo      = NSubstitute.Substitute.For <IGenericRepository <Core.DomainModel.Substitute> >();
            _reportRepo   = NSubstitute.Substitute.For <IGenericRepository <DriveReport> >();
            _driveService = NSubstitute.Substitute.For <IDriveReportService>();
            _subservice   = NSubstitute.Substitute.For <ISubstituteService>();

            _personRepoMock.AsQueryable().Returns(personList.AsQueryable());

            _personRepoMock.Insert(new Person()).ReturnsForAnyArgs(x => x.Arg <Person>()).AndDoes(x => personList.Add(x.Arg <Person>())).AndDoes(x => x.Arg <Person>().Id = personIdCount).AndDoes(x => personIdCount++);

            _emplRepoMock.AsQueryable().Returns(emplList.AsQueryable());

            _emplRepoMock.Insert(new Employment()).ReturnsForAnyArgs(x => x.Arg <Employment>()).AndDoes(x => emplList.Add(x.Arg <Employment>())).AndDoes(x => x.Arg <Employment>().Id = emplIdCount).AndDoes(x => emplIdCount++);

            _cachedAddressRepoMock.Insert(new CachedAddress()).ReturnsForAnyArgs(x => x.Arg <CachedAddress>()).AndDoes(x => cachedAddressList.Add(x.Arg <CachedAddress>())).AndDoes(x => x.Arg <CachedAddress>().Id = cachedIdCount).AndDoes(x => cachedIdCount++);

            cachedAddressList.Add(new CachedAddress()
            {
                Id           = 999,
                StreetName   = "Katrinebjergvej",
                StreetNumber = "93B",
                ZipCode      = 8200,
                Town         = "Aarhus N",
                DirtyString  = "Katrinebjergvej 93B, 8200 Aarhus N",
            });

            _cachedAddressRepoMock.AsQueryable().Returns(cachedAddressList.AsQueryable());

            _personalAddressRepoMock.Insert(new PersonalAddress()).ReturnsForAnyArgs(x => x.Arg <PersonalAddress>()).AndDoes(x => personalAddressList.Add(x.Arg <PersonalAddress>())).AndDoes(x => x.Arg <PersonalAddress>().Id = personalIdCount).AndDoes(x => personalIdCount++);

            _personalAddressRepoMock.AsQueryable().Returns(personalAddressList.AsQueryable());

            _actualLaundererMock.Launder(new Address()).ReturnsForAnyArgs(x => x.Arg <CachedAddress>());

            _uut = new UpdateService(_emplRepoMock, _orgUnitRepoMock, _personRepoMock, _cachedAddressRepoMock,
                                     _personalAddressRepoMock, _actualLaunderer, _coordinates, _dataProvider, _mailServiceMock, NSubstitute.Substitute.For <IAddressHistoryService>(), _reportRepo, _driveService, _subservice, _subRepo);

            _orgUnitRepoMock.AsQueryable().ReturnsForAnyArgs(new List <OrgUnit>()
            {
                new OrgUnit()
                {
                    Id                    = 1,
                    OrgId                 = 1,
                    ShortDescription      = "ITM",
                    LongDescription       = "IT Minds, Aarhus",
                    Level                 = 0,
                    HasAccessToFourKmRule = false,
                },
                new OrgUnit()
                {
                    Id                    = 2,
                    OrgId                 = 2,
                    ShortDescription      = "ITMB",
                    LongDescription       = "IT Minds, Aarhus child",
                    Level                 = 1,
                    ParentId              = 1,
                    HasAccessToFourKmRule = false,
                }
            }.AsQueryable());

            personList.Add(new Person()
            {
                Id = 1,
            });
        }
示例#10
0
        /// <summary>
        /// Returns every task that a given OrgUnit can use. This depends on the task usages of the parent OrgUnit.
        /// For every task returned, possibly a taskUsage is returned too, if the OrgUnit is currently using that task.
        /// </summary>
        /// <param name="id">ID of the OrgUnit</param>
        /// <param name="taskGroup">Optional id to filter by task group</param>
        /// <param name="tasks">Routing qualifier</param>
        /// <param name="pagingModel">Paging options</param>
        /// <returns>List of (task, taskUsage), where the taskUsage might be null</returns>
        public HttpResponseMessage GetAccessibleTasks(int id, int?taskGroup, bool?tasks, [FromUri] PagingModel <TaskRef> pagingModel)
        {
            try
            {
                var orgUnit = Repository.GetByKey(id);

                if (orgUnit == null)
                {
                    return(NotFound());
                }

                if (!AllowRead(orgUnit))
                {
                    return(Forbidden());
                }

                IQueryable <TaskRef> taskQuery;
                // if the org unit has a parent, only select those tasks that is in use by the parent org unit
                if (orgUnit.ParentId.HasValue)
                {
                    // this is not so good performance wise
                    var orgUnitQueryable = Repository.AsQueryable().Where(unit => unit.Id == id);
                    taskQuery = orgUnitQueryable.SelectMany(u => u.Parent.TaskUsages.Select(usage => usage.TaskRef));

                    // it would have been better with:
                    // pagingModel.Where(taskRef => taskRef.Usages.Any(usage => usage.OrgUnitId == orgUnit.ParentId));
                    // but we cant because of a bug in the mysql connector: http://bugs.mysql.com/bug.php?id=70722
                }
                else
                {
                    taskQuery = _taskRepository.AsQueryable();
                }

                // if a task group is given, only find the tasks in that group and sub groups
                if (taskGroup.HasValue)
                {
                    pagingModel.Where(
                        taskRef =>
                        (taskRef.ParentId.Value == taskGroup.Value ||
                         taskRef.Parent.ParentId.Value == taskGroup.Value) &&
                        !taskRef.Children.Any());
                }
                else
                {
                    // else get all task leaves
                    pagingModel.Where(taskRef => !taskRef.Children.Any());
                }

                var theTasks = Page(taskQuery, pagingModel).ToList();

                // convert tasks to DTO containing both the task and possibly also a taskUsage, if that exists
                var dtos = (from taskRef in theTasks
                            let taskUsage = taskRef.Usages.FirstOrDefault(usage => usage.OrgUnitId == id)
                                            select new TaskRefUsageDTO()
                {
                    TaskRef = Map <TaskRef, TaskRefDTO>(taskRef),
                    Usage = Map <TaskUsage, TaskUsageDTO>(taskUsage)
                }).ToList();             // must call .ToList here else the output will be wrapped in $type,$values

                return(Ok(dtos));
            }
            catch (Exception e)
            {
                return(LogError(e));
            }
        }
示例#11
0
 public ItProject GetById(int id)
 {
     return(_repository.AsQueryable().ById(id));
 }
 public IHttpActionResult HasLicensePlate([FromODataUri] int key, ODataActionParameters parameters)
 {
     return(Ok(_licensePlateRepo.AsQueryable().Any(x => x.PersonId == key)));
 }
        /// <summary>
        /// Synchronizes all DriveReports from DMZ to OS2 database.
        /// </summary>
        public void SyncFromDmz()
        {
            var reports = _dmzDriveReportRepo.AsQueryable().Where(x => x.SyncedAt == null).ToList();


            var max = reports.Count;

            _logger.Debug($"{this.GetType().Name}, SyncFromDMZ(), Amount of DMZ DriveReports: {max}");

            for (var i = 0; i < max; i++)
            {
                var coordinatesFailed = false;
                var dmzReport         = reports[i];

                dmzReport.Profile = Encryptor.DecryptProfile(dmzReport.Profile);

                Console.WriteLine("Syncing report " + i + " of " + max + " from DMZ.");

                var rate = _rateRepo.AsQueryable().FirstOrDefault(x => x.Id.Equals(dmzReport.RateId));

                var points    = new List <DriveReportPoint>();
                var viaPoints = new List <DriveReportPoint>();
                for (var j = 0; j < dmzReport.Route.GPSCoordinates.Count; j++)
                {
                    var gpsCoord = dmzReport.Route.GPSCoordinates.ToArray()[j];
                    try
                    {
                        gpsCoord = Encryptor.DecryptGPSCoordinate(gpsCoord);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error($"{this.GetType().Name}, SyncFromDMZ(), Error decrypting gps coordinate for DMZReportId= {dmzReport.Id} DMZReportProfile= {dmzReport.Profile} and Coordinate: {gpsCoord}", ex);
                    }

                    points.Add(new DriveReportPoint
                    {
                        Latitude  = gpsCoord.Latitude,
                        Longitude = gpsCoord.Longitude,
                    });

                    if (gpsCoord.IsViaPoint || j == 0 || j == dmzReport.Route.GPSCoordinates.Count - 1)
                    {
                        try
                        {
                            var address = _coordinates.GetAddressFromCoordinates(new Address
                            {
                                Latitude  = gpsCoord.Latitude,
                                Longitude = gpsCoord.Longitude
                            });

                            viaPoints.Add(new DriveReportPoint()
                            {
                                Latitude     = gpsCoord.Latitude,
                                Longitude    = gpsCoord.Longitude,
                                StreetName   = address.StreetName,
                                StreetNumber = address.StreetNumber,
                                ZipCode      = address.ZipCode,
                                Town         = address.Town,
                            });
                        }
                        catch (AddressCoordinatesException e)
                        {
                            coordinatesFailed = true;
                            _logger.Error($"{this.GetType().Name}, SyncFromDMZ().AddressCoordinatesException in DMZ reportID= {dmzReport.Id}, ProfileFuldNavn= {dmzReport.Profile.FullName} and purpose= {dmzReport.Purpose} + Invalid coordinates and was not synchronized", e);
                            break;
                        }
                        catch (Exception e)
                        {
                            coordinatesFailed = true;
                            _logger.Error($"{this.GetType().Name}, SyncFromDMZ().AddressCoordinatesException in DMZ reportID= {dmzReport.Id}, ProfileFuldNavn= {dmzReport.Profile.FullName} and purpose= {dmzReport.Purpose} + Invalid coordinates and was not synchronized", e);
                            break;
                        }
                    }
                }

                if (coordinatesFailed)
                {
                    continue;
                }

                var         licensePlate = _licensePlateRepo.AsQueryable().FirstOrDefault(x => x.PersonId.Equals(dmzReport.ProfileId) && x.IsPrimary);
                var         plate        = licensePlate != null ? licensePlate.Plate : "UKENDT";
                DriveReport newReport    = new Core.DomainModel.DriveReport();
                newReport.FourKmRule           = dmzReport.FourKmRule;
                newReport.IsFromApp            = true;
                newReport.HomeToBorderDistance = dmzReport.HomeToBorderDistance;
                newReport.StartsAtHome         = dmzReport.StartsAtHome;
                newReport.EndsAtHome           = dmzReport.EndsAtHome;
                newReport.Purpose           = dmzReport.Purpose;
                newReport.PersonId          = dmzReport.ProfileId;
                newReport.EmploymentId      = dmzReport.EmploymentId;
                newReport.KmRate            = rate.KmRate;
                newReport.UserComment       = dmzReport.ManualEntryRemark;
                newReport.Status            = ReportStatus.Pending;
                newReport.LicensePlate      = plate;
                newReport.Comment           = "";
                newReport.DriveReportPoints = viaPoints;
                //var newReport = new Core.DomainModel.DriveReport
                //{

                //    IsFromApp = true,
                //    FourKmRule = dmzReport.FourKmRule,
                //    HomeToBorderDistance = dmzReport.HomeToBorderDistance,
                //    StartsAtHome = dmzReport.StartsAtHome,
                //    EndsAtHome = dmzReport.EndsAtHome,
                //    Purpose = dmzReport.Purpose,
                //    PersonId = dmzReport.ProfileId,
                //    EmploymentId = dmzReport.EmploymentId,
                //    KmRate = rate.KmRate,
                //    UserComment = dmzReport.ManualEntryRemark,
                //    Status = ReportStatus.Pending,
                //    LicensePlate = plate,
                //    Comment = "",
                //    DriveReportPoints = viaPoints
                //};
                newReport.Distance           = dmzReport.Route.TotalDistance;
                newReport.KilometerAllowance = dmzReport.Route.GPSCoordinates.Count > 0 ? KilometerAllowance.Calculated : KilometerAllowance.Read;
                // Date might not be correct. Depends which culture is delivered from app.
                // https://msdn.microsoft.com/en-us/library/cc165448.aspx
                newReport.DriveDateTimestamp   = (Int32)(Convert.ToDateTime(dmzReport.Date).Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
                newReport.CreatedDateTimestamp = (Int32)(Convert.ToDateTime(dmzReport.Date).Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
                newReport.TFCode   = rate.Type.TFCode;
                newReport.FullName = dmzReport.Profile.FullName;



                newReport.RouteGeometry = GeoService.Encode(points);

                Profile profileAfterEncryption = null;
                try {
                    profileAfterEncryption = Encryptor.EncryptProfile(dmzReport.Profile);
                    _driveService.Create(newReport);
                    reports[i].SyncedAt = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    _dmzDriveReportRepo.Save();
                } catch (Exception e)
                {
                    _logger.Error($"{this.GetType().Name}, SyncFromDMZ(), Error when encrypting or saving drivereport from dmz or updating dmz report. DMZ reportID= {dmzReport.Id}. Exception= {e.Message}, ProfileFuldNavn= {dmzReport.Profile.FullName}, HomeLatitude= {dmzReport.Profile.HomeLatitude}, HomeLongitude= {dmzReport.Profile.HomeLongitude}. Report was not synchronized", e);
                }
            }
        }
        public IActionResult Report([FromBody] DriveViewModel driveViewModel)
        {
            try
            {
                var appLogin = loginRepo.AsQueryable().Where(l => l.GuId == driveViewModel.Authorization.GuId).SingleOrDefault();
                if (appLogin == null)
                {
                    var message = $"Ugyldigt login token";
                    logger.LogWarning(message);
                    return(ErrorResult(message, ErrorCodes.InvalidAuthorization, HttpStatusCode.Unauthorized));
                }

                if (appLogin.Person.Id != driveViewModel.DriveReport.ProfileId)
                {
                    var message = $"Forsøg på at indberette kørsel på forkert person";
                    logger.LogWarning(message);
                    return(ErrorResult(message, ErrorCodes.ReportAndUserDoNotMatch, HttpStatusCode.Unauthorized));
                }

                var duplicateReportCheck = driveReportRepo.AsQueryable().Where(t => t.AppUuid == driveViewModel.DriveReport.Uuid).Any();
                if (duplicateReportCheck)
                {
                    var message = "Indberetning afvist da den allerede er indberettet";
                    logger.LogWarning(message);
                    return(ErrorResult(message, ErrorCodes.DuplicateReportFound, HttpStatusCode.OK));
                }
                var appReport = driveViewModel.DriveReport;

                var points    = new List <DriveReportPoint>();
                var viaPoints = new List <DriveReportPoint>();
                for (var i = 0; i < appReport.route.GPSCoordinates.Count; i++)
                {
                    var coordinate = appReport.route.GPSCoordinates.ToArray()[i];
                    points.Add(new DriveReportPoint
                    {
                        Latitude  = coordinate.Latitude,
                        Longitude = coordinate.Longitude,
                    });

                    if (coordinate.IsViaPoint || i == 0 || i == appReport.route.GPSCoordinates.Count - 1)
                    {
                        var address = addressCoordinates.GetAddressFromCoordinates(new Address
                        {
                            Latitude  = coordinate.Latitude,
                            Longitude = coordinate.Longitude
                        });

                        viaPoints.Add(new DriveReportPoint()
                        {
                            Latitude     = coordinate.Latitude,
                            Longitude    = coordinate.Longitude,
                            StreetName   = address.StreetName,
                            StreetNumber = address.StreetNumber,
                            ZipCode      = address.ZipCode,
                            Town         = address.Town,
                        });
                    }
                }

                var rate         = rateRepo.AsQueryable().Where(r => r.Id == appReport.RateId).First();
                var licensePlate = appLogin.Person.LicensePlates.Where(p => p.IsPrimary).FirstOrDefault();

                DriveReport newReport = new DriveReport();
                newReport.AppUuid              = appReport.Uuid;
                newReport.FourKmRule           = appReport.FourKmRule;
                newReport.IsFromApp            = true;
                newReport.HomeToBorderDistance = appReport.HomeToBorderDistance;
                newReport.StartsAtHome         = appReport.StartsAtHome;
                newReport.EndsAtHome           = appReport.EndsAtHome;
                newReport.Purpose              = appReport.Purpose;
                newReport.PersonId             = appReport.ProfileId;
                newReport.EmploymentId         = appReport.EmploymentId;
                newReport.KmRate               = rate.KmRate;
                newReport.UserComment          = appReport.ManualEntryRemark;
                newReport.Status               = ReportStatus.Pending;
                newReport.LicensePlate         = licensePlate != null ? licensePlate.Plate : "UKENDT";
                newReport.Comment              = "";
                newReport.DriveReportPoints    = viaPoints;
                newReport.Distance             = appReport.route.TotalDistance;
                newReport.KilometerAllowance   = appReport.route.GPSCoordinates.Count > 0 ? KilometerAllowance.Calculated : KilometerAllowance.Read;
                newReport.DriveDateTimestamp   = (Int32)(Convert.ToDateTime(appReport.Date).Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
                newReport.CreatedDateTimestamp = (Int32)(Convert.ToDateTime(appReport.Date).Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
                newReport.TFCode               = rate.Type.TFCode;
                newReport.TFCodeOptional       = rate.Type.TFCodeOptional;
                newReport.FullName             = appLogin.Person.FullName;
                newReport.RouteGeometry        = GeoService.Encode(points);
                driveService.Create(newReport);

                return(Ok());
            }
            catch (Exception ex)
            {
                var message = "Kunne ikke gemme indberetning fra app";
                logger.LogError(ex, $"{message}, uuid: {driveViewModel.DriveReport.Uuid}");
                return(ErrorResult(message, ErrorCodes.SaveError, HttpStatusCode.BadRequest));
            }
        }
        public void GetResponsibleLeader_WithNoSub_ShouldGetActualLeader()
        {
            var leader = new Person()
            {
                Id        = 1,
                FirstName = "Test",
                LastName  = "Testesen",
                Initials  = "TT",
                FullName  = "Test Testesen [TT]"
            };

            var user = new Person()
            {
                Id        = 2,
                FirstName = "User",
                LastName  = "Usersen",
                Initials  = "UU",
                FullName  = "User Usersen [UU]"
            };

            var orgUnit = new OrgUnit()
            {
                Id = 1,
            };

            var leaderEmpl = new Employment()
            {
                Id        = 1,
                OrgUnit   = orgUnit,
                OrgUnitId = 1,
                Person    = leader,
                PersonId  = leader.Id,
                IsLeader  = true
            };

            var userEmpl = new Employment()
            {
                Id        = 2,
                OrgUnit   = orgUnit,
                PersonId  = user.Id,
                OrgUnitId = 1,
                Person    = user,
                IsLeader  = false
            };

            var substitute = new Core.DomainModel.Substitute()
            {
                Id        = 1,
                OrgUnitId = 12,
                PersonId  = 3,
                LeaderId  = 1,
                Sub       = new Person()
                {
                    FullName = "En Substitute [ES]"
                },
                StartDateTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1).AddDays(-1))).TotalSeconds,
                EndDateTimestamp   = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1).AddDays(1))).TotalSeconds,
            };

            _emplMock.AsQueryable().ReturnsForAnyArgs(new List <Employment>()
            {
                leaderEmpl, userEmpl
            }.AsQueryable());

            _orgUnitMock.AsQueryable().ReturnsForAnyArgs(new List <OrgUnit>()
            {
                orgUnit
            }.AsQueryable());

            _subMock.AsQueryable().ReturnsForAnyArgs(new List <Core.DomainModel.Substitute>()
            {
                substitute
            }.AsQueryable());

            var report = new DriveReport()
            {
                Id           = 1,
                Employment   = userEmpl,
                EmploymentId = userEmpl.Id,
                PersonId     = user.Id,
                Person       = user
            };


            var res = _uut.GetResponsibleLeaderForReport(report);

            Assert.AreEqual("Test Testesen [TT]", res.FullName);
        }
 private IEnumerable <DriveReport> GetDriveReportsToReimburse()
 {
     return(_reportRepo.AsQueryable().Where(r => r.Status == ReportStatus.Accepted).ToList());
 }
示例#17
0
        /// <summary>
        /// Synchronizes all DriveReports from DMZ to OS2 database.
        /// </summary>
        public void SyncFromDmz()
        {
            var reports = _dmzDriveReportRepo.AsQueryable().Where(x => x.SyncedAt == null).ToList();
            var max     = reports.Count;

            for (var i = 0; i < max; i++)
            {
                var coordinatesFailed = false;
                var dmzReport         = reports[i];
                dmzReport.Profile = Encryptor.DecryptProfile(dmzReport.Profile);
                Console.WriteLine("Syncing report " + i + " of " + max + " from DMZ.");
                var rate      = _rateRepo.AsQueryable().First(x => x.Id.Equals(dmzReport.RateId));
                var points    = new List <DriveReportPoint>();
                var viaPoints = new List <DriveReportPoint>();
                for (var j = 0; j < dmzReport.Route.GPSCoordinates.Count; j++)
                {
                    var gpsCoord = dmzReport.Route.GPSCoordinates.ToArray()[j];
                    gpsCoord = Encryptor.DecryptGPSCoordinate(gpsCoord);

                    points.Add(new DriveReportPoint
                    {
                        Latitude  = gpsCoord.Latitude,
                        Longitude = gpsCoord.Longitude,
                    });

                    if (gpsCoord.IsViaPoint || j == 0 || j == dmzReport.Route.GPSCoordinates.Count - 1)
                    {
                        try
                        {
                            var address = _coordinates.GetAddressFromCoordinates(new Address
                            {
                                Latitude  = gpsCoord.Latitude,
                                Longitude = gpsCoord.Longitude
                            });

                            viaPoints.Add(new DriveReportPoint()
                            {
                                Latitude     = gpsCoord.Latitude,
                                Longitude    = gpsCoord.Longitude,
                                StreetName   = address.StreetName,
                                StreetNumber = address.StreetNumber,
                                ZipCode      = address.ZipCode,
                                Town         = address.Town,
                            });
                        }
                        catch (AddressCoordinatesException e)
                        {
                            coordinatesFailed = true;
                            _logger.Log("Indberetning tilhørende " + dmzReport.Profile.FullName + " med formål \"" + dmzReport.Purpose + "\" har ugyldige koordinater og blev ikke synkroniseret.", "dmz", e, 2);
                            break;
                        }
                    }
                }

                if (coordinatesFailed)
                {
                    continue;
                }

                var licensePlate = _licensePlateRepo.AsQueryable().FirstOrDefault(x => x.PersonId.Equals(dmzReport.ProfileId) && x.IsPrimary);
                var plate        = licensePlate != null ? licensePlate.Plate : "UKENDT";

                var newReport = new Core.DomainModel.DriveReport
                {
                    IsFromApp          = true,
                    Distance           = dmzReport.Route.TotalDistance,
                    KilometerAllowance = dmzReport.Route.GPSCoordinates.Count > 0 ? KilometerAllowance.Calculated : KilometerAllowance.Read,
                    // Date might not be correct. Depends which culture is delivered from app.
                    // https://msdn.microsoft.com/en-us/library/cc165448.aspx
                    DriveDateTimestamp   = (Int32)(Convert.ToDateTime(dmzReport.Date).Subtract(new DateTime(1970, 1, 1)).TotalSeconds),
                    CreatedDateTimestamp = (Int32)(Convert.ToDateTime(dmzReport.Date).Subtract(new DateTime(1970, 1, 1)).TotalSeconds),
                    StartsAtHome         = dmzReport.StartsAtHome,
                    EndsAtHome           = dmzReport.EndsAtHome,
                    Purpose           = dmzReport.Purpose,
                    PersonId          = dmzReport.ProfileId,
                    EmploymentId      = dmzReport.EmploymentId,
                    KmRate            = rate.KmRate,
                    TFCode            = rate.Type.TFCode,
                    UserComment       = dmzReport.ManualEntryRemark,
                    Status            = ReportStatus.Pending,
                    FullName          = dmzReport.Profile.FullName,
                    LicensePlate      = plate,
                    Comment           = "",
                    DriveReportPoints = viaPoints
                };

                newReport.RouteGeometry = GeoService.Encode(points);

                try {
                    _driveService.Create(newReport);
                    reports[i].SyncedAt = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    _dmzDriveReportRepo.Save();
                } catch (Exception e)
                {
                    _logger.Log("En ukendt fejl opstod under synkronisering af indberetning tilhørende " + reports[i].Profile.FullName + ". Indberetningen blev ikke synkroniseret.", "dmz", e, 2);
                }
            }
        }
        public void GetEmploymentForLeader_MultipleLayers()
        {
            _persons = new List <Person> {
                new Person
                {
                    Id          = 1,
                    FirstName   = "Morten",
                    LastName    = "Rasmussen",
                    CprNumber   = "1234567890",
                    Initials    = "MR",
                    Employments = new List <Employment>()
                    {
                        new Employment
                        {
                            Id      = 1,
                            OrgUnit = new OrgUnit
                            {
                                Id               = 1,
                                OrgId            = 1,
                                ShortDescription = "orgUnit1",
                                LongDescription  = "OrgUnit 1.0",
                                Level            = 1,
                                ParentId         = null
                            },
                            OrgUnitId = 1,
                            IsLeader  = true,
                            PersonId  = 1,
                            Person    = _persons.AsQueryable().ToList()[0]
                        },
                        new Employment
                        {
                            Id      = 2,
                            OrgUnit = new OrgUnit
                            {
                                Id               = 2,
                                OrgId            = 2,
                                ShortDescription = "orgUnit2",
                                LongDescription  = "OrgUnit 2.1",
                                Level            = 2,
                                ParentId         = 1
                            },
                            OrgUnitId = 2,
                            IsLeader  = true,
                            PersonId  = 1,
                            Person    = _persons.AsQueryable().ToList()[0]
                        },
                        new Employment
                        {
                            Id      = 3,
                            OrgUnit = new OrgUnit
                            {
                                Id               = 2,
                                OrgId            = 2,
                                ShortDescription = "orgUnit2",
                                LongDescription  = "OrgUnit 2.1",
                                Level            = 2,
                                ParentId         = 1
                            },
                            OrgUnitId = 3,
                            IsLeader  = true,
                            PersonId  = 1,
                            Person    = _persons.AsQueryable().ToList()[0]
                        }
                    }
                },
                new Person
                {
                    Id        = 2,
                    FirstName = "Morten",
                    LastName  = "Jørgensen",
                    CprNumber = "0987654321",
                    Initials  = "MJ"
                },
                new Person
                {
                    Id        = 3,
                    FirstName = "Jacob",
                    LastName  = "Jensen",
                    CprNumber = "456456456",
                    Initials  = "JOJ"
                }
            }.AsQueryable();

            _employmentsRepoMock.AsQueryable().ReturnsForAnyArgs(new List <Employment>
            {
                new Employment
                {
                    Id      = 1,
                    OrgUnit = new OrgUnit
                    {
                        Id               = 1,
                        OrgId            = 1,
                        ShortDescription = "orgUnit1",
                        LongDescription  = "OrgUnit 1.0",
                        Level            = 1,
                        ParentId         = null
                    },
                    OrgUnitId = 1,
                    IsLeader  = true,
                    PersonId  = 1,
                    Person    = _persons.AsQueryable().ToList()[0]
                },
                new Employment
                {
                    Id      = 2,
                    OrgUnit = new OrgUnit
                    {
                        Id               = 2,
                        OrgId            = 2,
                        ShortDescription = "orgUnit2",
                        LongDescription  = "OrgUnit 2.1",
                        Level            = 2,
                        ParentId         = 1
                    },
                    OrgUnitId = 2,
                    IsLeader  = true,
                    PersonId  = 1,
                    Person    = _persons.AsQueryable().ToList()[0]
                },
                new Employment
                {
                    Id      = 3,
                    OrgUnit = new OrgUnit
                    {
                        Id               = 2,
                        OrgId            = 2,
                        ShortDescription = "orgUnit2",
                        LongDescription  = "OrgUnit 2.1",
                        Level            = 2,
                        ParentId         = 1
                    },
                    OrgUnitId = 3,
                    IsLeader  = true,
                    PersonId  = 1,
                    Person    = _persons.AsQueryable().ToList()[0]
                },
                new Employment
                {
                    Id      = 5,
                    OrgUnit = new OrgUnit
                    {
                        Id               = 3,
                        OrgId            = 2,
                        ShortDescription = "orgUnit2",
                        LongDescription  = "OrgUnit 2.1",
                        Level            = 2,
                        ParentId         = 1
                    },
                    OrgUnitId = 2,
                    IsLeader  = false,
                    PersonId  = 2,
                    Person    = _persons.AsQueryable().ToList()[1]
                },
                new Employment
                {
                    Id      = 4,
                    OrgUnit = new OrgUnit
                    {
                        Id               = 3,
                        OrgId            = 3,
                        ShortDescription = "orgUnit3",
                        LongDescription  = "OrgUnit 2.2",
                        Level            = 2,
                        ParentId         = 1
                    },
                    OrgUnitId = 3,
                    PersonId  = 3,
                    Person    = _persons.AsQueryable().ToList()[2]
                }
            }.AsQueryable());

            var result = _uut.GetEmployeesOfLeader(_persons.AsQueryable().ToList()[0]);

            // Asserts
            Assert.AreEqual(3, result.Count);
            Assert.IsTrue(result.Contains(_persons.AsQueryable().ToList()[0]));
            Assert.IsTrue(result.Contains(_persons.AsQueryable().ToList()[1]));
            Assert.IsTrue(result.Contains(_persons.AsQueryable().ToList()[2]));
        }
        public void SetUp()
        {
            _persons = new List <Person> {
                new Person
                {
                    Id        = 1,
                    FirstName = "Morten",
                    LastName  = "Rasmussen",
                    CprNumber = "1234567890",
                    Initials  = "MR"
                },
                new Person
                {
                    Id        = 2,
                    FirstName = "Morten",
                    LastName  = "Jørgensen",
                    CprNumber = "0987654321",
                    Initials  = "MJ"
                },
                new Person
                {
                    Id        = 3,
                    FirstName = "Jacob",
                    LastName  = "Jensen",
                    CprNumber = "456456456",
                    Initials  = "JOJ"
                }
            }.AsQueryable();

            _routeMock = NSubstitute.Substitute.For <IRoute <RouteInformation> >();
            _routeMock.GetRoute(DriveReportTransportType.Car, new List <Address>()).ReturnsForAnyArgs(new RouteInformation());
            _personalAddressRepoMock = NSubstitute.Substitute.For <IGenericRepository <PersonalAddress> >();
            _addressRepoMock         = NSubstitute.Substitute.For <IGenericRepository <Address> >();
            _employmentsRepoMock     = NSubstitute.Substitute.For <IGenericRepository <Employment> >();
            _orgUnitsRepoMock        = NSubstitute.Substitute.For <IGenericRepository <OrgUnit> >();

            _orgUnitsRepoMock.AsQueryable().ReturnsForAnyArgs(new List <OrgUnit>
            {
                new OrgUnit
                {
                    Id               = 1,
                    OrgId            = 1,
                    ShortDescription = "orgUnit1",
                    LongDescription  = "OrgUnit 1.0",
                    Level            = 1,
                    ParentId         = null
                },
                new OrgUnit
                {
                    Id               = 2,
                    OrgId            = 2,
                    ShortDescription = "orgUnit2",
                    LongDescription  = "OrgUnit 2.1",
                    Level            = 2,
                    ParentId         = 1
                },
                new OrgUnit
                {
                    Id               = 3,
                    OrgId            = 3,
                    ShortDescription = "orgUnit3",
                    LongDescription  = "OrgUnit 2.2",
                    Level            = 2,
                    ParentId         = 1
                }
            }.AsQueryable());

            _loggerMock      = NSubstitute.Substitute.For <ILogger>();
            _coordinatesMock = NSubstitute.Substitute.For <IAddressCoordinates>();
            _coordinatesMock.GetAddressCoordinates(new Address()).ReturnsForAnyArgs(new Address
            {
                Latitude  = "1",
                Longitude = "1"
            });
            _uut = new Core.ApplicationServices.PersonService(_personalAddressRepoMock, _addressRepoMock, _employmentsRepoMock, _orgUnitsRepoMock, _routeMock, _coordinatesMock, _loggerMock);
        }
        public void NoSubs_NoLeaderInReportOrg_ShouldReturn_ClosestParentOrgLeader()
        {
            _subMock.AsQueryable().ReturnsForAnyArgs(new List<Core.DomainModel.Substitute>().AsQueryable());

            var report = new DriveReport()
            {
                PersonId = 1,
                Person = new Person()
                {
                    Id = 1,
                },
                EmploymentId = 1,
                Employment = new Employment()
                {
                    OrgUnit = new OrgUnit()
                    {
                        Id = 2
                    },
                    OrgUnitId = 2

                }
            };

            _orgUnitMock.AsQueryable().ReturnsForAnyArgs(new List<OrgUnit>()
            {
                new OrgUnit()
                {
                    Id = 1,
                    Level = 0
                },
                new OrgUnit()
                {
                    Id = 2,
                    Level = 1,
                    ParentId = 1,
                    Parent = new OrgUnit()
                    {
                        Id = 1,
                        Level = 0
                    }
                }
            }.AsQueryable());

            _emplMock.AsQueryable().ReturnsForAnyArgs(new List<Employment>()
            {
                new Employment()
                {
                    PersonId = 1,
                    Person = new Person()
                    {
                        Id = 1,
                        FullName = "Jon Badstue"
                    },
                    Id = 1,
                    IsLeader = false,
                    OrgUnit = new OrgUnit()
                    {
                        Id = 2,
                    },
                    OrgUnitId = 2
                },
                new Employment()
                {
                    PersonId = 2,
                    Person = new Person()
                    {
                        Id = 2,
                        FullName = "Eva Due",
                    },
                    Id = 12,
                    IsLeader = true,
                    OrgUnit = new OrgUnit()
                    {
                        Id = 1,
                    },
                    OrgUnitId = 1
                },
            }.AsQueryable());

            var res = _uut.GetResponsibleLeadersForReport(report);
            Assert.AreEqual("Eva Due", res[0].FullName);
        }
示例#21
0
        public void SetUp()
        {
            _dmzRepoMock       = NSubstitute.Substitute.For <IGenericDmzRepository <Profile> >();
            _masterRepoMock    = NSubstitute.Substitute.For <IGenericRepository <Person> >();
            _personServiceMock = NSubstitute.Substitute.For <IPersonService>();


            _dmzRepoMock.WhenForAnyArgs(x => x.Delete(new Profile())).Do(p => _dmzProfileList.Remove(p.Arg <Profile>()));

            _personServiceMock.GetHomeAddress(new Person()).ReturnsForAnyArgs(new PersonalAddress()
            {
                Latitude  = "1",
                Longitude = "2"
            });

            _dmzRepoMock.WhenForAnyArgs(x => x.Insert(new Profile())).Do(t => _dmzProfileList.Add(t.Arg <Profile>()));

            _dmzProfileList   = new List <Profile>();
            _masterPersonList = new List <Person>()
            {
                new Person()
                {
                    Id          = 1,
                    IsActive    = true,
                    FirstName   = "Test",
                    LastName    = "Testesen",
                    Initials    = "TT",
                    FullName    = "Test Testesen [TT]",
                    Employments = new List <Employment>()
                    {
                        new Employment()
                        {
                            Id       = 1,
                            PersonId = 1,
                            Position = "Tester",
                            OrgUnit  = new OrgUnit()
                            {
                                LongDescription = "IT Minds"
                            }
                        }
                    }
                },
                new Person()
                {
                    Id          = 2,
                    FirstName   = "Lars",
                    IsActive    = true,
                    LastName    = "Testesen",
                    Initials    = "LT",
                    FullName    = "Lars Testesen [LT]",
                    Employments = new List <Employment>()
                    {
                        new Employment()
                        {
                            Id       = 1,
                            PersonId = 2,
                            Position = "Tester2",
                            OrgUnit  = new OrgUnit()
                            {
                                LongDescription = "IT Minds"
                            }
                        }
                    }
                },
                new Person()
                {
                    Id          = 3,
                    IsActive    = true,
                    FirstName   = "Preben",
                    LastName    = "Testesen",
                    Initials    = "PT",
                    FullName    = "Preben Testesen [PT]",
                    Employments = new List <Employment>()
                    {
                        new Employment()
                        {
                            Id       = 1,
                            PersonId = 3,
                            Position = "Tester3",
                            OrgUnit  = new OrgUnit()
                            {
                                LongDescription = "IT Minds"
                            }
                        }
                    }
                }
            };


            _masterRepoMock.AsQueryable().ReturnsForAnyArgs(_masterPersonList.AsQueryable());
            _dmzRepoMock.AsQueryable().ReturnsForAnyArgs(_dmzProfileList.AsQueryable());

            _uut = new PersonSyncService(_dmzRepoMock, _masterRepoMock, _personServiceMock);
        }
示例#22
0
        public void SetUp()
        {
            _dmzTokenList    = new List <Token>();
            _masterTokenList = new List <MobileToken>();

            _dmzRepoMock    = NSubstitute.Substitute.For <IGenericRepository <Token> >();
            _masterRepoMock = NSubstitute.Substitute.For <IGenericRepository <MobileToken> >();

            _dmzTokenList.Add(new Token()
            {
                Id        = 7,
                GuId      = Guid.NewGuid().ToString(),
                Status    = 1,
                ProfileId = 1,

                TokenString = "1234",
            });
            _dmzTokenList.Add(new Token()
            {
                Id          = 8,
                GuId        = Guid.NewGuid().ToString(),
                Status      = 1,
                ProfileId   = 3,
                TokenString = "1234",
            });
            _dmzTokenList.Add(new Token()
            {
                Id          = 9,
                GuId        = new Guid().ToString(),
                Status      = 1,
                ProfileId   = 3,
                TokenString = "1234",
            });
            _dmzRepoMock.AsQueryable().ReturnsForAnyArgs(_dmzTokenList.AsQueryable());
            _dmzRepoMock.WhenForAnyArgs(x => x.DeleteRange(_dmzTokenList)).Do(p => _dmzTokenList.Clear());

            _masterTokenList.Add(new MobileToken()
            {
                Id       = 1,
                Guid     = new Guid(_dmzTokenList.ElementAt(0).GuId),
                Status   = MobileTokenStatus.Created,
                PersonId = 1,
                Person   = new Person()
                {
                    IsActive = true
                },
                Token = "1234"
            });
            _masterTokenList.Add(new MobileToken()
            {
                Id       = 2,
                Guid     = new Guid(_dmzTokenList.ElementAt(1).GuId),
                Status   = MobileTokenStatus.Created,
                PersonId = 3,
                Person   = new Person()
                {
                    IsActive = true
                },
                Token = "1234"
            });
            _masterTokenList.Add(new MobileToken()
            {
                Id       = 4,
                Guid     = new Guid(_dmzTokenList.ElementAt(2).GuId),
                Status   = MobileTokenStatus.Created,
                PersonId = 3,
                Person   = new Person()
                {
                    IsActive = true
                },
                Token = "1234"
            });

            _dmzRepoMock.WhenForAnyArgs(x => x.Insert(new Token())).Do(t => _dmzTokenList.Add(t.Arg <Token>()));

            _masterRepoMock.AsQueryable().ReturnsForAnyArgs(_masterTokenList.AsQueryable());

            for (int i = 0; i < _dmzTokenList.Count; i++)
            {
                Encryptor.EncryptToken(_dmzTokenList.ToArray()[i]);
            }

            _uut = new TokenSyncService(_dmzRepoMock, _masterRepoMock);
        }
示例#23
0
 public void SyncFromDmz_ShouldUpdateTokenStatus()
 {
     _uut.SyncFromDmz();
     Assert.AreEqual(MobileTokenStatus.Activated, _masterRepoMock.AsQueryable().ElementAt(0).Status);
 }
        /// <summary>
        /// Validates report and creates it in the database if it validates.
        /// </summary>
        /// <param name="report">Report to be created.</param>
        /// <returns>Created report.</returns>
        public DriveReport Create(DriveReport report)
        {
            if (report.PersonId == 0)
            {
                throw new Exception("No person provided");
            }
            if (!Validate(report))
            {
                throw new Exception("DriveReport has some invalid parameters");
            }

            if (report.IsFromApp)
            {
                report = _calculator.Calculate(null, report);
            }
            else
            {
                if (report.KilometerAllowance != KilometerAllowance.Read)
                {
                    var pointsWithCoordinates = new List <DriveReportPoint>();
                    foreach (var driveReportPoint in report.DriveReportPoints)
                    {
                        if (string.IsNullOrEmpty(driveReportPoint.Latitude) || driveReportPoint.Latitude == "0" ||
                            string.IsNullOrEmpty(driveReportPoint.Longitude) || driveReportPoint.Longitude == "0")
                        {
                            pointsWithCoordinates.Add(
                                (DriveReportPoint)_coordinates.GetAddressCoordinates(driveReportPoint));
                        }
                        else
                        {
                            pointsWithCoordinates.Add(driveReportPoint);
                        }
                    }

                    report.DriveReportPoints = pointsWithCoordinates;

                    var isBike = _rateTypeRepo.AsQueryable().First(x => x.TFCode.Equals(report.TFCode)).IsBike;


                    // Set transportType to Bike if isBike is true. Otherwise set it to Car.
                    var drivenRoute = _route.GetRoute(
                        isBike ? DriveReportTransportType.Bike : DriveReportTransportType.Car, report.DriveReportPoints);


                    report.Distance = drivenRoute.Length / 1000;

                    if (report.Distance < 0)
                    {
                        report.Distance = 0;
                    }

                    report = _calculator.Calculate(drivenRoute, report);
                }
                else
                {
                    report = _calculator.Calculate(null, report);
                }
            }

            // Round off Distance and AmountToReimburse to two decimals.
            report.Distance          = Convert.ToDouble(report.Distance.ToString("0.##", CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
            report.AmountToReimburse = Convert.ToDouble(report.AmountToReimburse.ToString("0.##", CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);

            var createdReport = _driveReportRepository.Insert(report);

            createdReport.UpdateResponsibleLeaders(GetResponsibleLeadersForReport(report));
            var actualLeader = GetActualLeaderForReport(report);

            if (actualLeader != null)
            {
                createdReport.ActualLeaderId = actualLeader.Id;
            }

            if (report.Status == ReportStatus.Rejected)
            {
                // User is editing a rejected report to try and get it approved.
                report.Status = ReportStatus.Pending;
            }

            _driveReportRepository.Save();

            // If the report is calculated or from an app, then we would like to store the points.
            if (report.KilometerAllowance != KilometerAllowance.Read || report.IsFromApp)
            {
                // Reports from app with manual distance have no drivereportpoints.
                if (report.DriveReportPoints.Count > 1)
                {
                    for (var i = 0; i < createdReport.DriveReportPoints.Count; i++)
                    {
                        var currentPoint = createdReport.DriveReportPoints.ElementAt(i);

                        if (i == report.DriveReportPoints.Count - 1)
                        {
                            // last element
                            currentPoint.PreviousPointId = createdReport.DriveReportPoints.ElementAt(i - 1).Id;
                        }
                        else if (i == 0)
                        {
                            // first element
                            currentPoint.NextPointId = createdReport.DriveReportPoints.ElementAt(i + 1).Id;
                        }
                        else
                        {
                            // between first and last
                            currentPoint.NextPointId     = createdReport.DriveReportPoints.ElementAt(i + 1).Id;
                            currentPoint.PreviousPointId = createdReport.DriveReportPoints.ElementAt(i - 1).Id;
                        }
                    }
                    _driveReportRepository.Save();
                }
            }

            //AddFullName(report);

            SixtyDayRuleCheck(report);

            return(report);
        }
        /// <summary>
        /// Gets the ResponsibleLeader for driveReport
        /// </summary>
        /// <param name="driveReport"></param>
        /// <returns>DriveReport with ResponsibleLeader attached</returns>
        public List <Person> GetResponsibleLeadersForReport(DriveReport driveReport)
        {
            var responsibleLeaders   = new List <Person>();
            var currentDateTimestamp = Utilities.ToUnixTime(DateTime.Now);

            // Entity Framework doesnt always return child objects
            // https://stackoverflow.com/questions/29272581/why-ef-navigation-property-return-null

            // Fix for bug that sometimes happens when drivereport is from app, where personid is set, but person is not.
            var personId = _employmentRepository.AsQueryable().First(x => x.PersonId == driveReport.PersonId).PersonId;

            // Fix for bug that sometimes happens when drivereport is from app, where personid is set, but person is not.
            var empl = _employmentRepository.AsQueryable().First(x => x.Id == driveReport.EmploymentId);

            //Fetch personal approver for the person (Person and Leader of the substitute is the same)
            var personalApprovers =
                _substituteRepository.AsQueryable()
                .Where(
                    s =>
                    s.PersonId != s.LeaderId && s.PersonId == personId &&
                    s.StartDateTimestamp <currentDateTimestamp && s.EndDateTimestamp> currentDateTimestamp).ToList();

            if (personalApprovers != null)
            {
                foreach (var substitute in personalApprovers)
                {
                    // There must be only one responsible leaders
                    // Add the personal approver to the list and return the collection
                    responsibleLeaders.Add(substitute.Sub);
                    return(responsibleLeaders);
                }
            }

            //Find an org unit where the person is not the leader, and then find the leader of that org unit to attach to the drive report
            var orgUnit = _orgUnitRepository.AsQueryable().SingleOrDefault(o => o.Id == empl.OrgUnitId);

            if (orgUnit == null)
            {
                return(responsibleLeaders);
            }

            var leaderOfOrgUnit = _employmentRepository.AsQueryable().FirstOrDefault(e => e.OrgUnit.Id == orgUnit.Id && e.IsLeader && e.StartDateTimestamp < currentDateTimestamp && (e.EndDateTimestamp > currentDateTimestamp || e.EndDateTimestamp == 0));

            var currentTimestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            while ((leaderOfOrgUnit == null && orgUnit != null && orgUnit.Parent != null) ||
                   (leaderOfOrgUnit != null && leaderOfOrgUnit.PersonId == personId))
            {
                leaderOfOrgUnit = _employmentRepository
                                  .AsQueryable()
                                  .FirstOrDefault(e =>
                                                  e.OrgUnit.Id == orgUnit.ParentId &&
                                                  e.IsLeader &&
                                                  e.StartDateTimestamp < currentDateTimestamp &&
                                                  (e.EndDateTimestamp == 0 || e.EndDateTimestamp > currentDateTimestamp));

                orgUnit = orgUnit.Parent;
            }

            if (orgUnit == null || leaderOfOrgUnit == null)
            {
                return(responsibleLeaders);
            }

            var leader     = leaderOfOrgUnit.Person;
            var orgToCheck = empl.OrgUnit;

            var leaderOverrulingSubstitutes = _substituteRepository
                                              .AsQueryable()
                                              .Where(
                s =>
                s.PersonId == s.LeaderId &&
                s.PersonId == leader.Id &&
                s.StartDateTimestamp <= currentDateTimestamp && s.EndDateTimestamp >= currentDateTimestamp &&
                s.TakesOverOriginalLeaderReports &&
                s.PersonId != personId
                )
                                              .ToList();

            if (!leaderOverrulingSubstitutes.Any() && !responsibleLeaders.Contains(leader))
            {
                responsibleLeaders.Add(leaderOfOrgUnit.Person);
            }

            // Recursively look for substitutes in child orgs, up to the org of the actual leader.
            // Say the actual leader is leader of orgunit 1 with children 2 and 3. Child 2 has another child 4.
            // A report comes in for orgUnit 4. Check if leader has a substitute for that org.
            // If not then check if leader has a substitute for org 2.
            // If not then return the actual leader.
            List <Substitute> subs = null;
            var loopHasFinished    = false;

            while (!loopHasFinished)
            {
                subs = _substituteRepository.AsQueryable().Where(s => s.OrgUnitId == orgToCheck.Id && s.PersonId == leader.Id && s.StartDateTimestamp <= currentDateTimestamp && s.EndDateTimestamp >= currentDateTimestamp && s.PersonId.Equals(s.LeaderId)).ToList();
                if (subs.Count > 0)
                {
                    foreach (var sub in subs)
                    {
                        if (sub.Sub == null)
                        {
                            // This is a hack fix for a weird bug that happens, where sometimes the Sub navigation property on a Substitute is null, even though the SubId is not.
                            sub.Sub = _employmentRepository.AsQueryable().FirstOrDefault(x => x.PersonId == sub.SubId).Person;
                        }
                        if (!responsibleLeaders.Contains(sub.Sub))
                        {
                            responsibleLeaders.Add(sub.Sub);
                        }
                    }
                    loopHasFinished = true;
                }
                else
                {
                    orgToCheck = orgToCheck.Parent;
                    if (orgToCheck == null || orgToCheck.Id == orgUnit.Parent?.Id)
                    {
                        loopHasFinished = true;
                    }
                }
            }
            // if no leader was found, add the actual leader
            if (responsibleLeaders.Count == 0)
            {
                responsibleLeaders.Add(leaderOfOrgUnit.Person);
            }
            return(responsibleLeaders);
        }
        /// <summary>
        /// Takes a DriveReport as input and returns it with data.
        ///
        /// FourKmRule: If a user has set the FourKmRule to be used, the distance between
        /// the users home and municipality is used in the correction of the driven distance.
        /// If the rule is not used, the distance between the users home and work address are
        /// calculated and used, provided that the user has not set a override for this value.
        ///
        /// Calculated: The driven route is calculated, and based on whether the user starts
        /// and/or ends at home, the driven distance is corrected by subtracting the distance
        /// between the users home address and work address.
        /// Again, this is dependend on wheter the user has overridden this value.
        ///
        /// Calculated without extra distance: If this method is used, the driven distance is
        /// still calculated, but the distance is not corrected with the distance between the
        /// users home address and work address. The distance calculated from the service is
        /// therefore used directly in the calculation of the amount to reimburse
        ///
        /// </summary>
        public DriveReport Calculate(RouteInformation drivenRoute, DriveReport report)
        {
            //Check if user has manually provided a distance between home address and work address
            var homeWorkDistance = 0.0;

            var person = _personRepo.AsQueryable().First(x => x.Id == report.PersonId);

            var homeAddress = _personService.GetHomeAddress(person);

            // Get Work and Homeaddress of employment at time of DriveDateTimestamp for report.
            AddressHistory addressHistory = null;

            try
            {
                addressHistory = _addressHistoryRepo.AsQueryable().SingleOrDefault(x => x.EmploymentId == report.EmploymentId && x.StartTimestamp <report.DriveDateTimestamp && x.EndTimestamp> report.DriveDateTimestamp);
            }
            catch (InvalidOperationException)
            {
                _logger.LogForAdmin(report.FullName + " har et overlap i sin adressehistorik");
                throw;
            }

            if (homeAddress.Type != PersonalAddressType.AlternativeHome)
            {
                if (addressHistory != null && addressHistory.HomeAddress != null)
                {
                    // If user doesn't have an alternative address set up then use the homeaddress at the time of DriveDateTimestamp
                    // If the user does have an alternative address then always use that.
                    homeAddress = addressHistory.HomeAddress;
                }
            }


            var employment = _emplrepo.AsQueryable().FirstOrDefault(x => x.Id.Equals(report.EmploymentId));

            Address workAddress = employment.OrgUnit.Address;

            if (addressHistory != null && addressHistory.WorkAddress != null)
            {
                // If an AddressHistory.WorkAddress exists, then use that.
                workAddress = addressHistory.WorkAddress;
            }


            if (employment.AlternativeWorkAddress != null)
            {
                // Overwrite workaddress if an alternative work address exists.
                workAddress = employment.AlternativeWorkAddress;
            }

            if (report.WorkAddressId != 0)
            {
                if (report.WorkAddressId != employment.AlternativeWorkAddress?.Id && report.WorkAddressId != employment.OrgUnit.Address.Id)
                {
                    // only allow work address id that is either the address of the orgunit or is the alternative address
                    throw new Exception("Invalid WorkAddressId for report");
                }
                // Overwrite workaddress if chosen on web report page
                workAddress = _addressRepo.AsQueryable().First(a => a.Id == report.WorkAddressId);
            }

            if (report.KilometerAllowance != KilometerAllowance.Read && !report.IsFromApp)
            {
                //Check if drivereport starts at users home address.
                report.StartsAtHome = areAddressesCloseToEachOther(homeAddress, report.DriveReportPoints.First());
                //Check if drivereport ends at users home address.
                report.EndsAtHome = areAddressesCloseToEachOther(homeAddress, report.DriveReportPoints.Last());
            }


            homeWorkDistance = employment.WorkDistanceOverride;

            if (homeWorkDistance <= 0)
            {
                homeWorkDistance = _route.GetRoute(DriveReportTransportType.Car, new List <Address>()
                {
                    homeAddress, workAddress
                }).Length;
            }

            //Calculate distance to subtract
            double toSubtract = 0;

            //If user indicated to use the Four Km Rule
            if (report.FourKmRule)
            {
                //Take users provided distance from home to border of municipality. If report is from app, use distance provided in report, else use distance saved on person.
                var borderDistance = report.IsFromApp ? report.HomeToBorderDistance : person.DistanceFromHomeToBorder;

                //Adjust distance based on if user starts or ends at home
                if (report.StartsAtHome)
                {
                    toSubtract += borderDistance;
                }

                if (report.EndsAtHome)
                {
                    toSubtract += borderDistance;
                }
            }
            else
            {
                //Same logic as above, but uses calculated distance between home and work
                if (report.StartsAtHome)
                {
                    toSubtract += homeWorkDistance;
                }

                if (report.EndsAtHome)
                {
                    toSubtract += homeWorkDistance;
                }
            }

            switch (report.KilometerAllowance)
            {
            case KilometerAllowance.Calculated:
            {
                // Norddjurs Kommune uses an alternative way of calculating the amount to reimburse. Instead of subtracting the distance from home to work from the driven distance,
                // either the home-to-destination or work-to-destination distance is used, which ever is shortest. This only applies to routes starting from home, in any other case
                // the standard calculation method is used.
                bool useNorddjursAltCalculation;
                bool parseSucces = bool.TryParse(_customSettings.AlternativeCalculationMethod, out useNorddjursAltCalculation);
                useNorddjursAltCalculation = parseSucces ? useNorddjursAltCalculation : false;

                // Use Norddjurs alternative reimbursemnt calculation method if configured so.
                if (useNorddjursAltCalculation)
                {
                    // The alternative calculationmethod is only used for reports starting at home.
                    if (report.StartsAtHome)
                    {
                        // Distance from home.
                        var homeDistance = report.Distance;
                        if (!report.IsFromApp)
                        {
                            // In case the report is not from app then get distance from the supplied route.
                            homeDistance = drivenRoute.Length;
                        }

                        // Get distance from work.
                        var addresses = new List <Address>();
                        addresses.Add(workAddress);
                        foreach (Address address in report.DriveReportPoints)
                        {
                            if (!(address.Latitude == homeAddress.Latitude && address.Longitude == homeAddress.Longitude))
                            {
                                addresses.Add(address);
                            }
                        }

                        var isBike = _rateTypeRepo.AsQueryable().First(x => x.TFCode.Equals(report.TFCode)).IsBike;

                        var workDistance = _route.GetRoute(isBike ? DriveReportTransportType.Bike : DriveReportTransportType.Car, addresses).Length;

                        // Compare the distance from home to the distance from work and apply the shortest of them.
                        report.Distance = homeDistance < workDistance ? homeDistance : workDistance;

                        if (!report.IsFromApp)
                        {
                            //Get RouteGeometry from driven route if the report is not from app. If it is from App then RouteGeometry is already set.
                            report.RouteGeometry = drivenRoute.GeoPoints;
                        }

                        break;
                    }
                    else
                    {
                        if (!report.IsFromApp)
                        {
                            report.Distance = drivenRoute.Length;

                            //Save RouteGeometry
                            report.RouteGeometry = drivenRoute.GeoPoints;
                        }

                        break;
                    }
                }

                if ((report.StartsAtHome || report.EndsAtHome) && !report.FourKmRule)
                {
                    report.IsExtraDistance = true;
                }

                double drivenDistance = report.Distance;

                if (!report.IsFromApp)
                {
                    // In case the report is not from app then get distance from the supplied route.
                    drivenDistance = drivenRoute.Length;
                }
                //Adjust distance based on FourKmRule and if user start and/or ends at home
                var correctDistance = drivenDistance - toSubtract;

                //Set distance to corrected
                report.Distance = correctDistance;

                if (!report.IsFromApp)
                {
                    //Get RouteGeometry from driven route if the report is not from app. If it is from App then RouteGeometry is already set.
                    report.RouteGeometry = drivenRoute.GeoPoints;
                }

                break;
            }

            case KilometerAllowance.CalculatedWithoutExtraDistance:
            {
                report.Distance = drivenRoute.Length;

                //Save RouteGeometry
                report.RouteGeometry = drivenRoute.GeoPoints;


                break;
            }

            case KilometerAllowance.Read:
            {
                if ((report.StartsAtHome || report.EndsAtHome) && !report.FourKmRule)
                {
                    report.IsExtraDistance = true;
                }

                //Take distance from report
                var manuallyProvidedDrivenDistance = report.Distance;

                report.Distance = manuallyProvidedDrivenDistance - toSubtract;

                break;
            }

            default:
            {
                throw new Exception("No calculation method provided");
            }
            }

            //Calculate the actual amount to reimburse

            if (report.Distance < 0)
            {
                report.Distance = 0;
            }

            // Multiply the distance by two if the report is a return trip
            if (report.IsRoundTrip == true)
            {
                report.Distance *= 2;
            }

            CalculateFourKmRuleForReport(report);

            SetAmountToReimburse(report);

            return(report);
        }
        /// <summary>
        /// Takes a DriveReport as input and returns it with data.
        ///
        /// FourKmRule: If a user has set the FourKmRule to be used, the distance between
        /// the users home and municipality is used in the correction of the driven distance.
        /// If the rule is not used, the distance between the users home and work address are
        /// calculated and used, provided that the user has not set a override for this value.
        ///
        /// Calculated: The driven route is calculated, and based on whether the user starts
        /// and/or ends at home, the driven distance is corrected by subtracting the distance
        /// between the users home address and work address.
        /// Again, this is dependend on wheter the user has overridden this value.
        ///
        /// Calculated without extra distance: If this method is used, the driven distance is
        /// still calculated, but the distance is not corrected with the distance between the
        /// users home address and work address. The distance calculated from the service is
        /// therefore used directly in the calculation of the amount to reimburse
        ///
        /// </summary>
        public DriveReport Calculate(RouteInformation drivenRoute, DriveReport report)
        {
            //Check if user has manually provided a distance between home address and work address
            var homeWorkDistance = 0.0;

            var person = _personRepo.AsQueryable().First(x => x.Id == report.PersonId);

            var homeAddress = _personService.GetHomeAddress(person);

            // Get Work and Homeaddress of employment at time of DriveDateTimestamp for report.
            var addressHistory = _addressHistoryRepo.AsQueryable().SingleOrDefault(x => x.EmploymentId == report.EmploymentId && x.StartTimestamp <report.DriveDateTimestamp && x.EndTimestamp> report.DriveDateTimestamp);

            if (homeAddress.Type != PersonalAddressType.AlternativeHome)
            {
                if (addressHistory != null && addressHistory.HomeAddress != null)
                {
                    // If user doesn't have an alternative address set up then use the homeaddress at the time of DriveDateTimestamp
                    // If the user does have an alternative address then always use that.
                    homeAddress = addressHistory.HomeAddress;
                }
            }


            var employment = _emplrepo.AsQueryable().FirstOrDefault(x => x.Id.Equals(report.EmploymentId));

            Address workAddress = employment.OrgUnit.Address;

            if (addressHistory != null && addressHistory.WorkAddress != null)
            {
                // If an AddressHistory.WorkAddress exists, then use that.
                workAddress = addressHistory.WorkAddress;
            }


            if (employment.AlternativeWorkAddress != null)
            {
                // Overwrite workaddress if an alternative work address exists.
                workAddress = employment.AlternativeWorkAddress;
            }

            if (report.KilometerAllowance != KilometerAllowance.Read && !report.IsFromApp)
            {
                //Check if drivereport starts at users home address.
                report.StartsAtHome = areAddressesCloseToEachOther(homeAddress, report.DriveReportPoints.First());
                //Check if drivereport ends at users home address.
                report.EndsAtHome = areAddressesCloseToEachOther(homeAddress, report.DriveReportPoints.Last());
            }


            homeWorkDistance = employment.WorkDistanceOverride;

            if (homeWorkDistance <= 0)
            {
                homeWorkDistance = _route.GetRoute(DriveReportTransportType.Car, new List <Address>()
                {
                    homeAddress, workAddress
                }).Length;
            }



            //Calculate distance to subtract
            double toSubtract = 0;

            //If user indicated to use the Four Km Rule
            if (report.FourKmRule)
            {
                //Take users provided distance from home to border of municipality
                var borderDistance = person.DistanceFromHomeToBorder;

                //Adjust distance based on if user starts or ends at home
                if (report.StartsAtHome)
                {
                    toSubtract += borderDistance;
                }

                if (report.EndsAtHome)
                {
                    toSubtract += borderDistance;
                }
            }
            else
            {
                //Same logic as above, but uses calculated distance between home and work
                if (report.StartsAtHome)
                {
                    toSubtract += homeWorkDistance;
                }

                if (report.EndsAtHome)
                {
                    toSubtract += homeWorkDistance;
                }
            }

            switch (report.KilometerAllowance)
            {
            case KilometerAllowance.Calculated:
            {
                if ((report.StartsAtHome || report.EndsAtHome) && !report.FourKmRule)
                {
                    report.IsExtraDistance = true;
                }


                double drivenDistance = report.Distance;

                if (!report.IsFromApp)
                {
                    // In case the report is not from app then get distance from the supplied route.
                    drivenDistance = drivenRoute.Length;
                }
                //Adjust distance based on FourKmRule and if user start and/or ends at home
                var correctDistance = drivenDistance - toSubtract;

                //Set distance to corrected
                report.Distance = correctDistance;

                if (!report.IsFromApp)
                {
                    //Get RouteGeometry from driven route if the report is not from app. If it is from App then RouteGeometry is already set.
                    report.RouteGeometry = drivenRoute.GeoPoints;
                }

                break;
            }

            case KilometerAllowance.CalculatedWithoutExtraDistance:
            {
                report.Distance = drivenRoute.Length;

                //Save RouteGeometry
                report.RouteGeometry = drivenRoute.GeoPoints;


                break;
            }

            case KilometerAllowance.Read:
            {
                if ((report.StartsAtHome || report.EndsAtHome) && !report.FourKmRule)
                {
                    report.IsExtraDistance = true;
                }

                //Take distance from report
                var manuallyProvidedDrivenDistance = report.Distance;

                report.Distance = manuallyProvidedDrivenDistance - toSubtract;

                break;
            }

            default:
            {
                throw new Exception("No calculation method provided");
            }
            }

            //Calculate the actual amount to reimburse

            if (report.Distance < 0)
            {
                report.Distance = 0;
            }

            // Multiply the distance by two if the report is a return trip
            if (report.IsRoundTrip == true)
            {
                report.Distance *= 2;
            }

            if (report.FourKmRule)
            {
                report.Distance -= FourKmAdjustment;
            }

            SetAmountToReimburse(report);

            return(report);
        }
 public IQueryable <DataProcessingRegistration> GetDataProcessingRegistrationsFromOrganization(int organizationId)
 {
     return(_repository.AsQueryable().ByOrganizationId(organizationId));
 }
示例#29
0
        public IQueryable <Organization> ResolveOrganizationsWhereAuthenticatedUserHasRightsHolderAccess()
        {
            var organizationIds = _userContext.GetOrganizationIdsWhereHasRole(OrganizationRole.RightsHolderAccess).ToList();

            return(_organizationRepository.AsQueryable().ByIds(organizationIds));
        }
示例#30
0
        public virtual List <TEntityDto> Get()
        {
            var resultList = _genericRepo.AsQueryable().ToList();

            return(_mapper.Map <List <TEntityDto> >(resultList));
        }