public ActionResult Health()
        {
            // a simple health endpoint check that also fails if there is no connection to database
            var count = orgUnitRepo.AsNoTracking().Count();

            return(Ok());
        }
Exemple #2
0
        public void UpdateReportsAffectedBySubstitute(Substitute sub)
        {
            if (sub.LeaderId == sub.PersonId)
            {
                // Substitute is a substitute - Not a Personal Approver.
                // Select reports to be updated based on OrgUnits
                var orgIds = new List <int>();
                orgIds.Add(sub.OrgUnitId);
                orgIds.AddRange(_orgService.GetChildOrgsWithoutLeader(sub.OrgUnitId).Select(x => x.Id));
                var idsOfLeadersOfImmediateChildOrgs = _orgService.GetIdsOfLeadersInImmediateChildOrgs(sub.OrgUnitId);

                var reports = _reportRepo.AsNoTracking().Where(rep => orgIds.Contains(rep.Employment.OrgUnitId) || idsOfLeadersOfImmediateChildOrgs.Contains(rep.PersonId)).ToList();
                foreach (var report in reports)
                {
                    if (report.ReportType != sub.Type)
                    {
                        continue;
                    }
                    report.ResponsibleLeaderId = _reportService.GetResponsibleLeaderForReport(report).Id;
                    _reportRepo.Patch(report);
                }
                _reportRepo.Save();
            }
            else
            {
                // Substitute is a personal approver
                // Select reports to be updated based on PersonId on report
                var reports2 =
                    _reportRepo.AsNoTracking().Where(rep => rep.PersonId == sub.PersonId).ToList();
                foreach (var report in reports2.AsEnumerable())
                {
                    if (report.ReportType != sub.Type)
                    {
                        continue;
                    }
                    report.ResponsibleLeaderId = _reportService.GetResponsibleLeaderForReport(report).Id;
                    _reportRepo.Patch(report);
                }
                _reportRepo.Save();
            }
        }
        /// <summary>
        /// Gets the email address of all leaders that have pending reports to be approved.
        /// </summary>
        /// <returns>List of email addresses.</returns>
        public IEnumerable <Report> GetLeadersWithPendingReportsMails()
        {
            var reports = _reportRepo.AsNoTracking().Where(r => r.Status == ReportStatus.Pending).ToList();

            var reportsWithNoLeader = reports.Where(report => report.ResponsibleLeader == null);

            foreach (var report in reportsWithNoLeader)
            {
                _logger.Log(report.Person.FullName + "s indberetning har ingen leder. Indberetningen kan derfor ikke godkendes.", "web", 2);
            }

            return(reports.Where(report => report.ResponsibleLeaderId != null && !string.IsNullOrEmpty(report.ResponsibleLeader.Mail) && report.ResponsibleLeader.RecieveMail));
        }
        public IHttpActionResult LeadersPeople(int type = 1)
        {
            var subsituteType    = (ReportType)type;
            var currentTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            var substitutes       = _substituteRepo.AsQueryable().Where(x => x.PersonId == x.LeaderId && x.SubId == CurrentUser.Id && x.EndDateTimestamp >= currentTimestamp && x.Type == subsituteType).Distinct().ToList();
            var personalApproving = _substituteRepo.AsQueryable().Where(x => x.PersonId != x.LeaderId && x.SubId == CurrentUser.Id && x.EndDateTimestamp >= currentTimestamp && x.Type == subsituteType).Select(x => x.Person).ToList();
            var orgs = _orgService.GetWhereUserIsResponsible(CurrentUser.Id).Where(x => subsituteType == ReportType.Vacation && x.HasAccessToVacation).ToList();

            foreach (var sub in substitutes)
            {
                orgs.AddRange(_orgService.GetWhereUserIsResponsible(sub.PersonId));
            }

            var people = _reportRepo.AsNoTracking().Where(x => x.ResponsibleLeaderId == CurrentUser.Id && x.Status == ReportStatus.Pending).Select(x => x.Person).Distinct().ToList();

            foreach (var org in orgs)
            {
                foreach (var person in org.Employments.Where(x => (x.EndDateTimestamp == 0 || x.EndDateTimestamp >= currentTimestamp) && people.All(y => y.Id != x.PersonId) && x.PersonId != CurrentUser.Id).Select(x => x.Person))
                {
                    people.Add(person);
                }

                var leadersIds = _orgService.GetIdsOfLeadersInImmediateChildOrgs(org.Id);

                foreach (var leaderId in leadersIds)
                {
                    var leader = Repo.AsQueryable().FirstOrDefault(x => x.Id == leaderId);
                    if (leader != null && !people.Contains(leader))
                    {
                        people.Add(leader);
                    }
                }
            }

            foreach (var subbing in personalApproving)
            {
                if (!people.Contains(subbing))
                {
                    people.Add(subbing);
                }
            }

            people.RemoveAll(x => x.Employments.All(y => y.EndDateTimestamp <= currentTimestamp && y.EndDateTimestamp != 0));

            return(Ok(people.GroupBy(p => p.Id).Select(g => g.First()).AsQueryable()));
        }
        /// <summary>
        /// Updates ResponsibleLeader on all reports that had a substitute which expired yesterday or became active today.
        /// </summary>
        public void UpdateLeadersOnExpiredOrActivatedSubstitutes()
        {
            // TODO Find something more generic for updating drive and vacation reports.
            var yesterdayTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1).AddDays(1))).TotalSeconds;
            var currentTimestamp   = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            var endOfDayStamp   = _subService.GetEndOfDayTimestamp(yesterdayTimestamp);
            var startOfDayStamp = _subService.GetStartOfDayTimestamp(currentTimestamp);

            var affectedSubstitutes = _subRepo.AsNoTracking().Where(s => (s.EndDateTimestamp == endOfDayStamp) || (s.StartDateTimestamp == startOfDayStamp)).ToList();

            Console.WriteLine(affectedSubstitutes.Count() + " substitutes have expired or become active. Updating affected reports.");
            foreach (var sub in affectedSubstitutes)
            {
                _subService.UpdateReportsAffectedBySubstitute(sub);
            }
        }
        private void UpdateOrgUnits(IEnumerable <APIOrgUnit> apiOrgUnits)
        {
            // Handle inserts
            var toBeInserted = apiOrgUnits.Where(s => !_orgUnitRepo.AsNoTracking().Select(d => d.OrgId.ToString()).Contains(s.Id)).ToList();
            var toBeUpdated  = _orgUnitRepo.AsQueryableLazy().Where(d => apiOrgUnits.Select(s => s.Id).Contains(d.OrgId.ToString())).ToList();

            var insertTotal   = toBeInserted.Count();
            var insertCounter = 0;

            _logger.LogDebug("Orgunits to be inserted: {0}", insertTotal);
            foreach (var apiOrgUnit in toBeInserted)
            {
                if (++insertCounter % 10 == 0)
                {
                    _logger.LogDebug("Inserting orgunit {0} of {1}", insertCounter, insertTotal);
                }
                var orgToInsert = new OrgUnit();
                orgToInsert.HasAccessToFourKmRule     = false;
                orgToInsert.HasAccessToVacation       = false;
                orgToInsert.DefaultKilometerAllowance = KilometerAllowance.Calculated;
                mapAPIOrgUnit(apiOrgUnit, ref orgToInsert);
                if (orgToInsert.Address == null)
                {
                    _logger.LogWarning("Skipping orgunit insert because it has no address. OrgId: {0} Name: {1}", orgToInsert.OrgId, orgToInsert.LongDescription);
                    continue;
                }
                _orgUnitRepo.Insert(orgToInsert);
                // need to save each time to generate db id used in the next parent references
                _orgUnitRepo.Save();
            }

            // Handle updates
            var updateTotal   = toBeUpdated.Count();
            var updateCounter = 0;

            _logger.LogDebug("Orgunits to be updated: {0}", updateTotal);
            foreach (var orgUnit in toBeUpdated)
            {
                try
                {
                    if (++updateCounter % 10 == 0)
                    {
                        _logger.LogDebug("Updating orgunit {0} of {1}", updateCounter, updateTotal);
                    }
                    var apiOrgUnit  = apiOrgUnits.Where(s => s.Id == orgUnit.OrgId.ToString()).First();
                    var orgToUpdate = orgUnit;
                    mapAPIOrgUnit(apiOrgUnit, ref orgToUpdate);
                    if (orgToUpdate.Address == null)
                    {
                        _logger.LogWarning("Skipping orgunit update because it has no address. OrgId: {0} Name: {1}", orgToUpdate.OrgId, orgToUpdate.LongDescription);
                        continue;
                    }
                    _orgUnitRepo.Update(orgToUpdate);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Failed to update Orgunit. OrgId: {0} Name: {1}", orgUnit.OrgId, orgUnit.LongDescription);
                }
            }
            _orgUnitRepo.DetectChanges();
            _orgUnitRepo.Save();
        }
        private void UpdatePersons(IEnumerable <APIPerson> apiPersons)
        {
            // Handle inserts
            var toBeInserted = apiPersons.Where(s => !_personRepo.AsNoTracking().Select(d => d.CprNumber).Contains(s.CPR));
            var toBeUpdated  = _personRepo.AsQueryableLazy().Where(d => apiPersons.Select(s => s.CPR).Contains(d.CprNumber)).ToList();
            var toBeDeleted  = _personRepo.AsQueryableLazy().Where(p => p.IsActive && !apiPersons.Select(ap => ap.CPR).Contains(p.CprNumber)).ToList();

            var insertTotal   = toBeInserted.Count();
            var insertCounter = 0;

            _logger.LogDebug("Persons to be inserted: {0}", insertTotal);
            foreach (var apiPerson in toBeInserted)
            {
                if (++insertCounter % 10 == 0)
                {
                    _logger.LogDebug("Inserting person {0} of {1}", insertCounter, insertTotal);
                }
                var personToInsert = new Person();
                personToInsert.IsAdmin           = false;
                personToInsert.RecieveMail       = true;
                personToInsert.Employments       = new List <Employment>();
                personToInsert.PersonalAddresses = new List <PersonalAddress>();
                mapAPIPerson(apiPerson, ref personToInsert);
                _personRepo.Insert(personToInsert);
                _personRepo.Save();
                //UpdateHomeAddress(apiPerson, ref personToInsert);
                UpdateVacationBalances(apiPerson, ref personToInsert);
            }
            _personRepo.Save();

            // Handle updates
            var updateTotal   = toBeUpdated.Count();
            var updateCounter = 0;

            _logger.LogDebug("Persons to be updated: {0}", updateTotal);
            foreach (var person in toBeUpdated)
            {
                try
                {
                    if (++updateCounter % 10 == 0)
                    {
                        _logger.LogDebug("Updating person {0} of {1}", updateCounter, updateTotal);
                    }
                    var apiPerson      = apiPersons.Where(s => s.CPR == person.CprNumber).First();
                    var personToUpdate = person;
                    mapAPIPerson(apiPerson, ref personToUpdate);
                    //UpdateHomeAddress(apiPerson, ref personToUpdate);
                    UpdateVacationBalances(apiPerson, ref personToUpdate);
                    _personRepo.Update(personToUpdate);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Failed to update Person. Name: {0}", person.FullName);
                }
            }

            // Handle deletes
            var deleteTotal   = toBeDeleted.Count();
            var deleteCounter = 0;

            _logger.LogDebug("Persons to be inactivated: {0}", deleteTotal);
            foreach (var personToBeDeleted in toBeDeleted)
            {
                if (++deleteCounter % 10 == 0)
                {
                    _logger.LogDebug("Inactivating person {0} of {1}", deleteCounter, deleteTotal);
                }
                personToBeDeleted.IsActive = false;
                foreach (var employment in personToBeDeleted.Employments)
                {
                    if (employment.EndDateTimestamp == 0 || employment.EndDateTimestamp > GetUnixTime(DateTime.Now.Date))
                    {
                        employment.EndDateTimestamp = GetUnixTime(DateTime.Now.Date);
                    }
                }
                _personRepo.Update(personToBeDeleted);
            }
            _personRepo.DetectChanges();
            _personRepo.Save();
        }