Exemplo n.º 1
0
        public List <ShiftDay> GetShiftDaysForDay(DateTime currentTime, int departmentId)
        {
            var shiftDays = new List <ShiftDay>();

            var shifts = (from s in _shiftsRepository.GetAll()
                          where s.DepartmentId == departmentId
                          select s).ToList();

            foreach (var shift in shifts)
            {
                var localizedDate = TimeConverterHelper.TimeConverter(currentTime, shift.Department);

                var shiftStart = shift.StartTime;

                if (String.IsNullOrWhiteSpace(shiftStart))
                {
                    shiftStart = "12:00 AM";
                }

                var startTime = DateTimeHelpers.ConvertStringTime(shiftStart, localizedDate, shift.Department.Use24HourTime.GetValueOrDefault());

                var days = from sd in shift.Days
                           let shiftDayTime = DateTimeHelpers.ConvertStringTime(shiftStart, sd.Day, shift.Department.Use24HourTime.GetValueOrDefault())
                                              let nextDayShiftTime = localizedDate
                                                                     where shiftDayTime == nextDayShiftTime.Within(TimeSpan.FromHours(12))
                                                                     select sd;

                shiftDays.AddRange(days);
            }

            return(shiftDays);
        }
Exemplo n.º 2
0
        public async Task <List <ScheduledTask> > GetUpcomingScheduledTasksByUserIdTaskTypeAsync(string userId, TaskTypes?type)
        {
            var upcomingTasks = new List <ScheduledTask>();
            var tasks         = new List <ScheduledTask>();

            if (type == null)
            {
                tasks = (from st in await GetAllScheduledTasksAsync()
                         where st.Active == true && st.UserId == userId
                         select st).ToList();
            }
            else
            {
                tasks = (from st in await GetAllScheduledTasksAsync()
                         where st.Active == true && st.UserId == userId && st.TaskType == (int)type.Value
                         select st).ToList();
            }

            var department = await _departmentsService.GetDepartmentByUserIdAsync(userId);

            var runDate = TimeConverterHelper.TimeConverter(DateTime.UtcNow, department);

            foreach (var scheduledTask in tasks)
            {
                var log = await _scheduledTaskLogRepository.GetLogForTaskAndDateAsync(scheduledTask.ScheduledTaskId, DateTime.UtcNow);

                var runTime = scheduledTask.WhenShouldJobBeRun(runDate);

                if (runTime.HasValue)
                {
                    if (scheduledTask.AddedOn.HasValue)
                    {
                        if (scheduledTask.AddedOn.Value < DateTime.UtcNow)
                        {
                            if (runTime.Value > runDate && log == null)
                            {
                                upcomingTasks.Add(scheduledTask);
                            }
                            else if (runTime.Value < runDate && log == null)
                            {
                                upcomingTasks.Add(scheduledTask);
                            }
                        }
                    }
                    else
                    {
                        if (runTime.Value > runDate && log == null)
                        {
                            upcomingTasks.Add(scheduledTask);
                        }
                        else if (runTime.Value < runDate && log == null)
                        {
                            upcomingTasks.Add(scheduledTask);
                        }
                    }
                }
            }

            return(upcomingTasks);
        }
