private async Task CheckSubmitState()
        {
            // Query options to filter expired work hours entries
            var queryOptions = new List <QueryOption>();

            queryOptions.Add(new QueryOption("filter", @"startswith(fields/AutoSubmitData,'scheduled')"));
            // Call graph to get all registered users
            var usersList = await _graphSharePointService.GetSiteListItemsAsync(_usersSiteList, queryOptions);

            if (usersList?.Count > 0)
            {
                foreach (var item in usersList)
                {
                    await updateStatus("inprogress", item.Id);

                    var substractMonths = -3;
                    try
                    {
                        while (substractMonths != 0)
                        {
                            var queryOptionsExpired = new List <QueryOption>();
                            var nextOccurrence      = DateTime.Now.AddMonths(substractMonths);
                            queryOptionsExpired.Add(new QueryOption("filter", @"startswith(fields/Date,'" + nextOccurrence.ToString("yyyyMM") + "')"));

                            var userObjectIdentifier = item.Properties["ObjectIdentifier"].ToString();
                            var workHoursSiteList    = await _graphSharePointService.GetSiteListAsync(userObjectIdentifier, ListSchema.WorkHoursListSchema);

                            // Call graph to get hours not submitted but expired due to cut off setting
                            var workHoursList = await _graphSharePointService.GetSiteListItemsAsync(workHoursSiteList, queryOptionsExpired);

                            if (workHoursList?.Count > 0)
                            {
                                var workHoursToSubmit = new List <WorkHours>();
                                var managerOfUser     = await _graphUserService.GetUserManagerAsync(userObjectIdentifier);

                                foreach (var graphItem in workHoursList)
                                {
                                    workHoursToSubmit.Add(new WorkHours
                                    {
                                        Id     = graphItem.Id,
                                        ListId = workHoursSiteList.ListId,
                                        Fields = WorkHoursRepository.ConvertToWorkHours(graphItem, userObjectIdentifier)
                                    });
                                }
                                var result = await SubmitHoursAsync(workHoursToSubmit, userObjectIdentifier, managerOfUser);
                            }
                            substractMonths++;
                        }
                        await updateStatus("updated", item.Id);
                    }
                    catch (Exception ex)
                    {
                        //go to the next user.
                    }
                }
            }
        }
Exemplo n.º 2
0
        public async Task <bool> UpdateAnalytics()
        {
            try
            {
                // Get the site list
                string objectIdentifier  = Guid.NewGuid().ToString();
                var    analyticsSiteList = await _graphSharePointService.GetSiteListAsync(objectIdentifier, ListSchema.TotalHrsListSchema);

                bool processForToday  = true;
                var  analyticsRecords = await _graphSharePointService.GetSiteListItemsAsync(analyticsSiteList);

                processForToday = analyticsRecords.Count > 0;

                // get the reportHours
                var reportHoursSiteList = await _graphSharePointService.GetSiteListAsync(_reportHoursListIdentifier, ListSchema.ReportHoursListSchema);

                // if is first time process the submissions during current month, else check for any submits today.

                //var submittedDate = DateTime.Now.Date.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
                ////var todayDate = DateTime.ParseExact(submittedDate, "yyyyMMdd", CultureInfo.InvariantCulture);
                //submittedDate = processForToday ? submittedDate : submittedDate.Remove(6);

                //var options = new List<QueryOption>();
                //options.Add(new QueryOption("filter", @"startswith(fields/TeamHoursSubmittedDate,'" + submittedDate + "')"));
                //var reportHoursList = await _graphSharePointService.GetSiteListItemsAsync(reportHoursSiteList, options);

                var submitDate = DateTime.Now.Date.AddDays(-1);
                var startDate  = processForToday ? submitDate : submitDate.AddDays(1 - submitDate.Day);
                var endDate    = submitDate; // processForToday ? submitDate : startDate.AddMonths(1).AddDays(-1);

                var reportHoursList = await _graphSharePointService.GetSiteListItemsAsync(reportHoursSiteList);

                var filteredList = reportHoursList.Where(k => (DateTime.Parse(k.Properties["TeamHoursSubmittedDate"].ToString()).Date >= startDate) &&
                                                         (DateTime.Parse(k.Properties["TeamHoursSubmittedDate"].ToString()).Date <= endDate)).ToList();

                foreach (var item in filteredList)
                {
                    // Get work hours list for this teamHours entry and update the TeamHoursItemState
                    var userObjectIdentifier = item.Properties["ObjectIdentifier"].ToString();

                    var workHoursSiteList = await _graphSharePointService.GetSiteListAsync(userObjectIdentifier, ListSchema.WorkHoursListSchema);

                    // Works for longer yyyyMMdd date.
                    var dateQuery = item.Properties["Date"].ToString().Remove(6);

                    var workHoursResult = await _graphSharePointService.GetSiteListItemsAsync(workHoursSiteList, dateQuery);

                    if (workHoursResult?.Count == 0)
                    {
                        throw new ServiceException(new Error {
                            Code = "invalidRequest", Message = "Can't retrieve work hours for a team hours entry"
                        });
                    }

                    foreach (var workHoursItem in workHoursResult)
                    {
                        if ((workHoursItem.Properties["TeamHoursItemState"].ToString() != ItemState.Submitted.ToString()) ||
                            (item.Properties["TeamHoursSubmittedDate"].ToString() != workHoursItem.Properties["TeamHoursSubmittedDate"].ToString()))
                        {
                            // log error and continue;
                            // continue;   //TODO: find out why only one item is getting updated in workhours with teamhourssubmitteddate.
                        }
                        WorkHoursFields            whf         = WorkHoursRepository.ConvertToWorkHours(workHoursItem, userObjectIdentifier);
                        Dictionary <string, short> dailyTotals = Helpers.HoursComputeHelper.ComputeDailyTotals(whf);

                        // calculate totals and overtime
                        int totalHours   = Convert.ToInt16(dailyTotals["FinalTotalHrs"]);
                        int totalMins    = Convert.ToInt16(dailyTotals["FinalTotalMins"]);
                        int dailyGoalHrs = _timeTrackerOptions.DayHours;
                        int dailyGoalMin = 0;
                        int OTHours      = 0;
                        int OTMins       = 0;

                        if ((totalHours > dailyGoalHrs) || ((totalHours == dailyGoalHrs) && (dailyGoalMin > 0) && (totalMins > dailyGoalMin)))
                        {
                            OTHours = totalHours - dailyGoalHrs;
                            OTMins  = totalMins - dailyGoalMin; //TODO: verify -ve values
                            if (OTMins < 0)
                            {
                                OTMins += 60;
                                OTHours--;
                            }
                        }

                        // create analytic record.
                        // Create JSON object to add a new list item in Daily OT Hours list in SharePoint
                        dynamic dailyOTHoursFieldsObject = new JObject();
                        dailyOTHoursFieldsObject.ObjectIdentifier = userObjectIdentifier;
                        dailyOTHoursFieldsObject.Date             = workHoursItem.Properties["Date"].ToString();
                        dailyOTHoursFieldsObject.TotalHours       = totalHours;
                        dailyOTHoursFieldsObject.TotalMins        = totalMins;
                        dailyOTHoursFieldsObject.OTHours          = OTHours;
                        dailyOTHoursFieldsObject.OTMins           = OTMins;

                        dynamic dailyOTHoursRootObject = new JObject();
                        dailyOTHoursRootObject.fields = dailyOTHoursFieldsObject;

                        var saveResults = await _graphSharePointService.CreateSiteListItemAsync(analyticsSiteList, dailyOTHoursRootObject.ToString());
                    }
                }
            }

            catch (Exception ex)
            {
                _logger.LogError("Error saving team hours in submit: " + ex.Message);
                throw ex;
            }
            return(true);
        }