Exemplo n.º 3
0
        public async Task ProcessAsync(Commands.StaffingScheduleCommand command, IQuidjiboProgress progress, CancellationToken cancellationToken)
        {
            progress.Report(1, $"Starting the {Name} Task");

            await Task.Factory.StartNew(() =>
            {
                var _departmentsService    = Bootstrapper.GetKernel().Resolve <IDepartmentsService>();
                var _scheduledTasksService = Bootstrapper.GetKernel().Resolve <IScheduledTasksService>();
                var logic = new StaffingScheduleLogic();

                var allItems = _scheduledTasksService.GetAllUpcomingStaffingScheduledTaks();

                if (allItems != null && allItems.Any())
                {
                    // Filter only the past items and ones that are 5 minutes 30 seconds in the future
                    var items = (from st in allItems
                                 let department = _departmentsService.GetDepartmentByUserId(st.UserId)
                                                  let runTime = st.WhenShouldJobBeRun(TimeConverterHelper.TimeConverter(DateTime.UtcNow, department))
                                                                where
                                                                runTime.HasValue && runTime.Value >= TimeConverterHelper.TimeConverter(DateTime.UtcNow, department) &&
                                                                runTime.Value <= TimeConverterHelper.TimeConverter(DateTime.UtcNow, department).AddMinutes(5).AddSeconds(30)
                                                                select new
                    {
                        ScheduledTask = st,
                        Department = department
                    }).ToList();

                    if (items != null && items.Any())
                    {
                        _logger.LogInformation("StaffingSchedule::Staffing Levels to Change: " + items.Count());

                        foreach (var i in items)
                        {
                            var qi           = new StaffingScheduleQueueItem();
                            qi.ScheduledTask = i.ScheduledTask;
                            qi.Department    = i.Department;

                            _logger.LogInformation("StaffingSchedule::Processing Staffing Schedule:" + qi.ScheduledTask.ScheduledTaskId);

                            var result = logic.Process(qi);

                            if (result.Item1)
                            {
                                _logger.LogInformation($"StaffingSchedule::Processed Staffing Schedule {qi.ScheduledTask.ScheduledTaskId} successfully.");
                            }
                            else
                            {
                                _logger.LogInformation($"StaffingSchedule::Failed to Process staffing schedule {qi.ScheduledTask.ScheduledTaskId} error {result.Item2}");
                            }
                        }
                    }
                }
            }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);



            progress.Report(100, $"Finishing the {Name} Task");
        }
Exemplo n.º 4
0
        public List <Shift> GetShiftsStartingNextDay(DateTime currentTime)
        {
            var upcomingShifts = new List <Shift>();

            var shifts = _shiftsRepository.GetAllShiftsAndDays();

            foreach (var shift in shifts)
            {
                try
                {
                    var localizedDate = TimeConverterHelper.TimeConverter(currentTime, shift.Department);

                    var shiftStart = shift.StartTime;

                    if (String.IsNullOrWhiteSpace(shiftStart))
                    {
                        shiftStart = "12:00 AM";
                    }

                    var startTime = DateTimeHelpers.ConvertStringTime(shiftStart, localizedDate, shift.Department.Use24HourTime.GetValueOrDefault());

                    var shiftDays = from sd in shift.Days
                                    let shiftDayTime = DateTimeHelpers.ConvertStringTime(shiftStart, sd.Day, shift.Department.Use24HourTime.GetValueOrDefault())
                                                       let nextDayShiftTime = localizedDate.AddDays(1)
                                                                              where shiftDayTime == nextDayShiftTime.Within(TimeSpan.FromMinutes(15))
                                                                              select sd;

                    //List<ShiftDay> shiftDays = new List<ShiftDay>();
                    //foreach (var sd in shift.Days)
                    //{
                    //	var shiftDayTime = DateTimeHelpers.ConvertStringTime(shiftStart, sd.Day, shift.Department.Use24HourTime.GetValueOrDefault());
                    //	var nextDayShiftTime = localizedDate.AddDays(1);

                    //	if (shiftDayTime == nextDayShiftTime.Within(TimeSpan.FromMinutes(15)))
                    //		shiftDays.Add(sd);
                    //}

                    if (shiftDays.Any())
                    {
                        var previousShift = from sd in shift.Days
                                            where sd.Day.ToShortDateString() == startTime.ToShortDateString()
                                            select sd;

                        if (!previousShift.Any())
                        {
                            upcomingShifts.Add(shift);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex, $"DepartmentId:{shift.DepartmentId}");
                }
            }

            return(upcomingShifts);
        }
Exemplo n.º 5
0
        public void PopulateQueue()
        {
            Logging.LogTrace("StaffingJob: Entering PopulateQueue");

            if (!_isLocked)
            {
                _isLocked              = true;
                _departmentsService    = Bootstrapper.GetKernel().Resolve <IDepartmentsService>();
                _scheduledTasksService = Bootstrapper.GetKernel().Resolve <IScheduledTasksService>();

                var t1 = new Task(() =>
                {
                    try
                    {
                        var allItems = _scheduledTasksService.GetUpcomingScheduledTaks();
                        Logging.LogTrace(string.Format("StaffingJob: Analyzing {0} schedule tasks", allItems.Count));

                        // Filter only the past items and ones that are 5 minutes 30 seconds in the future
                        var items = from st in allItems
                                    let department = _departmentsService.GetDepartmentByUserId(st.UserId)
                                                     let runTime = st.WhenShouldJobBeRun(TimeConverterHelper.TimeConverter(DateTime.UtcNow, department))
                                                                   where
                                                                   (st.TaskType == (int)TaskTypes.DepartmentStaffingReset || st.TaskType == (int)TaskTypes.UserStaffingLevel) &&
                                                                   runTime.HasValue && runTime.Value >= TimeConverterHelper.TimeConverter(DateTime.UtcNow, department) &&
                                                                   runTime.Value <= TimeConverterHelper.TimeConverter(DateTime.UtcNow, department).AddMinutes(5).AddSeconds(30)
                                                                   select new
                        {
                            ScheduledTask = st,
                            Department    = department
                        };

                        foreach (var i in items)
                        {
                            var qi           = new StaffingScheduleQueueItem();
                            qi.ScheduledTask = i.ScheduledTask;
                            qi.Department    = i.Department;

                            _queue.Enqueue(qi);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.LogException(ex);
                    }
                    finally
                    {
                        _isLocked = false;
                        _cleared  = false;

                        _departmentsService    = null;
                        _scheduledTasksService = null;
                    }
                }, TaskCreationOptions.LongRunning);

                t1.Start();
            }
        }
Exemplo n.º 6
0
        public List <Training> GetTrainingsToNotify(DateTime currentTime)
        {
            var trainingsToNotify = new List <Training>();

            var trainings = _trainingRepository.GetAllTrainings();

            if (trainings != null && trainings.Any())
            {
                foreach (var training in trainings)
                {
                    if (!training.Notified.HasValue)
                    {
                        trainingsToNotify.Add(training);
                    }
                    else
                    {
                        Department d;
                        if (training.Department != null)
                        {
                            d = training.Department;
                        }
                        else
                        {
                            d = _departmentService.GetDepartmentById(training.DepartmentId);
                        }

                        if (d != null)
                        {
                            var localizedDate = TimeConverterHelper.TimeConverter(currentTime, d);
                            var setToNotify   = new DateTime(localizedDate.Year, localizedDate.Month, localizedDate.Day, 10, 0, 0, 0);

                            if (localizedDate == setToNotify.Within(TimeSpan.FromMinutes(13)) && training.ToBeCompletedBy.HasValue)
                            {
                                if (localizedDate.AddDays(1).ToShortDateString() == training.ToBeCompletedBy.Value.ToShortDateString())
                                {
                                    trainingsToNotify.Add(training);
                                }
                            }
                        }
                    }
                }
            }

            return(trainingsToNotify);
        }
Exemplo n.º 7
0
        public List <Shift> GetShiftsStartingNextDay(DateTime currentTime)
        {
            var upcomingShifts = new List <Shift>();

            var shifts = (from s in _shiftsRepository.GetAll()
                          select s).ToList();

            foreach (var shift in shifts)
            {
                var localizedDate = TimeConverterHelper.TimeConverter(currentTime, shift.Department);

                var shiftStart = shift.StartTime;

                if (String.IsNullOrWhiteSpace(shiftStart))
                {
                    shiftStart = "12:00 AM";
                }

                var startTime = DateTimeHelpers.ConvertStringTime(shiftStart, localizedDate, shift.Department.Use24HourTime.GetValueOrDefault());

                var shiftDays = from sd in shift.Days
                                let shiftDayTime = DateTimeHelpers.ConvertStringTime(shiftStart, sd.Day, shift.Department.Use24HourTime.GetValueOrDefault())
                                                   let nextDayShiftTime = localizedDate.AddDays(1)
                                                                          where shiftDayTime == nextDayShiftTime.Within(TimeSpan.FromMinutes(15))
                                                                          select sd;

                if (shiftDays.Any())
                {
                    var previousShift = from sd in shift.Days
                                        where sd.Day.ToShortDateString() == startTime.ToShortDateString()
                                        select sd;

                    if (!previousShift.Any())
                    {
                        upcomingShifts.Add(shift);
                    }
                }
            }

            return(upcomingShifts);
        }
        /// <summary>
        /// Gets the current staffing level (state) for the user
        /// </summary>
        /// <returns>StateResult object with the users current staffing level</returns>
        public List <StaffingScheduleResult> GetStaffingSchedules()
        {
            var results = new List <StaffingScheduleResult>();

            var department = _departmentsService.GetDepartmentById(DepartmentId, false);
            var tasks      = _scheduledTasksService.GetScheduledStaffingTasksForUser(UserId);

            foreach (var task in tasks)
            {
                var st = new StaffingScheduleResult();
                st.Id = task.ScheduledTaskId;
                if (task.ScheduleType == (int)ScheduleTypes.Weekly)
                {
                    st.Typ = "Weekly";
                }
                else
                {
                    st.Typ = "Date";
                }

                if (task.SpecifcDate.HasValue)
                {
                    st.Spc = TimeConverterHelper.TimeConverter(task.SpecifcDate.Value, department);
                }

                st.Act = task.Active;

                var days = new StringBuilder();

                if (task.Monday)
                {
                    days.Append("M");
                }

                if (task.Tuesday)
                {
                    days.Append("T");
                }

                if (task.Wednesday)
                {
                    days.Append("W");
                }

                if (task.Thursday)
                {
                    days.Append("Th");
                }

                if (task.Friday)
                {
                    days.Append("F");
                }

                if (task.Saturday)
                {
                    days.Append("S");
                }

                if (task.Sunday)
                {
                    days.Append("Su");
                }

                days.Append(" @ " + task.Time);

                if (task.ScheduleType == (int)ScheduleTypes.Weekly)
                {
                    st.Dow = days.ToString();
                }

                st.Data = task.Data;

                results.Add(st);
            }

            return(results);
        }
Exemplo n.º 9
0
        public void PopulateQueue()
        {
            if (!_isLocked)
            {
                _isLocked = true;

                _departmentsService    = Bootstrapper.GetKernel().Resolve <IDepartmentsService>();
                _scheduledTasksService = Bootstrapper.GetKernel().Resolve <IScheduledTasksService>();
                _usersService          = Bootstrapper.GetKernel().Resolve <IUsersService>();

                Task t1 = new Task(() =>
                {
                    try
                    {
                        var allItems = _scheduledTasksService.GetUpcomingScheduledTaks();

                        // Filter only the past items and ones that are 5 minutes 30 seconds in the future
                        var items = from st in allItems
                                    let department                         = _departmentsService.GetDepartmentByUserId(st.UserId)
                                                                 let email = _usersService.GetMembershipByUserId(st.UserId).Email
                                                                             let runTime = st.WhenShouldJobBeRun(TimeConverterHelper.TimeConverter(DateTime.UtcNow, department))
                                                                                           where
                                                                                           st.TaskType == (int)TaskTypes.ReportDelivery && runTime.HasValue &&
                                                                                           runTime.Value >= TimeConverterHelper.TimeConverter(DateTime.UtcNow, department) &&
                                                                                           runTime.Value <= TimeConverterHelper.TimeConverter(DateTime.UtcNow, department).AddMinutes(5).AddSeconds(30)
                                                                                           select new
                        {
                            ScheduledTask = st,
                            Department    = department,
                            Email         = email
                        };

                        foreach (var i in items)
                        {
                            var qi           = new ReportDeliveryQueueItem();
                            qi.ScheduledTask = i.ScheduledTask;
                            qi.Department    = i.Department;
                            qi.Email         = i.Email;

                            _queue.Enqueue(qi);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.LogException(ex);
                    }
                    finally
                    {
                        _isLocked = false;
                        _cleared  = false;

                        _departmentsService    = null;
                        _scheduledTasksService = null;
                        _usersService          = null;
                    }
                });

                t1.Start();
            }
        }
Exemplo n.º 10
0
            public static PersonnelViewModel Create(string name, ActionLog actionLog, UserState userState, Department department, DepartmentGroup respondingToDepartment, DepartmentGroup group, List <PersonnelRole> roles, string callNumber)
            {
                DateTime updateDate = TimeConverterHelper.TimeConverter(DateTime.UtcNow, department);

                string status          = "";
                string statusCss       = "";
                string state           = "";
                string stateCss        = "";
                string stateStyle      = "";
                string statusStyle     = "";
                double?latitude        = null;
                double?longitude       = null;
                int    statusValue     = 0;
                double eta             = 0;
                int    destinationType = 0;

                if (userState != null)
                {
                    if (userState.State <= 25)
                    {
                        if (userState.State == 0)
                        {
                            state    = "Available";
                            stateCss = "label-default";
                        }
                        else if (userState.State == 1)
                        {
                            state    = "Delayed";
                            stateCss = "label-warning";
                        }
                        else if (userState.State == 2)
                        {
                            state    = "Unavailable";
                            stateCss = "label-danger";
                        }
                        else if (userState.State == 3)
                        {
                            state    = "Committed";
                            stateCss = "label-info";
                        }
                        else if (userState.State == 4)
                        {
                            state    = "On Shift";
                            stateCss = "label-info";
                        }
                    }
                    else
                    {
                        var customState = CustomStatesHelper.GetCustomState(department.DepartmentId, userState.State);

                        if (customState != null)
                        {
                            state      = customState.ButtonText;
                            stateCss   = "label-default";
                            stateStyle = string.Format("color:{0};background-color:{1};", customState.TextColor, customState.ButtonColor);
                        }
                        else
                        {
                            state    = "Unknown";
                            stateCss = "label-default";
                        }
                    }
                }
                else
                {
                    state    = "Available";
                    stateCss = "label-default";
                }


                if (actionLog == null)
                {
                    status    = "Standing By";
                    statusCss = "label-default";
                }
                else
                {
                    updateDate      = TimeConverterHelper.TimeConverter(actionLog.Timestamp, department);
                    eta             = actionLog.Eta;
                    destinationType = actionLog.DestinationType.GetValueOrDefault();

                    statusValue = actionLog.ActionTypeId;

                    if (actionLog.ActionTypeId <= 25)
                    {
                        if (actionLog.ActionTypeId == 1)
                        {
                            status    = "Not Responding";
                            statusCss = "label-danger";
                        }
                        else if (actionLog.ActionTypeId == 2)
                        {
                            status    = "Responding";
                            statusCss = "label-success";

                            if (!String.IsNullOrWhiteSpace(actionLog.GeoLocationData))
                            {
                                var cords = actionLog.GetCoordinates();

                                latitude  = cords.Latitude;
                                longitude = cords.Longitude;
                            }
                        }
                        else if (actionLog.ActionTypeId == 0)
                        {
                            status    = "Standing By";
                            statusCss = "label-default";
                        }
                        else if (actionLog.ActionTypeId == 3)
                        {
                            status    = "On Scene";
                            statusCss = "label-inverse";
                        }
                        else if (actionLog.ActionTypeId == 4)
                        {
                            if (respondingToDepartment == null)
                            {
                                status = "Available Station";
                            }
                            else
                            {
                                status = string.Format("Available at {0}", respondingToDepartment.Name);
                            }

                            statusCss = "label-default";
                        }
                        else if (actionLog.ActionTypeId == 5)
                        {
                            statusCss = "label-success";

                            if (!String.IsNullOrWhiteSpace(actionLog.GeoLocationData))
                            {
                                var cords = actionLog.GetCoordinates();

                                latitude  = cords.Latitude;
                                longitude = cords.Longitude;
                            }

                            if (respondingToDepartment == null)
                            {
                                status = "Responding to Station";
                            }
                            else
                            {
                                status = string.Format("Responding to {0}", respondingToDepartment.Name);
                            }
                        }
                        else if (actionLog.ActionTypeId == 6)
                        {
                            statusCss = "label-success";

                            if (!String.IsNullOrWhiteSpace(actionLog.GeoLocationData))
                            {
                                var cords = actionLog.GetCoordinates();

                                latitude  = cords.Latitude;
                                longitude = cords.Longitude;
                            }

                            if (!actionLog.DestinationId.HasValue)
                            {
                                status = "Responding to Call";
                            }
                            else
                            {
                                if (!String.IsNullOrWhiteSpace(callNumber))
                                {
                                    status = string.Format("Responding to Call {0}", callNumber);
                                }
                                else
                                {
                                    status = string.Format("Responding to Call {0}", actionLog.DestinationId);
                                }
                            }
                        }
                    }
                    else
                    {
                        var customStatus = CustomStatesHelper.GetCustomState(department.DepartmentId, actionLog.ActionTypeId);

                        if (customStatus != null)
                        {
                            status      = customStatus.ButtonText;
                            statusCss   = "label-default";
                            statusStyle = string.Format("color:{0};background-color:{1};", customStatus.TextColor, customStatus.ButtonColor);

                            if (!String.IsNullOrWhiteSpace(actionLog.GeoLocationData))
                            {
                                var cords = actionLog.GetCoordinates();

                                latitude  = cords.Latitude;
                                longitude = cords.Longitude;
                            }
                        }
                        else
                        {
                            status    = "Unknown";
                            statusCss = "label-default";
                        }
                    }
                }

                string groupName = "";
                int    groupId   = 0;

                if (group != null)
                {
                    groupName = group.Name;
                    groupId   = group.DepartmentGroupId;
                }

                var newRoles = new StringBuilder();

                foreach (var role in roles)
                {
                    if (newRoles.Length > 0)
                    {
                        newRoles.Append(", " + role.Name);
                    }
                    else
                    {
                        newRoles.Append(role.Name);
                    }
                }

                return(new PersonnelViewModel
                {
                    Name = name,
                    Status = status,
                    StatusCss = statusCss,
                    State = state,
                    StateCss = stateCss,
                    UpdatedDate = updateDate,
                    Group = groupName,
                    Roles = newRoles.ToString(),
                    GroupId = groupId,
                    StateStyle = stateStyle,
                    StatusStyle = statusStyle,
                    Latitude = latitude,
                    Longitude = longitude,
                    StatusValue = statusValue,
                    Eta = eta,
                    DestinationType = destinationType
                });
            }
Exemplo n.º 11
0
        public async Task ProcessAsync(ReportDeliveryTaskCommand command, IQuidjiboProgress progress, CancellationToken cancellationToken)
        {
            progress.Report(1, $"Starting the {Name} Task");

            await Task.Factory.StartNew(() =>
            {
                var _departmentsService    = Bootstrapper.GetKernel().Resolve <IDepartmentsService>();
                var _scheduledTasksService = Bootstrapper.GetKernel().Resolve <IScheduledTasksService>();
                var _usersService          = Bootstrapper.GetKernel().Resolve <IUsersService>();
                var logic = new ReportDeliveryLogic();

                var allItems = _scheduledTasksService.GetUpcomingScheduledTaks();

                if (allItems != null)
                {
                    // Filter only the past items and ones that are 5 minutes 30 seconds in the future
                    var items = from st in allItems
                                let department                         = _departmentsService.GetDepartmentByUserId(st.UserId)
                                                             let email = _usersService.GetMembershipByUserId(st.UserId).Email
                                                                         let runTime = st.WhenShouldJobBeRun(TimeConverterHelper.TimeConverter(DateTime.UtcNow, department))
                                                                                       where
                                                                                       st.TaskType == (int)TaskTypes.ReportDelivery && runTime.HasValue &&
                                                                                       runTime.Value >= TimeConverterHelper.TimeConverter(DateTime.UtcNow, department) &&
                                                                                       runTime.Value <= TimeConverterHelper.TimeConverter(DateTime.UtcNow, department).AddMinutes(5).AddSeconds(30)
                                                                                       select new
                    {
                        ScheduledTask = st,
                        Department    = department,
                        Email         = email
                    };

                    if (items != null && items.Count() > 0)
                    {
                        _logger.LogInformation("ReportDelivery::Reports to Deliver: " + items.Count());

                        foreach (var i in items)
                        {
                            var qi           = new ReportDeliveryQueueItem();
                            qi.ScheduledTask = i.ScheduledTask;
                            qi.Department    = i.Department;
                            qi.Email         = i.Email;

                            _logger.LogInformation("ReportDelivery::Processing Report:" + qi.ScheduledTask.ScheduledTaskId);

                            var result = logic.Process(qi);

                            if (result.Item1)
                            {
                                _logger.LogInformation($"ReportDelivery::Processed Report {qi.ScheduledTask.ScheduledTaskId} successfully.");
                            }
                            else
                            {
                                _logger.LogInformation($"ReportDelivery::Failed to Process report {qi.ScheduledTask.ScheduledTaskId} error {result.Item2}");
                            }
                        }
                    }
                }
            }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);

            progress.Report(100, $"Finishing the {Name} Task");
        }
Exemplo n.º 12
0
        public async Task ProcessAsync(Commands.StatusScheduleCommand command, IQuidjiboProgress progress, CancellationToken cancellationToken)
        {
            try
            {
                progress.Report(1, $"Starting the {Name} Task");

                //await Task.Run(async () =>
                //{
                var _departmentsService    = Bootstrapper.GetKernel().Resolve <IDepartmentsService>();
                var _scheduledTasksService = Bootstrapper.GetKernel().Resolve <IScheduledTasksService>();
                var logic = new StaffingScheduleLogic();

                var allDepartments = await _departmentsService.GetAllAsync();

                var allItems = await _scheduledTasksService.GetAllUpcomingStatusScheduledTasksAsync();

                if (allItems != null && allItems.Any())
                {
                    // Filter only the past items and ones that are 5 minutes 30 seconds in the future
                    var items = (from st in allItems
                                 let department = allDepartments.FirstOrDefault(x => x.DepartmentId == st.DepartmentId)
                                                  let runTime = st.WhenShouldJobBeRun(TimeConverterHelper.TimeConverter(DateTime.UtcNow, department))
                                                                where
                                                                runTime.HasValue && runTime.Value >= TimeConverterHelper.TimeConverter(DateTime.UtcNow, department) &&
                                                                runTime.Value <= TimeConverterHelper.TimeConverter(DateTime.UtcNow, department).AddMinutes(5).AddSeconds(30)
                                                                select new
                    {
                        ScheduledTask = st,
                        Department = department
                    }).ToList();

                    if (items != null && items.Any())
                    {
                        _logger.LogInformation("StatusSchedule::Status Levels to Change: " + items.Count());

                        foreach (var i in items)
                        {
                            var qi = new StaffingScheduleQueueItem();
                            qi.ScheduledTask = i.ScheduledTask;
                            qi.Department    = i.Department;

                            _logger.LogInformation("StatusSchedule::Processing Status Schedule:" + qi.ScheduledTask.ScheduledTaskId);

                            var result = await logic.Process(qi);

                            if (result.Item1)
                            {
                                _logger.LogInformation($"StatusSchedule::Processed Status Schedule {qi.ScheduledTask.ScheduledTaskId} successfully.");
                            }
                            else
                            {
                                _logger.LogInformation($"StatusSchedule::Failed to Process status schedule {qi.ScheduledTask.ScheduledTaskId} error {result.Item2}");
                            }
                        }
                    }
                }
                //}, cancellationToken);

                progress.Report(100, $"Finishing the {Name} Task");
            }
            catch (Exception ex)
            {
                Resgrid.Framework.Logging.LogException(ex);
                _logger.LogError(ex.ToString());
            }
        }
Exemplo n.º 13
0
        public List <ScheduledTask> GetUpcomingScheduledTaks(DateTime currentTime, List <ScheduledTask> tasks)
        {
            //Logging.LogTrace("ScheduledTasksService: Entering GetUpcomingScheduledTaks");

            var upcomingTasks = new List <ScheduledTask>();

            if (tasks == null || !tasks.Any())
            {
                tasks = (from st in GetAllScheduledTasks()
                         where st.Active == true
                         select st).ToList();
            }

            var logs = _scheduledTaskLogRepository.GetAllLogForDate(DateTime.UtcNow);

            //Logging.LogTrace(string.Format("ScheduledTasksService: Analyzing {0} active tasks.", tasks.Count));

            foreach (var scheduledTask in tasks)
            {
                try
                {
                    //Logging.LogTrace(string.Format("ScheduledTasksService: ScheduledTask Id: {0}", scheduledTask.ScheduledTaskId));

                    //var department = _departmentsService.GetDepartmentByUserId(scheduledTask.UserId, false);
                    //if (department != null)
                    //{
                    //	//Logging.LogTrace(string.Format("ScheduledTasksService: Department Id: {0}, Name: {1}, TimeZone: {2}",
                    //		department.DepartmentId, department.Name, department.TimeZone));

                    var runDate = TimeConverterHelper.TimeConverter(currentTime, new Department()
                    {
                        TimeZone = scheduledTask.DepartmentTimeZone
                    });
                    //Logging.LogTrace(string.Format("ScheduledTasksService: Running For Department Localized Time: {0}", runDate));

                    ///* We need to pull the Log for this schedule. There should only ever be 1 log per ScheduledTask
                    //* per day, you can't run a scheduled task multiple times per day (at the current time)
                    //*
                    //* SJ 6/8/2014: I think a problem here was that we are tracking the log in UTC, but all other work is occuring
                    //* in a localized DateTime. We were seeing some very strange behavior when UTC ticked past midnight. I've modified
                    //* the selection below to run on a localized DateTime. Linq to Entities doesn't support time converion, so I broke
                    //* up the query.
                    //*/
                    //var logs = _scheduledTaskLogRepository.GetAllLogsForTask(scheduledTask.ScheduledTaskId);

                    var log = (from stl in logs
                               where stl.ScheduledTaskId == scheduledTask.ScheduledTaskId
                               //let localizedRunDate = TimeConverterHelper.TimeConverter(stl.RunDate, new Department() { TimeZone = scheduledTask.DepartmentTimeZone })
                               //where localizedRunDate.Day == runDate.Day &&
                               //		 localizedRunDate.Month == runDate.Month &&
                               //		 localizedRunDate.Year == runDate.Year
                               select stl).FirstOrDefault();

                    //if (log == null)
                    //Logging.LogTrace("ScheduledTasksService: No previous log");
                    //else
                    //Logging.LogTrace("ScheduledTasksService: Previous Task Log detected.");

                    var runTime = scheduledTask.WhenShouldJobBeRun(runDate);

                    if (runTime.HasValue)
                    {
                        //Logging.LogTrace(string.Format("ScheduledTasksService: When should Task be run: {0}", runTime));

                        if (scheduledTask.AddedOn.HasValue)
                        {
                            //Logging.LogTrace(string.Format("ScheduledTasksService: Schedule task AddedOn has value: {0}",	scheduledTask.AddedOn));

                            if (scheduledTask.AddedOn.Value < DateTime.UtcNow)
                            {
                                //Logging.LogTrace(string.Format("ScheduledTasksService: Schedule task AddedOn is less then UtcNow"));

                                if (runTime.Value > runDate && log == null)
                                {
                                    upcomingTasks.Add(scheduledTask);
                                }
                                else if (runTime.Value < runDate && log == null)
                                {
                                    upcomingTasks.Add(scheduledTask);
                                }
                            }
                        }
                        else
                        {
                            //Logging.LogTrace(string.Format("ScheduledTasksService: Schedule task AddedOn has no value"));

                            if (runTime.Value > runDate && log == null)
                            {
                                upcomingTasks.Add(scheduledTask);
                            }
                            else if (runTime.Value < runDate && log == null)
                            {
                                upcomingTasks.Add(scheduledTask);
                            }
                        }
                    }
                    //else
                    //Logging.LogTrace(string.Format("ScheduledTasksService: NO SCHEDULE RUNTIME VALUE DETECTED"));
                    //}
                    //else
                    //{
                    //	Logging.LogError(string.Format("ScheduledTasksService: Cannot find Department for UserId: {0}", scheduledTask.UserId));
                    //}
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex);
                }
            }

            //Logging.LogTrace("ScheduledTasksService: Leaving GetUpcomingScheduledTaks");

            return(upcomingTasks);
        }
Exemplo n.º 14
0
 public static DateTime TimeConverter(this HtmlHelper html, DateTime timestamp, Department department)
 {
     return(TimeConverterHelper.TimeConverter(timestamp, department));
 }