public async Task <ListCollectionPage <TeamHours> > GetPreviousItemsAsync(ListCollectionPage <TeamHours> listCollectionPage)
        {
            try
            {
                // Try fetching the data from cache
                listCollectionPage.CurrentPageIndex--;
                //if (listCollectionPage.CurrentPageIndex > 1) listCollectionPage.CurrentPageIndex--;
                var cacheKey = listCollectionPage.CurrentPageIndex.ToString() + "_" + listCollectionPage.ObjectIdentifier + listCollectionPage.QueryDate;



                if (String.IsNullOrEmpty(listCollectionPage.SkipToken))
                {
                    return(null);                                                    // No more entries TODO: process not submitted
                }
                // TeamHours entry not in cache TODO: Should not get to here unless no distributed cache so different logic to re-create previous

                listCollectionPage.SkipToken = "";

                listCollectionPage.DataList = new List <TeamHours>();

                return(listCollectionPage);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public async Task <IEnumerable <WorkHours> > GetItemsAsync(DateTime date)
        {
            if (date == null)
            {
                throw new ArgumentNullException(nameof(date));
            }

            try
            {
                var workHoursListCollectionPage = new ListCollectionPage <WorkHours>();
                var dateQuery     = date.ToString("yyyyMM"); // Get all items in a given month
                var workHoursList = new List <WorkHours>();
                workHoursListCollectionPage.ObjectIdentifier = _objectIdentifier;
                workHoursListCollectionPage.SiteList         = await _graphSharePointService.GetSiteListAsync(_objectIdentifier, ListSchema.WorkHoursListSchema);

                var siteList = workHoursListCollectionPage.SiteList;
                var results  = await getGraphResults(date);

                // Get the WorkHours list with computed work hours
                workHoursList = (await ComputeHours(date, results, siteList, _objectIdentifier, _timeTrackerOptions, _graphSharePointService, _graphCalendarService, _graphTasksService, _graphMailService, timezoneHelper, _timeTrackerOptions.ExcludedCategories, _timeTrackerOptions.ExcludedShowAs, _timeTrackerOptions.AllDayCountHours)).ToList <WorkHours>();
                // Write the user profile to cache
                workHoursListCollectionPage.DataList = workHoursList;

                return(workHoursList);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public async Task <ListCollectionPage <ReportHours> > GetItemsAsync(DateTime date, int pageSize = 10)
        {
            try
            {
                // Try fetching the data from cache
                var cacheKey           = "1_" + date.ToString("yyyyMM");
                var listCollectionPage = new ListCollectionPage <ReportHours>();
                //var cacheEntry = await _reportHoursCache.TryRetrieveFromCacheAsync(listCollectionPage, cacheKey);

                //if (cacheEntry != null)
                //{
                //    if (String.IsNullOrEmpty(cacheEntry.SearchQuery)) return cacheEntry;
                //    await _reportHoursCache.ClearCacheAsync("_" + date.ToString("yyyyMM"));
                //}

                // Data set not found in cache, get from backend
                listCollectionPage = await GetItemsResultsAsync(date, pageSize);

                // Save to cache
                //await _reportHoursCache.SaveToCacheAsync(listCollectionPage, cacheKey);

                return(listCollectionPage);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #4
0
        public async Task <ListCollectionPage <ReportHours> > GetItemsAsync(DateTime date, int pageSize = 10)
        {
            try
            {
                // Try fetching the data from cache
                var cacheKey           = "1_" + date.ToString("yyyyMM");
                var listCollectionPage = new ListCollectionPage <ReportHours>();
                var cacheEntry         = await _reportHoursCache.TryRetrieveFromCacheAsync(listCollectionPage, cacheKey);

                if (cacheEntry != null)
                {
                    if (String.IsNullOrEmpty(cacheEntry.SearchQuery))
                    {
                        return(cacheEntry);
                    }
                    await _reportHoursCache.ClearCacheAsync("_" + date.ToString("yyyyMM"));
                }

                // Data set not found in cache, get from backend
                listCollectionPage = await GetItemsResultsAsync(date, pageSize);

                // Save to cache
                await _reportHoursCache.SaveToCacheAsync(listCollectionPage, cacheKey);

                return(listCollectionPage);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting report hour items in repository: " + ex.Message);
                throw;
            }
        }
Example #5
0
        public async Task <ListCollectionPage <TeamHours> > GetItemsAsync(DateTime date, int pageSize = 10)
        {
            try
            {
                // Get the user object identifier
                var userObjectIdentifier = _userContext.User.FindFirst(AzureAdAuthenticationBuilderExtensions.ObjectIdentifierType)?.Value;

                // Try fetching the data from cache
                var cacheKey           = "1_" + userObjectIdentifier + date.ToString("yyyyMM");
                var listCollectionPage = new ListCollectionPage <TeamHours>();
                //var cacheEntry = await _teamHoursCache.TryRetrieveFromCacheAsync(listCollectionPage, cacheKey);

                //if (cacheEntry != null)
                //{
                //    if (String.IsNullOrEmpty(cacheEntry.SearchQuery)) return cacheEntry;
                //    await _teamHoursCache.ClearCacheAsync("_" + userObjectIdentifier + date.ToString("yyyyMM"));
                //}

                // Data set not found in cache, get from backend
                listCollectionPage = await GetItemsResultsAsync(date, pageSize, String.Empty);

                // Save to cache
                await _teamHoursCache.SaveToCacheAsync(listCollectionPage, cacheKey);

                return(listCollectionPage);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting team hour items in repository: " + ex.Message);
                throw;
            }
        }
Example #6
0
        public async Task <ListCollectionPage <TeamHours> > GetPreviousItemsAsync(ListCollectionPage <TeamHours> listCollectionPage)
        {
            try
            {
                // Try fetching the data from cache
                listCollectionPage.CurrentPageIndex--;
                //if (listCollectionPage.CurrentPageIndex > 1) listCollectionPage.CurrentPageIndex--;
                var cacheKey   = listCollectionPage.CurrentPageIndex.ToString() + "_" + listCollectionPage.ObjectIdentifier + listCollectionPage.QueryDate;
                var cacheEntry = await _teamHoursCache.TryRetrieveFromCacheAsync(listCollectionPage, cacheKey);

                if (cacheEntry != null)
                {
                    return(cacheEntry);
                }
                if (String.IsNullOrEmpty(listCollectionPage.SkipToken))
                {
                    return(null);                                                    // No more entries TODO: process not submitted
                }
                // TeamHours entry not in cache TODO: Should not get to here unless no distributed cache so different logic to re-create previous

                listCollectionPage.SkipToken = "";

                listCollectionPage.DataList = new List <TeamHours>();

                return(listCollectionPage);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting team hour items in repository: " + ex.Message);
                throw;
            }
        }
Example #7
0
        public async Task <ListCollectionPage <ReportHours> > GetPreviousItemsAsync(ListCollectionPage <ReportHours> listCollectionPage)
        {
            try
            {
                // Try fetching the data from cache
                if (listCollectionPage.CurrentPageIndex > 1)
                {
                    listCollectionPage.CurrentPageIndex--;
                }
                var cacheKey   = listCollectionPage.CurrentPageIndex.ToString() + "_" + listCollectionPage.ObjectIdentifier + listCollectionPage.QueryDate;
                var cacheEntry = await _reportHoursCache.TryRetrieveFromCacheAsync(listCollectionPage, cacheKey);

                if (cacheEntry != null)
                {
                    return(cacheEntry);
                }
                if (String.IsNullOrEmpty(listCollectionPage.SkipToken))
                {
                    return(null);                                                    // No more entries TODO: process not submitted
                }
                // ReportHours entry not in cache TODO: Should not get to here unless no distributed cache so different logic to re-create previous

                var listCollectionPageDr = new ListCollectionPage <GraphResultItem>();

                // Prepare call to graph to fetch teamhours records from SharePoint

                var queryOptions = new List <QueryOption>();
                queryOptions.Add(new QueryOption("filter", @"startswith(fields/Date,'" + listCollectionPage.QueryDate + "')")); // Filter to get all entries of a month
                queryOptions.Add(new QueryOption("$skiptoken", listCollectionPage.SkipToken));

                // Call to SharePoint graph service
                var graphResults = await _graphSharePointService.GetSiteListItemsAsync(listCollectionPage.SiteList, queryOptions, listCollectionPage.PageSize);

                listCollectionPage.SkipToken = "";
                if (!String.IsNullOrEmpty(graphResults.SkipToken))
                {
                    listCollectionPage.SkipToken = graphResults.SkipToken;                                                // Store skiptoken if any
                }
                var dateQuery = listCollectionPage.QueryDate;

                listCollectionPage.DataList = await AddItemsToDataListAsync(graphResults.DataList, dateQuery);

                // Save to cache
                await _reportHoursCache.SaveToCacheAsync(listCollectionPage, cacheKey);

                return(listCollectionPage);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting report hour items in repository: " + ex.Message);
                throw;
            }
        }
        public async Task SaveToCacheAsync(ListCollectionPage <ReportHours> items, string key)
        {
            key = key + _cacheKey;

            // Set cache options.
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                                    // Keep in cache for this time, reset time if accessed.
                                    .SetSlidingExpiration(TimeSpan.FromMinutes(_cacheTime));

            var jsonItems = JsonConvert.SerializeObject(items);

            // Save data in cache.
            _memoryCache.Set(key, jsonItems, cacheEntryOptions);
        }
Example #9
0
        public async Task <ListCollectionPage <TeamHours> > GetPageItemsAsync(ListCollectionPage <TeamHours> listCollectionPage, int page = 1)
        {
            try
            {
                // Try fetching the data from cache
                var cacheKey   = page.ToString() + "_" + listCollectionPage.ObjectIdentifier + listCollectionPage.QueryDate;
                var cacheEntry = await _teamHoursCache.TryRetrieveFromCacheAsync(listCollectionPage, cacheKey);

                if (cacheEntry != null)
                {
                    return(cacheEntry);
                }

                if (cacheEntry.CurrentPageIndex > page && !String.IsNullOrEmpty(listCollectionPage.SkipToken))
                {
                    var currentPage = cacheEntry.CurrentPageIndex;
                    while (currentPage < page)
                    {
                        var moveResults = await GetNextItemsAsync(listCollectionPage);

                        if (moveResults != null)
                        {
                            if (moveResults.CurrentPageIndex == page)
                            {
                                return(moveResults);
                            }
                            currentPage = moveResults.CurrentPageIndex;
                        }

                        if (currentPage < page && String.IsNullOrEmpty(moveResults.SkipToken))
                        {
                            break;
                        }
                    }

                    return(null);
                }
                else
                {
                    return(null); // No pages exists for provided index
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting team hour items in repository: " + ex.Message);
                throw;
            }
        }
        public async Task <ListCollectionPage <TeamHours> > GetItemsAsync(DateTime date, int pageSize = 10)
        {
            try
            {
                // Get the user object identifier
                //var userObjectIdentifier = _userContext.User.FindFirst(AzureAdAuthenticationBuilderExtensions.ObjectIdentifierType)?.Value;
                var userObjectIdentifier = _objectIdentifier;

                var listCollectionPage = new ListCollectionPage <TeamHours>();
                listCollectionPage = await GetItemsResultsAsync(date, pageSize, String.Empty);

                return(listCollectionPage);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public async Task <ListCollectionPage <ReportHours> > GetNextItemsAsync(ListCollectionPage <ReportHours> listCollectionPage)
        {
            try
            {
                // Try fetching the data from cache
                listCollectionPage.CurrentPageIndex++;
                var cacheKey = listCollectionPage.CurrentPageIndex.ToString() + "_" + listCollectionPage.ObjectIdentifier + listCollectionPage.QueryDate;
                //var cacheEntry = await _reportHoursCache.TryRetrieveFromCacheAsync(listCollectionPage, cacheKey);

                //if (cacheEntry != null) return cacheEntry;
                if (String.IsNullOrEmpty(listCollectionPage.SkipToken))
                {
                    return(null);                                                    // No more entries TODO: process not submitted
                }
                // ReportHours entry not in cache
                listCollectionPage.DataList = new List <ReportHours>();

                var queryOptions = new List <QueryOption>();
                queryOptions.Add(new QueryOption("filter", @"startswith(fields/Date,'" + listCollectionPage.QueryDate + "')")); // Filter to get all entries of a month
                queryOptions.Add(new QueryOption("$skiptoken", listCollectionPage.SkipToken));

                // Call to SharePoint graph service
                var graphResults = await _graphSharePointService.GetSiteListItemsAsync(listCollectionPage.SiteList, queryOptions, listCollectionPage.PageSize);

                listCollectionPage.SkipToken = "";
                if (!String.IsNullOrEmpty(graphResults.SkipToken))
                {
                    listCollectionPage.SkipToken = graphResults.SkipToken;                                                // Store skiptoken if any
                }
                var dateQuery = listCollectionPage.QueryDate;

                listCollectionPage.DataList = await AddItemsToDataListAsync(graphResults.DataList, dateQuery);

                // Save to cache
                //await _reportHoursCache.SaveToCacheAsync(listCollectionPage, cacheKey);

                return(listCollectionPage);
            }
            catch (Exception ex)
            {
                //_logger.LogError("Error getting report hour items in repository: " + ex.Message);
                throw;
            }
        }
        public async Task SaveItemAsync(WorkHours modelData)
        {
            if (String.IsNullOrEmpty(modelData.Id))
            {
                throw new ArgumentNullException(nameof(modelData.Id));
            }

            try
            {
                var workHoursList = new List <WorkHours>();
                var workHoursListCollectionPage = new ListCollectionPage <WorkHours>();
                // This works when dateTime is longer.
                var dateQuery = modelData.Fields.Date.Remove(6);


                // Get the site list
                var userObjectIdentifier = _objectIdentifier;                 // _userContext.User.FindFirst(ObjectIdentifierType)?.Value;
                var siteList             = await _graphSharePointService.GetSiteListAsync(userObjectIdentifier, ListSchema.WorkHoursListSchema);

                //if (String.IsNullOrEmpty(siteList.ListId)) siteList = await _graphSharePointService.GetSiteListAsync(userObjectIdentifier, ListSchema.WorkHoursListSchema);

                // Create JSON object
                dynamic fieldsObject = new JObject();
                fieldsObject.MeetingAdjustedHours   = modelData.Fields.MeetingAdjustedHours;
                fieldsObject.MeetingAdjustedMinutes = modelData.Fields.MeetingAdjustedMinutes;
                fieldsObject.EmailAdjustedHours     = modelData.Fields.EmailAdjustedHours;
                fieldsObject.EmailAdjustedMinutes   = modelData.Fields.EmailAdjustedMinutes;
                fieldsObject.OtherAdjustedHours     = modelData.Fields.OtherAdjustedHours;
                fieldsObject.OtherAdjustedMinutes   = modelData.Fields.OtherAdjustedMinutes;
                fieldsObject.AdjustedHoursReason    = modelData.Fields.AdjustedHoursReason;

                dynamic rootObject = new JObject();
                rootObject.fields = fieldsObject;

                // Persist to SharePoint
                var result = await _graphSharePointService.UpdateSiteListItemAsync(siteList, modelData.Id, rootObject.ToString());
            }
            catch (Exception ex)
            {
            }
        }
        public async Task <IEnumerable <Analytics> > GetItemsAsync(DateTime date)
        {
            if (date == null)
            {
                throw new ArgumentNullException(nameof(date));
            }

            try
            {
                var analyticsListCollectionPage = new ListCollectionPage <Analytics>();
                var dateQuery = date.ToString("yyyyMM");  // Get all items in a given month

                string objectIdentifier = Guid.NewGuid().ToString();

                // Get the site list
                analyticsListCollectionPage.SiteList = await _graphSharePointService.GetSiteListAsync(objectIdentifier, ListSchema.TotalHrsListSchema);

                var siteList = analyticsListCollectionPage.SiteList;

                analyticsListCollectionPage.QueryDate = dateQuery;

                // Get the results from the call to GraphService.GetSiteListItemByDateAsync
                var results = await _graphSharePointService.GetSiteListItemsAsync(siteList, dateQuery);

                var analyticsResults = await AddItemsToDataListAsync(siteList, results);

                // get the datewise groupings and the count of users both total and reported overtime
                //var groupings = from item in analyticsResults
                //                group item by item.Fields.selDate into data

                //                select data.Distinct();

                return(analyticsResults);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting work hour items in repository: " + ex.Message);
                throw;
            }
        }
Example #14
0
        // Private methods

        public async Task <ListCollectionPage <ReportHours> > GetItemsResultsAsync(DateTime date, int pageSize = 10, string searchQuery = "")
        {
            try
            {
                var dateQuery = date.ToString("yyyyMM");

                var listCollectionPage = new ListCollectionPage <ReportHours>();
                listCollectionPage.QueryDate        = dateQuery;
                listCollectionPage.ObjectIdentifier = _reportHoursIdentifier;
                listCollectionPage.CurrentPageIndex = 1;
                listCollectionPage.PageSize         = pageSize;
                listCollectionPage.SearchQuery      = searchQuery;
                listCollectionPage.SiteList         = await _graphSharePointService.GetSiteListAsync(_reportHoursIdentifier, ListSchema.ReportHoursListSchema);

                var queryOptions = new List <QueryOption>();
                queryOptions.Add(new QueryOption("filter", @"startswith(fields/Date,'" + listCollectionPage.QueryDate + "')")); // Filter to get all entries of a month

                // Call to SharePoint graph service
                var graphResults = await _graphSharePointService.GetSiteListItemsAsync(listCollectionPage.SiteList, queryOptions, pageSize);

                if (graphResults.DataList?.Count == 0)
                {
                    return(new ListCollectionPage <ReportHours>());                                  // No entries were found
                }
                listCollectionPage.SkipToken = "";
                if (!String.IsNullOrEmpty(graphResults.SkipToken))
                {
                    listCollectionPage.SkipToken = graphResults.SkipToken;                                                // Store skiptoken if any
                }
                listCollectionPage.DataList = await AddItemsToDataListAsync(graphResults.DataList, dateQuery);

                return(listCollectionPage);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting report hour items in repository: " + ex.Message);
                throw;
            }
        }
        public async Task <ListCollectionPage <TeamHours> > GetPageItemsAsync(ListCollectionPage <TeamHours> listCollectionPage, int page = 1)
        {
            try
            {
                // Try fetching the data from cache
                var cacheKey = page.ToString() + "_" + listCollectionPage.ObjectIdentifier + listCollectionPage.QueryDate;
                //var cacheEntry = await _teamHoursCache.TryRetrieveFromCacheAsync(listCollectionPage, cacheKey);

                //if (cacheEntry != null) return cacheEntry;

                //if (cacheEntry.CurrentPageIndex > page && !String.IsNullOrEmpty(listCollectionPage.SkipToken))
                //{
                //    var currentPage = cacheEntry.CurrentPageIndex;
                //    while (currentPage < page)
                //    {
                //        var moveResults = await GetNextItemsAsync(listCollectionPage);
                //        if (moveResults != null)
                //        {
                //            if (moveResults.CurrentPageIndex == page) return moveResults;
                //            currentPage = moveResults.CurrentPageIndex;
                //        }

                //        if (currentPage < page && String.IsNullOrEmpty(moveResults.SkipToken)) break;
                //    }

                //    return null;
                //}
                //else
                //{
                //    return null; // No pages exists for provided index
                //}
                return(null);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public async Task <IListCollectionPage <GraphResultItem> > GetUserDirectReportsAsync(string userObjectIdentifier, string skipToken = "", int pageSize = 10)
        {
            try
            {
                var directReportsList = new ListCollectionPage <GraphResultItem>();
                directReportsList.ObjectIdentifier = userObjectIdentifier;

                var queryOptions = new List <QueryOption>();
                if (!String.IsNullOrEmpty(skipToken))
                {
                    queryOptions.Add(new QueryOption("$skiptoken", skipToken));
                }

                // Call to Graph API to get the current user direct reports information.
                var graphRequest = await GraphAppClient.Users[userObjectIdentifier].DirectReports.Request(queryOptions).Top(pageSize).GetAsync();

                if (graphRequest?.Count == 0)
                {
                    return(directReportsList);
                }

                if (graphRequest.NextPageRequest != null)
                {
                    var graphRequestOptions = graphRequest.NextPageRequest.QueryOptions.ToList();
                    directReportsList.SkipToken = graphRequestOptions.Find(x => x.Name == "$skiptoken").Value ?? "";
                }
                else
                {
                    directReportsList.SkipToken = "";
                }

                foreach (User user in graphRequest)
                {
                    directReportsList.DataList.Add(new GraphResultItem
                    {
                        Id          = user.Id,
                        DisplayName = user.DisplayName,
                        Properties  = new Dictionary <string, object>
                        {
                            { "Mail", user.Mail },
                            { "Upn", user.UserPrincipalName }
                        }
                    });
                }

                return(directReportsList);
            }
            catch (ServiceException ex)
            {
                switch (ex.Error.Code)
                {
                case "Request_ResourceNotFound":
                case "ResourceNotFound":
                case "ErrorItemNotFound":
                case "itemNotFound":
                    return(new ListCollectionPage <GraphResultItem>());

                case "TokenNotFound":
                    //await HttpContext.ChallengeAsync();
                    throw;

                default:
                    throw;
                }
            }
        }
Example #17
0
        public async Task <WeeklyHoursViewModel> GetViewModel(DateTime dt, int pageIndex = 1, int pageSize = 10)
        {
            var ci = System.Threading.Thread.CurrentThread.CurrentCulture;

            try
            {
                if (_listCollectionPage == null)
                {
                    _listCollectionPage = await _reportHoursRepository.GetItemsAsync(dt, pageSize);
                }

                // Check to see if a new date is being requested
                if (_listCollectionPage.QueryDate != dt.ToString("yyyyMM"))
                {
                    _listCollectionPage = await _reportHoursRepository.GetItemsAsync(dt, pageSize);
                }

                if ((pageIndex - _listCollectionPage.CurrentPageIndex) == 1)
                {
                    // Move next
                    _listCollectionPage = await _reportHoursRepository.GetNextItemsAsync(_listCollectionPage);
                }
                else if ((_listCollectionPage.CurrentPageIndex - pageIndex) == 1)
                {
                    // Move previous
                    _listCollectionPage = await _reportHoursRepository.GetPreviousItemsAsync(_listCollectionPage);
                }
                else if (pageIndex > 2)  // Increment until we find the correct page.
                {
                    while (_listCollectionPage.CurrentPageIndex < pageIndex)
                    {
                        _listCollectionPage = await _reportHoursRepository.GetNextItemsAsync(_listCollectionPage);
                    }
                }

                // Create the DataTable
                MyWeeklyHoursDataTableData dataTableData = new MyWeeklyHoursDataTableData(); // This is the WeeklyHoursListData.

                List <WeeklyHoursListData> weeklyHrsListData = new List <WeeklyHoursListData>();

                // Get an array tagging each item of the month with the Week number
                int[] dateWeekNumber = this.GetDayOfMonthWeekAssignmentArray(dt);
                var   myWeekNumber   = dateWeekNumber[dt.Day - 1];

                var weeklyHrsList = new List <WeeklyHours>();

                //var items = await this._reportHoursRepository.GetItemsAsync(dt);

                // Group Report hours by individual User data using DisplayName
                var monthDate = from item in _listCollectionPage.DataList
                                group item by item.Fields.DisplayName into data

                                select data;

                DateTime weekStartDate = dt;
                DateTime weekEndDate   = weekStartDate;
                while (weekEndDate.DayOfWeek != DayOfWeek.Saturday)
                {
                    weekEndDate = weekEndDate.AddDays(1);
                }

                //var groupings = monthDate.ToList().Where(k => DateTime.ParseExact(k.Contains, "yyyyMMdd", ci).Date >= LweekStEndDt["weekStDate"].Date && DateTime.ParseExact(k.Fields.Date, "yyyyMMdd", ci).Date <= LweekStEndDt["weekEndDate"].Date);


                // Process the data for each user
                foreach (var grouping in monthDate)
                {
                    var thisGrouping = new WeeklyHoursListData();

                    int SundayMins     = 0;
                    int SundayHours    = 0;
                    int MondayMins     = 0;
                    int MondayHours    = 0;
                    int TuesdayMins    = 0;
                    int TuesdayHours   = 0;
                    int WednesdayMins  = 0;
                    int WednesdayHours = 0;
                    int ThursdayMins   = 0;
                    int ThursdayHours  = 0;
                    int FridayMins     = 0;
                    int FridayHours    = 0;
                    int SaturdayMins   = 0;
                    int SaturdayHours  = 0;


                    var weekTotalMns = 0;
                    var TotalMins    = 0;

                    var weekTotalHrs = 0;
                    var TotalHours   = 0;


                    var weeklyHrs = new WeeklyHours();


                    var thisWeekData = grouping.Where(k => DateTime.ParseExact(k.Fields.Date, "yyyyMMdd", ci).Date >= weekStartDate.Date && DateTime.ParseExact(k.Fields.Date, "yyyyMMdd", ci).Date <= weekEndDate.Date);
                    //var resultLastWeek = grouping.Where(k => DateTime.ParseExact(k.Fields.Date, "yyyyMMdd", ci).Date >= weekStartDate.Date && DateTime.ParseExact(k.Fields.Date, "yyyyMMdd", ci).Date <= LweekStEndDt["weekEndDate"].Date);
                    //Add the computed object(for each employee) to the list of weekly hours for the HR
                    weeklyHrsList.Add(weeklyHrs);
                    weeklyHrs.EmpName = grouping.Key;
                    //foreach (var item in grouping)

                    foreach (var item in thisWeekData)

                    {
                        thisGrouping.ENm = item.Fields.DisplayName.ToString();
                        thisGrouping.MNm = item.Fields.ManagerDisplayName.ToString();
                        Dictionary <string, short> hrsMins = new Dictionary <string, short>();

                        //call to get Final hours for ReportHours Repository data
                        hrsMins = HoursComputeHelper.GetFinalHrsMins(item);
                        var totalHours = hrsMins["FinalTotalHrs"];
                        var totalMins  = hrsMins["FinalTotalMins"];
                        if (weeklyHrs.MgrName == null)
                        {
                            weeklyHrs.MgrName = item.Fields.ManagerDisplayName;
                        }
                        var itemDate = DateTime.ParseExact(item.Fields.Date, "yyyyMMdd", ci);

                        //var theWeekNumber = dateWeekNumber[itemDate.Day - 1];
                        //if (dateWeekNumber[itemDate.Day - 1] == myWeekNumber)
                        //{

                        switch (itemDate.DayOfWeek)
                        {
                        case System.DayOfWeek.Sunday:
                            weeklyHrs.SundayHours += totalHours;
                            weeklyHrs.SundayMins  += totalMins;
                            break;

                        case System.DayOfWeek.Monday:
                            weeklyHrs.MondayHours += totalHours;
                            weeklyHrs.MondayMins  += totalMins;
                            break;

                        case System.DayOfWeek.Tuesday:
                            weeklyHrs.TuesdayHours += totalHours;
                            weeklyHrs.TuesdayMins  += totalMins;
                            break;

                        case System.DayOfWeek.Wednesday:
                            weeklyHrs.WednesdayHours += totalHours;
                            weeklyHrs.WednesdayMins  += totalMins;
                            break;

                        case System.DayOfWeek.Thursday:
                            weeklyHrs.ThursdayHours += totalHours;
                            weeklyHrs.ThursdayMins  += totalMins;
                            break;

                        case System.DayOfWeek.Friday:
                            weeklyHrs.FridayHours += totalHours;
                            weeklyHrs.FridayMins  += totalMins;
                            break;

                        default:
                            weeklyHrs.SaturdayHours += totalHours;
                            weeklyHrs.SaturdayMins  += totalMins;
                            break;
                        }


                        SundayMins     = (short)(weeklyHrs.SundayMins % 60);
                        SundayHours    = (short)(weeklyHrs.SundayHours + (weeklyHrs.SundayMins / 60));
                        MondayMins     = (short)(weeklyHrs.MondayMins % 60);
                        MondayHours    = (short)(weeklyHrs.MondayHours + (weeklyHrs.MondayMins / 60));
                        TuesdayMins    = (short)(weeklyHrs.TuesdayMins % 60);
                        TuesdayHours   = (short)(weeklyHrs.TuesdayHours + (weeklyHrs.TuesdayMins / 60));
                        WednesdayMins  = (short)(weeklyHrs.WednesdayMins % 60);
                        WednesdayHours = (short)(weeklyHrs.WednesdayHours + (weeklyHrs.WednesdayMins / 60));
                        ThursdayMins   = (short)(weeklyHrs.ThursdayMins % 60);
                        ThursdayHours  = (short)(weeklyHrs.ThursdayHours + (weeklyHrs.ThursdayMins / 60));
                        FridayMins     = (short)(weeklyHrs.FridayMins % 60);
                        FridayHours    = (short)(weeklyHrs.FridayHours + (weeklyHrs.FridayMins / 60));
                        SaturdayMins   = (short)(weeklyHrs.SaturdayMins % 60);
                        SaturdayHours  = (short)(weeklyHrs.SaturdayHours + (weeklyHrs.SaturdayMins / 60));


                        weekTotalMns = (SundayMins + MondayMins + TuesdayMins + WednesdayMins + ThursdayMins + FridayMins + SaturdayMins) % 60;
                        TotalMins    = (short)weekTotalMns;

                        weekTotalHrs = (SundayHours + MondayHours + TuesdayHours + WednesdayHours + ThursdayHours + FridayHours + SaturdayHours) + (weekTotalMns / 60);
                        TotalHours   = (short)weekTotalHrs;

                        // This is what the view needs.
                    }                     // end for each grouping.

                    var weeklySundayHrMns    = SundayHours + "h " + SundayMins + "m";
                    var weeklyMondayHrMns    = MondayHours + "h " + MondayMins + "m";
                    var weeklyTuesdayHrMns   = TuesdayHours + "h " + TuesdayMins + "m";
                    var weeklyWednesdayHrMns = WednesdayHours + "h " + WednesdayMins + "m";
                    var weeklyThursdayHrMns  = ThursdayHours + "h " + ThursdayMins + "m";
                    var weeklyFridayHrMns    = FridayHours + "h " + FridayMins + "m";
                    var weeklySaturdayHrMns  = SaturdayHours + "h " + SaturdayMins + "m";
                    var weeklylyTotalHrMns   = TotalHours + "h " + TotalMins + "m";
                    thisGrouping.suHM  = weeklySundayHrMns.ToString();
                    thisGrouping.MonHM = weeklyMondayHrMns.ToString();
                    thisGrouping.TuHM  = weeklyTuesdayHrMns.ToString();
                    thisGrouping.weHM  = weeklyWednesdayHrMns.ToString();
                    thisGrouping.ThHM  = weeklyThursdayHrMns.ToString();
                    thisGrouping.frHM  = weeklyFridayHrMns.ToString();
                    thisGrouping.SaHM  = weeklySaturdayHrMns.ToString();
                    thisGrouping.TotHM = weeklylyTotalHrMns.ToString();


                    //Add the computed object(for each employee) to the list of monthly hours for the HR
                    weeklyHrsListData.Add(thisGrouping);

                    SundayMins     = 0;
                    SundayHours    = 0;
                    MondayMins     = 0;
                    MondayHours    = 0;
                    TuesdayMins    = 0;
                    TuesdayHours   = 0;
                    WednesdayMins  = 0;
                    WednesdayHours = 0;
                    ThursdayMins   = 0;
                    ThursdayHours  = 0;
                    FridayMins     = 0;
                    FridayHours    = 0;
                    SaturdayMins   = 0;
                    SaturdayHours  = 0;


                    weekTotalMns = 0;
                    TotalMins    = 0;

                    weekTotalHrs = 0;
                    TotalHours   = 0;
                }
                //dataTableData.draw = draw;
                dataTableData.recordsTotal = (pageIndex * pageSize) + weeklyHrsListData.Count + 1;
                int recordsFiltered = (pageIndex * pageSize) + weeklyHrsListData.Count + 1;

                dataTableData.recordsFiltered = recordsFiltered;
                dataTableData.data            = weeklyHrsListData;

                var weeklyHoursViewModel = new WeeklyHoursViewModel
                {
                    MyWeeklyHoursDataTableData = dataTableData,
                    PaginationInfo             = new PaginationInfoViewModel
                    {
                        CurrentPage = pageIndex,
                        PageSize    = pageSize,
                        Next        = "is-disabled",
                        Previous    = "is-disabled"
                    }
                };

                return(weeklyHoursViewModel);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting the weekly hours view model: " + ex.Message);
                return(new WeeklyHoursViewModel());
            }
        }
        public async Task <ListCollectionPage <ReportHours> > TryRetrieveFromCacheAsync(ListCollectionPage <ReportHours> items, string key)
        {
            key = key + _cacheKey;

            if (_cacheTime == 0)
            {
                return(items);                 // Cache is disabled
            }
            var entryFromCache = _memoryCache.Get <string>(key);

            if (entryFromCache == null)
            {
                return(null);
            }

            items = JsonConvert.DeserializeObject <ListCollectionPage <ReportHours> >(entryFromCache);

            return(items);
        }
        public async Task <IListCollectionPage <GraphResultItem> > GetSiteListItemsAsync(SiteList siteList, IEnumerable <QueryOption> queryOptions, int pageSize = 10)
        {
            try
            {
                if (String.IsNullOrEmpty(siteList.ListId))
                {
                    throw new ArgumentNullException(nameof(siteList.ListId));
                }
                if (String.IsNullOrEmpty(siteList.SiteId))
                {
                    throw new ArgumentNullException(nameof(siteList.SiteId));
                }
                if (queryOptions == null)
                {
                    throw new ArgumentNullException(nameof(queryOptions));
                }

                var listItemResults = new List <ListItem>();

                var options = queryOptions.ToList <QueryOption>();
                options.Add(new QueryOption("top", pageSize.ToString()));

                // Call to graph API to retrieve List Items filtered by dateQuery (match pattern: yyyyMMdd) example: for full month 201802
                var graphRequest = await GraphAppClient.Sites[siteList.SiteId].Lists[siteList.ListId].Items.Request(options).Expand("fields").GetAsync();

                if (graphRequest?.Count == 0)
                {
                    throw new ServiceException(new Error {
                        Code = ErrorConstants.Codes.ItemNotFound
                    });
                }

                var graphRequestList = new ListCollectionPage <GraphResultItem>();

                if (graphRequest.NextPageRequest != null)
                {
                    var graphRequestOptions = graphRequest.NextPageRequest.QueryOptions.ToList();
                    graphRequestList.SkipToken = graphRequestOptions.Find(x => x.Name == "$skiptoken").Value ?? "";
                }

                var resultItems = new List <GraphResultItem>();

                foreach (var item in graphRequest)
                {
                    var resultsItemProperties = new Dictionary <string, object>();

                    foreach (var field in item.Fields.AdditionalData)
                    {
                        resultsItemProperties.Add(field.Key, field.Value.ToString());
                    }

                    resultItems.Add(new GraphResultItem
                    {
                        Id         = item.Id,
                        Properties = resultsItemProperties
                    });
                }

                graphRequestList.DataList = resultItems;

                return(graphRequestList);
            }
            catch (ServiceException ex)
            {
                switch (ex.Error.Code)
                {
                case "Request_ResourceNotFound":
                case "ResourceNotFound":
                case "ErrorItemNotFound":
                case "itemNotFound":
                    return(new ListCollectionPage <GraphResultItem>());

                case "ErrorInvalidUser":
                    throw;

                case "AuthenticationFailure":
                    throw;

                case "TokenNotFound":
                    //await HttpContext.ChallengeAsync();
                    throw;

                default:
                    throw;
                }
            }
        }
Example #20
0
        public async Task <IActionResult> Myteams(string selMonthDt, string empNameFilter = default(string), int pageId = 0, int pageSize = 10, ListCollectionPage <TeamHours> teamHours = null, int status = 0)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (_userProfile == null)
                {
                    _userProfile = await _userProfileRepository.GetItemAsync();
                }
                ViewData["Email"]     = _userProfile.Fields.Upn;
                ViewData["IsManager"] = _userProfile.Fields.IsManager;
                ViewData["IsHr"]      = _userProfile.Fields.IsHr;
                ViewData["IsAdmin"]   = _userProfile.Fields.IsAdmin;
                ViewData["UserImage"] = _userProfile.Fields.UserPicture;

                DateTime selDt = DateTime.Now.AddMonths(-1);
                if (selMonthDt != null)
                {
                    selDt = Convert.ToDateTime(selMonthDt.ToString());
                }

                var myTeamsHoursViewModel = await _dataServiceClient.GetMyTeamHours(selDt, empNameFilter, pageId, pageSize);

                //MyTeamHoursViewModel myTeamsHoursViewModel = new MyTeamHoursViewModel();
                //ListCollectionPage<TeamHours> teamHourstemp = null;
                //if (Request.Query.Count != 0)
                //{
                //    var json = Request.Query["teamHours"];
                //    teamHourstemp = JsonConvert.DeserializeObject<ListCollectionPage<TeamHours>>(json);
                //}
                //if (status == 0)
                //    teamHours = await _dataServiceClient.GetMyTeamHoursPageView(selDt, empNameFilter, pageId, pageSize, User, HttpContext, null, 0);
                //else if (status == 1)
                //    teamHours = await _dataServiceClient.GetMyTeamHoursPageView(selDt, empNameFilter, pageId, pageSize, User, HttpContext, teamHourstemp, 1);
                //else if (status == 2)
                //    teamHours = await _dataServiceClient.GetMyTeamHoursPageView(selDt, empNameFilter, pageId, pageSize, User, HttpContext, teamHourstemp, 2);

                //if (teamHours == null)
                //{
                //    myTeamsHoursViewModel.UserInfo = _userProfile;
                //    return View(myTeamsHoursViewModel);
                //}

                ViewData["TeamHoursCollection"] = teamHours;

                IList <TeamHours> teamHoursList = teamHours.DataList;
                bool   isSubmitted   = false;
                string SubmittedDate = string.Empty;
                if (teamHoursList != null)
                {
                    List <MyTeamFields> myTeam = new List <MyTeamFields>();
                    foreach (var team in teamHoursList)
                    {
                        if (team.Fields.TeamHoursItemState == MiddleTier.Helpers.ItemState.Submitted)
                        {
                            isSubmitted   = true;
                            SubmittedDate = team.Fields.TeamHoursSubmittedDate.ToString();
                        }

                        myTeam.Add(new MyTeamFields
                        {
                            TeamHours = team
                        });
                    }

                    myTeamsHoursViewModel.IsSubmitted   = isSubmitted;
                    myTeamsHoursViewModel.SubmittedDate = SubmittedDate;
                    myTeamsHoursViewModel.MyTeam        = myTeam;
                }

                if (selMonthDt == null)
                {
                    myTeamsHoursViewModel.SearchDate = myTeamsHoursViewModel.fnGetLastMonthEndDate();
                }
                else
                {
                    myTeamsHoursViewModel.SearchDate = selDt;
                }

                myTeamsHoursViewModel.UserInfo = _userProfile;

                return(View(myTeamsHoursViewModel));
            }
            else
            {
                ErrorViewModel EVM = new ErrorViewModel();

                return(View(EVM));
            }
        }
Example #21
0
        /*
         * public async Task<IActionResult> Weekly(string dt)
         * {
         * if (User.Identity.IsAuthenticated)
         * {
         * // Get UserProfile details
         * _userProfile = await _dataServiceClient.GetUserProfile(User, HttpContext);
         * ViewData["Email"] = _userProfile.Fields.Upn;
         * ViewData["IsManager"] = _userProfile.Fields.IsManager;
         * ViewData["IsHr"] = _userProfile.Fields.IsHr;
         * ViewData["IsAdmin"] = _userProfile.Fields.IsAdmin;
         * ViewData["UserImage"] = _userProfile.Fields.UserPicture;
         *
         * DateTime selDt = DateTime.Now.AddDays(-DateTime.Now.Day);
         * if (dt != null)
         * {
         *  selDt = Convert.ToDateTime(dt.ToString());
         * }
         *
         *
         * var viewModel = await _dataServiceClient.GetWeeklyReportHours(
         *  User,
         *  HttpContext,
         * selDt);
         * viewModel.ComputeTotalHrs();
         * viewModel.SelectedDate = selDt;
         * return View(viewModel);
         * }
         * else
         * {
         * ErrorViewModel EVM = new ErrorViewModel();
         *
         * return View(EVM);
         * }
         * }
         */

        //public async Task<IActionResult> Weekly(string dt)
        public async Task <IActionResult> Weekly(string selMonthDt, string empNameFilter = default(string), int pageId = 0, int pageSize = 10, ListCollectionPage <ReportHours> reportHours = null, int status = 0)
        {
            var ci = System.Threading.Thread.CurrentThread.CurrentCulture;

            if (User.Identity.IsAuthenticated)
            {
                // Get UserProfile details
                if (_userProfile == null)
                {
                    _userProfile = await _userProfileRepository.GetItemAsync();
                }
                ViewData["Email"]     = _userProfile.Fields.Upn;
                ViewData["IsManager"] = _userProfile.Fields.IsManager;
                ViewData["IsHr"]      = _userProfile.Fields.IsHr;
                ViewData["IsAdmin"]   = _userProfile.Fields.IsAdmin;
                ViewData["UserImage"] = _userProfile.Fields.UserPicture;

                DateTime selDt      = DateTime.Now.AddDays(-DateTime.Now.Day);
                int      startDay   = (int)selDt.DayOfWeek;
                int      dayOfMonth = (int)selDt.Day;
                while ((startDay > 0) && (dayOfMonth > 1))
                {
                    selDt = selDt.AddDays(-1);
                    startDay--;
                    dayOfMonth--;
                }

                if (selMonthDt != null)
                {
                    selDt      = Convert.ToDateTime(selMonthDt.ToString());
                    startDay   = (int)selDt.DayOfWeek;
                    dayOfMonth = (int)selDt.Day;
                    while ((startDay > 0) && (dayOfMonth > 1))
                    {
                        selDt = selDt.AddDays(-1);
                        startDay--;
                        dayOfMonth--;
                    }
                }
                //DateTime date = Convert.ToDateTime(selMonthDt);
                // Get an array tagging each item of the month with the Week number



                int[] dateWeekNumber = _dataServiceClient.GetDayOfMonthWeekAssignmentArray(selDt);


                // Get an array tagging each item of the month with the Week number
                var myWeekNumber  = dateWeekNumber[selDt.Day - 1];
                var weeklyHrsList = new List <WeeklyHours>();

                WeeklyHoursViewModel             weeklyViewModel = new WeeklyHoursViewModel();
                ListCollectionPage <ReportHours> weeklyTemp      = null;
                //if (Request.Query.Count != 0)
                //{
                //var json = Request.Query["reportHours"];
                //weeklyTemp = JsonConvert.DeserializeObject<ListCollectionPage<ReportHours>>(json);
                //}
                if (status == 0)
                {
                    reportHours = await _dataServiceClient.GetWeeklyPageView(selDt, empNameFilter, pageId, pageSize, null, 0);
                }
                else if (status == 1)
                {
                    reportHours = await _dataServiceClient.GetWeeklyPageView(selDt, empNameFilter, pageId, pageSize, reportHours, 1);
                }
                else if (status == 2)
                {
                    reportHours = await _dataServiceClient.GetWeeklyPageView(selDt, empNameFilter, pageId, pageSize, reportHours, 2);
                }

                /*
                 * if (teamHours == null)
                 * {
                 *      myTeamsHoursViewModel.UserInfo = _userProfile;
                 *      return View(myTeamsHoursViewModel);
                 * }
                 */
                ViewData["ReportHoursCollection"] = reportHours;

                IList <ReportHours> reportHoursList = reportHours.DataList;
                // Group Monthly Report hours by individual User data using DisplayName
                var groupings = from item in reportHoursList
                                group item by item.Fields.DisplayName into data
                                select data;

                // Process the data for each user
                foreach (var grouping in groupings)
                {
                    var weeklyHrs = new WeeklyHours();

                    //Add the computed object(for each employee) to the list of weekly hours for the HR
                    weeklyHrsList.Add(weeklyHrs);
                    weeklyHrs.EmpName = grouping.Key;
                    foreach (var item in grouping)
                    {
                        Dictionary <string, short> hrsMins = new Dictionary <string, short>();

                        //call to get Final hours for ReportHours Repository data
                        hrsMins = HoursComputeHelper.GetFinalHrsMins(item);
                        var totalHours = hrsMins["FinalTotalHrs"];
                        var totalMins  = hrsMins["FinalTotalMins"];
                        if (weeklyHrs.MgrName == null)
                        {
                            weeklyHrs.MgrName = item.Fields.ManagerDisplayName;
                        }
                        var itemDate = DateTime.ParseExact(item.Fields.Date, "yyyyMMdd", ci);

                        var theWeekNumber = dateWeekNumber[itemDate.Day - 1];
                        if (dateWeekNumber[itemDate.Day - 1] == myWeekNumber)
                        {
                            switch (itemDate.DayOfWeek)
                            {
                            case System.DayOfWeek.Saturday:
                                weeklyHrs.SundayHours += totalHours;
                                weeklyHrs.SundayMins  += totalMins;
                                break;

                            case System.DayOfWeek.Monday:
                                weeklyHrs.MondayHours += totalHours;
                                weeklyHrs.MondayMins  += totalMins;
                                break;

                            case System.DayOfWeek.Tuesday:
                                weeklyHrs.TuesdayHours += totalHours;
                                weeklyHrs.TuesdayMins  += totalMins;
                                break;

                            case System.DayOfWeek.Wednesday:
                                weeklyHrs.WednesdayHours += totalHours;
                                weeklyHrs.WednesdayMins  += totalMins;
                                break;

                            case System.DayOfWeek.Thursday:
                                weeklyHrs.ThursdayHours += totalHours;
                                weeklyHrs.ThursdayMins  += totalMins;
                                break;

                            case System.DayOfWeek.Friday:
                                weeklyHrs.FridayHours += totalHours;
                                weeklyHrs.FridayMins  += totalMins;
                                break;

                            default:
                                weeklyHrs.SaturdayHours += totalHours;
                                weeklyHrs.SaturdayMins  += totalMins;
                                break;
                            }
                        }
                    }
                }


                if (selMonthDt == null)
                {
                    weeklyViewModel.SelectedDate = fnGetLastMonthLastWeekSunDate();                     // Start on Sunday.
                }
                else
                {
                    weeklyViewModel.SelectedDate = selDt;
                }

                //weeklyViewModel.u = _userProfile;


                //WeeklyHrs = weeklyHrsList;
                weeklyViewModel.WeeklyHrs = weeklyHrsList;
                return(View(weeklyViewModel));
            }
            else
            {
                ErrorViewModel EVM = new ErrorViewModel();

                return(View(EVM));
            }
        }
 public Task <ListCollectionPage <Analytics> > GetPreviousItemsAsync(ListCollectionPage <Analytics> listCollectionPage)
 {
     throw new NotImplementedException();
 }
Example #23
0
        public async Task <ListCollectionPage <TeamHours> > GetNextItemsAsync(ListCollectionPage <TeamHours> listCollectionPage)
        {
            try
            {
                // Try fetching the data from cache
                listCollectionPage.CurrentPageIndex++;
                var cacheKey   = listCollectionPage.CurrentPageIndex.ToString() + "_" + listCollectionPage.ObjectIdentifier + listCollectionPage.QueryDate;
                var cacheEntry = await _teamHoursCache.TryRetrieveFromCacheAsync(listCollectionPage, cacheKey);

                if (cacheEntry != null)
                {
                    return(cacheEntry);
                }
                if (String.IsNullOrEmpty(listCollectionPage.SkipToken))
                {
                    return(null);                                                    // No more entries TODO: process not submitted
                }
                // TeamHours entry not in cache
                listCollectionPage.DataList = new List <TeamHours>();

                // Get all Team hours for the date if not in memory
                if (_teamHoursDataList?.Count == 0)
                {
                    var teamHoursResults = await _graphSharePointService.GetSiteListItemsAsync(listCollectionPage.SiteList, listCollectionPage.QueryDate);

                    foreach (var teamHoursItem in teamHoursResults)
                    {
                        var teamHoursFields = ConvertToTeamHours(teamHoursItem);

                        var userInfo = await _graphUserService.GetUserBasicAsync(teamHoursFields.ObjectIdentifier);

                        teamHoursFields.DisplayName = userInfo.DisplayName ?? "";

                        _teamHoursDataList.Add(new TeamHours
                        {
                            Id     = teamHoursItem.Id,
                            ListId = listCollectionPage.SiteList.ListId,
                            Fields = teamHoursFields
                        });
                    }
                }

                // Call graph for direct reports next page
                var directReports = await _graphUserService.GetUserDirectReportsAsync(listCollectionPage.ObjectIdentifier, listCollectionPage.SkipToken, listCollectionPage.PageSize);

                listCollectionPage.SkipToken = directReports.SkipToken;


                var teamHoursDataList = new List <TeamHours>();
                foreach (var item in directReports.DataList)
                {
                    var teamHoursId = String.Empty;

                    var teamHoursFields = new TeamHoursFields
                    {
                        ObjectIdentifier   = item.Id,
                        Date               = listCollectionPage.QueryDate,
                        ItemState          = ItemState.NotSubmitted,
                        TeamHoursItemState = ItemState.NotSubmitted
                    };

                    foreach (var teamHoursItem in _teamHoursDataList)
                    {
                        if (teamHoursItem.Fields.ObjectIdentifier == item.Id)
                        {
                            teamHoursId     = teamHoursItem.Id;
                            teamHoursFields = teamHoursItem.Fields;
                        }
                    }

                    if (String.IsNullOrEmpty(teamHoursFields.DisplayName))
                    {
                        var userInfo = await _graphUserService.GetUserBasicAsync(teamHoursFields.ObjectIdentifier);

                        teamHoursFields.DisplayName = userInfo.DisplayName ?? "";
                    }

                    teamHoursDataList.Add(new TeamHours
                    {
                        Id     = teamHoursId,
                        ListId = listCollectionPage.SiteList.ListId,
                        Fields = teamHoursFields
                    });
                }

                listCollectionPage.DataList = teamHoursDataList;

                // Save to cache
                await _teamHoursCache.SaveToCacheAsync(listCollectionPage, cacheKey);

                return(listCollectionPage);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting team hour items in repository: " + ex.Message);
                throw;
            }
        }
        public async Task <MyMonthlyHoursViewModel> GetViewModel(DateTime dt, int pageIndex = 1, int pageSize = 10)
        {
            var ci = System.Threading.Thread.CurrentThread.CurrentCulture;

            try
            {
                if (_listCollectionPage == null)
                {
                    _listCollectionPage = await _reportHoursRepository.GetItemsAsync(dt, pageSize);
                }

                // Check to see if a new date is being requested
                if (_listCollectionPage.QueryDate != dt.ToString("yyyyMM"))
                {
                    _listCollectionPage = await _reportHoursRepository.GetItemsAsync(dt, pageSize);
                }

                if ((pageIndex - _listCollectionPage.CurrentPageIndex) == 1)
                {
                    // Move next
                    _listCollectionPage = await _reportHoursRepository.GetNextItemsAsync(_listCollectionPage);
                }
                else if ((_listCollectionPage.CurrentPageIndex - pageIndex) == 1)
                {
                    // Move previous
                    _listCollectionPage = await _reportHoursRepository.GetPreviousItemsAsync(_listCollectionPage);
                }
                else
                {
                    // Other page
                    //_listCollectionPage = await _reportHoursRepository.GetPageItemsAsync(_listCollectionPage, pageIndex);
                }

                // Create the DataTable
                MyMonthlyHoursDataTableData dataTableData = new MyMonthlyHoursDataTableData(); // This is the MonthlyHoursListData.

                List <MonthlyHoursListData> mh = new List <MonthlyHoursListData>();

                // Get an array tagging each item of the month with the Week number
                int[] dateWeekNumber = this.GetDayOfMonthWeekAssignmentArray(dt);

                //var monthlyHrsList = new List<MonthlyHours>();

                // variables to compute total hours per week.
                int week1TotHrs    = 0;
                int week1TotMins   = 0;
                int week2TotHrs    = 0;
                int week2TotMins   = 0;
                int week3TotHrs    = 0;
                int week3TotMins   = 0;
                int week4TotHrs    = 0;
                int week4TotMins   = 0;
                int week5TotHrs    = 0;
                int week5TotMins   = 0;
                int monthTotalHrs  = 0;
                int monthTotalMins = 0;

                // Populate MonthlyHoursList
                // Group Monthly Report hours by individual User data using DisplayName
                var groupings = from item in _listCollectionPage.DataList
                                group item by item.Fields.DisplayName into data

                                select data.Distinct();

                //var monthlyHours = new MonthlyHours();
                // Process the data for each user

                foreach (var grouping in groupings)
                {
                    var thisGrouping = new MonthlyHoursListData();

                    //logic for handling duplicate records coming for the IW
                    var count    = grouping.Count();
                    var noOfDays = DateTime.DaysInMonth(dt.Year, dt.Month);
                    int diff     = 0;
                    if (count > noOfDays)
                    {
                        diff = count - noOfDays;
                    }

                    var reportHoursforIW = grouping.Skip(diff);

                    // Compute the total for each week of the month by processing daily records
                    foreach (var item in reportHoursforIW)
                    {
                        thisGrouping.EmpName     = item.Fields.DisplayName.ToString();
                        thisGrouping.ManagerName = item.Fields.ManagerDisplayName.ToString();

                        var itemDate = DateTime.ParseExact(item.Fields.Date, "yyyyMMdd", ci);

                        ConcurrentDictionary <string, short> hrsMins = new ConcurrentDictionary <string, short>();

                        //call to get Final hours for ReportHours Repository data
                        hrsMins = HoursComputeHelper.GetFinalHrsMins(item);
                        var totalHours = hrsMins["FinalTotalHrs"];
                        var totalMins  = hrsMins["FinalTotalMins"];

                        if ((itemDate.Day - 1) < DateTime.DaysInMonth(dt.Year, dt.Month))
                        {
                            var theWeekNumber = dateWeekNumber[itemDate.Day - 1];

                            switch (dateWeekNumber[itemDate.Day - 1])
                            {
                            case 1:
                                week1TotHrs  += totalHours;
                                week1TotMins += totalMins;
                                break;

                            case 2:
                                week2TotHrs  += totalHours;
                                week2TotMins += totalMins;
                                break;

                            case 3:

                                week3TotHrs  += totalHours;
                                week3TotMins += totalMins;
                                break;

                            case 4:

                                week4TotHrs  += totalHours;
                                week4TotMins += totalMins;
                                break;

                            case 5:

                                week5TotHrs  += totalHours;
                                week5TotMins += totalMins;
                                break;
                            }
                        }
                        else
                        {
                            week5TotHrs  += totalHours;
                            week5TotMins += totalMins;
                        }
                    }

                    //Logic to adjust values 60 min = hrs++
                    week1TotHrs    = (week1TotHrs + (week1TotMins / 60));
                    week1TotMins   = (week1TotMins % 60);
                    week2TotHrs    = (week2TotHrs + (week2TotMins / 60));
                    week2TotMins   = (week2TotMins % 60);
                    week3TotHrs    = (week3TotHrs + (week3TotMins / 60));
                    week3TotMins   = (week3TotMins % 60);
                    week4TotHrs    = (week4TotHrs + (week4TotMins / 60));
                    week4TotMins   = (week4TotMins % 60);
                    week5TotHrs    = (week5TotHrs + (week5TotMins / 60));
                    week5TotMins   = (week5TotMins % 60);
                    monthTotalMins = (week1TotMins + week2TotMins + week3TotMins + week4TotMins + week5TotMins);
                    monthTotalHrs  = (week1TotHrs + week2TotHrs + week3TotHrs + week4TotHrs + week5TotHrs) + (monthTotalMins / 60);
                    monthTotalMins = monthTotalMins % 60;

                    // Create display string.
                    var week1TotalHrMns = week1TotHrs + "h " + week1TotMins + "m";
                    var week2TotalHrMns = week2TotHrs + "h " + week2TotMins + "m";
                    var week3TotalHrMns = week3TotHrs + "h " + week3TotMins + "m";
                    var week4TotalHrMns = week4TotHrs + "h " + week4TotMins + "m";
                    var week5TotalHrMns = week5TotHrs + "h " + week5TotMins + "m";
                    //var monthlyTotalHrMns = monthTotalHrs + "h " + monthTotalMins + "m";

                    thisGrouping.Week1TotalHrMns = week1TotalHrMns;
                    thisGrouping.Week2TotalHrMns = week2TotalHrMns;
                    thisGrouping.Week3TotalHrMns = week3TotalHrMns;
                    thisGrouping.Week4TotalHrMns = week4TotalHrMns;
                    thisGrouping.Week5TotalHrMns = week5TotalHrMns;
                    //thisGrouping.MonthlyTotalHrMns = monthlyTotalHrMns;


                    monthTotalMins = (week1TotMins + week2TotMins + week3TotMins + week4TotMins + week5TotMins);
                    monthTotalHrs  = (week1TotHrs + week2TotHrs + week3TotHrs + week4TotHrs + week5TotHrs) + (monthTotalMins / 60);
                    monthTotalMins = monthTotalMins % 60;
                    var monthlyTotalHrMns = monthTotalHrs + "h " + monthTotalMins + "m";

                    thisGrouping.MonthlyTotalHrMns = monthlyTotalHrMns;

                    //Add the computed object(for each employee) to the list of monthly hours for the HR
                    mh.Add(thisGrouping);

                    // initializing the values to 0 for the next employee
                    week1TotHrs  = 0;
                    week1TotMins = 0;
                    week2TotHrs  = 0;
                    week2TotMins = 0;
                    week3TotHrs  = 0;
                    week3TotMins = 0;
                    week4TotHrs  = 0;
                    week4TotMins = 0;
                    week5TotHrs  = 0;
                    week5TotMins = 0;
                } // end for each grouping.

                //dataTableData.draw = draw;
                dataTableData.recordsTotal = (pageIndex * pageSize) + mh.Count + 1;
                int recordsFiltered = (pageIndex * pageSize) + mh.Count + 1;

                dataTableData.recordsFiltered = recordsFiltered;
                dataTableData.Data            = mh;

                var monthlyHoursViewModel = new MyMonthlyHoursViewModel
                {
                    MyMonthlyHoursDataTableData = dataTableData,
                    RequestRevision             = "is-disabled",
                    PaginationInfo = new PaginationInfoViewModel
                    {
                        CurrentPage = pageIndex,
                        PageSize    = pageSize,
                        Next        = "is-disabled",
                        Previous    = "is-disabled"
                    }
                };

                return(monthlyHoursViewModel);
            }
            catch (Exception ex)
            {
                return(new MyMonthlyHoursViewModel());
            }
        }
        public async Task <TeamHoursViewModel> GetViewModel(DateTime date, int pageIndex = 1, int pageSize = 10)
        {
            var  ci            = System.Threading.Thread.CurrentThread.CurrentCulture;
            bool userSubmitted = false;
            bool mgrSubmitted  = false;
            bool submitToHR    = false;

            try
            {
                if (_listCollectionPage == null)
                {
                    _listCollectionPage = await _teamHoursRepository.GetItemsAsync(date, pageSize);
                }

                // Exit from search
                //if (!String.IsNullOrEmpty(_listCollectionPage.SearchQuery)) _listCollectionPage = await _teamHoursRepository.GetItemsAsync(date, pageSize);

                // Check to see if a new date is being requested
                if (_listCollectionPage.QueryDate != date.ToString("yyyyMM"))
                {
                    _listCollectionPage = await _teamHoursRepository.GetItemsAsync(date, pageSize);
                }

                if ((pageIndex - _listCollectionPage.CurrentPageIndex) == 1)
                {
                    // Move next
                    _listCollectionPage = await _teamHoursRepository.GetNextItemsAsync(_listCollectionPage);
                }
                else if ((_listCollectionPage.CurrentPageIndex - pageIndex) == 1)
                {
                    // Move previous
                    _listCollectionPage = await _teamHoursRepository.GetPreviousItemsAsync(_listCollectionPage);
                }
                else if (pageIndex > 2)  // Increment until we find the correct page.
                {
                    while (_listCollectionPage.CurrentPageIndex < pageIndex)
                    {
                        _listCollectionPage = await _teamHoursRepository.GetNextItemsAsync(_listCollectionPage);
                    }
                }
                //var saveResults = await _graphSharePointService.CreateSiteListItemAsync(analyticsSiteList, dailyOTHoursRootObject.ToString());
                // Create the DataTable
                MyTeamDataTableData dataTableData = new MyTeamDataTableData();

                List <TeamHoursListData> th = new List <TeamHoursListData>();
                foreach (var item in _listCollectionPage.DataList)
                {
                    var computedHours = item.Fields.EmailHours + item.Fields.MeetingHours + item.Fields.OtherHours +
                                        ((item.Fields.EmailMinutes + item.Fields.MeetingMinutes + item.Fields.OtherMinutes) / 60);
                    var computedMinutes = (item.Fields.EmailMinutes + item.Fields.MeetingMinutes + item.Fields.OtherMinutes) % 60;

                    /*
                     *                  var AdjustedHours = item.Fields.EmailAdjustedHours + item.Fields.MeetingAdjustedHours + item.Fields.OtherAdjustedHours +
                     *                  ((item.Fields.EmailAdjustedMinutes + item.Fields.MeetingAdjustedMinutes + item.Fields.OtherAdjustedMinutes) / 60);
                     *                  var AdjustedMinutes = (item.Fields.EmailAdjustedMinutes + item.Fields.MeetingAdjustedMinutes + item.Fields.OtherAdjustedMinutes) % 60;
                     */
                    ConcurrentDictionary <string, short> hrsMins = new ConcurrentDictionary <string, short>();

                    //call to get Final hours for ReportHours Repository data
                    hrsMins = HoursComputeHelper.GetFinalTeamHrsMins(item);
                    var AdjustedHours   = hrsMins["FinalTotalHrs"];
                    var AdjustedMinutes = hrsMins["FinalTotalMins"];

                    string status      = "";
                    string actionLinks = "";
                    if (item.Fields.TeamHoursItemState.ToString() == ItemState.Submitted.ToString())
                    {
                        mgrSubmitted = true;
                        status       = item.Fields.ItemState.ToString();
                        actionLinks += "<span class='recheckHrs icon-noaction'> <i class='ms-Icon ms-Icon--DelveAnalytics font20' title='Request Revision'></i></span>";
                    }
                    else if (item.Fields.ItemState.ToString() == ItemState.Submitted.ToString())
                    {
                        userSubmitted = true;
                        status        = item.Fields.ItemState.ToString();
                        actionLinks  += "<span class='recheckHrs'> <i class='ms-Icon ms-Icon--DelveAnalytics font20 Pointer' title='Request Revision'></i></span>";
                    }
                    else if (item.Fields.ItemState.ToString() == ItemState.RequiresRevision.ToString())
                    {
                        status       = "Requires Revision";
                        actionLinks += "<span class='recheckHrs icon-noaction'> <i class='ms-Icon ms-Icon--DelveAnalytics font20' title='Request Revision'></i></span>";
                    }
                    else if (item.Fields.ItemState.ToString() == ItemState.NotSubmitted.ToString())
                    {
                        status       = "Not Submitted";
                        actionLinks += "<span class='recheckHrs icon-noaction'> <i class='ms-Icon ms-Icon--DelveAnalytics font20' title='Request Revision'></i></span>";
                    }
                    else if (item.Fields.ItemState.ToString() == ItemState.SubmittedBySystem.ToString())
                    {
                        userSubmitted = true;
                        status        = "Submitted By System";
                        actionLinks  += "<span class='recheckHrs'> <i class='ms-Icon ms-Icon--DelveAnalytics font20 Pointer' title='Request Revision'></i></span>";
                    }
                    else
                    {
                        status       = item.Fields.ItemState.ToString();
                        actionLinks += "<span class='recheckHrs icon-noaction'> <i class='ms-Icon ms-Icon--DelveAnalytics font20' title='Request Revision'></i></span>";
                    }

                    if (userSubmitted && !mgrSubmitted)  // Enable Submit Button.
                    {
                        submitToHR = true;
                    }

                    // reset the 2 local variables - never reset submitToHR.
                    userSubmitted = false;
                    mgrSubmitted  = false;

                    var t = new TeamHoursListData
                    {
                        Name             = item.Fields.DisplayName,
                        ComputedHours    = computedHours + "h " + computedMinutes + "m",
                        AdjustedHours    = AdjustedHours + "h " + AdjustedMinutes + "m",
                        ObjectIdentifier = item.Fields.ObjectIdentifier,
                        Status           = status,
                        Action           = actionLinks,
                        Id            = item.Id,
                        Date          = item.Fields.Date,
                        SubmittedDate = item.Fields.TeamHoursSubmittedDate
                    };
                    th.Add(t);
                }

                dataTableData.recordsTotal = (pageIndex * pageSize) + th.Count + 1;
                int recordsFiltered = (pageIndex * pageSize) + th.Count + 1;

                dataTableData.recordsFiltered = recordsFiltered;
                dataTableData.data            = th;
                dataTableData.SubmittedDate   = (dataTableData.data.Exists(x => x.SubmittedDate != DateTime.MinValue) ? dataTableData.data.FirstOrDefault().SubmittedDate.ToShortDateString() : DateTime.MinValue.ToShortDateString());
                //dataTableData.SubmitEnable = (dataTableData.data.Exists(x => x.SubmittedDate == DateTime.MinValue) ? true : false);
                dataTableData.SubmitEnable = (dataTableData.data.Exists(x => x.Status == ItemState.Submitted.ToString()) ? true : false);
                dataTableData.SubmitToHR   = submitToHR;

                var teamHoursViewModel = new TeamHoursViewModel
                {
                    MyTeamDataTableData = dataTableData,
                    RequestRevision     = "is-disabled",
                    EditTeamHours       = "is-disabled",
                };

                return(teamHoursViewModel);
            }
            catch (Exception ex)
            {
                return(new TeamHoursViewModel());
            }
        }
        private async Task <string> SubmitHoursAsync(IEnumerable <WorkHours> workHoursToSubmit, string userObjectIdentifier, GraphResultItem managerOfUser)
        {
            var completedSubmit = String.Empty;

            if (workHoursToSubmit == null)
            {
                throw new ArgumentNullException(nameof(workHoursToSubmit));
            }
            var workHoursToSubmitList = workHoursToSubmit.ToList();

            if (workHoursToSubmitList?.Count == 0)
            {
                return(completedSubmit);                                   // Nothing to do
            }
            if (String.IsNullOrEmpty(userObjectIdentifier))
            {
                return(completedSubmit);                                            // Nothing to do
            }
            var workHoursListCollectionPage = new ListCollectionPage <WorkHours>();
            var teamHoursSiteList           = new SiteList();

            if (managerOfUser == null)
            {
                // Skip manager by passing report hours identifier as manager identifier and handling that when building the models for the report by setting the manager display name to blank
                managerOfUser = new GraphResultItem
                {
                    Id          = "",
                    DisplayName = ""
                };

                teamHoursSiteList = await _graphSharePointService.GetSiteListAsync("entries", ListSchema.ReportHoursListSchema);
            }

            var managerObjectIdentifier = managerOfUser.Id;

            // Get the SpSiteList, if the list does not exists, it will create one
            var workHoursSiteList = workHoursListCollectionPage.SiteList;

            if (String.IsNullOrEmpty(workHoursSiteList.ListId))
            {
                workHoursSiteList = await _graphSharePointService.GetSiteListAsync(userObjectIdentifier, ListSchema.WorkHoursListSchema);
            }
            if (!String.IsNullOrEmpty(managerObjectIdentifier))
            {
                teamHoursSiteList = await _graphSharePointService.GetSiteListAsync(managerObjectIdentifier, ListSchema.TeamHoursListSchema);
            }

            var teamHoursRow         = new TeamHours();
            var submittedDate        = DateTime.Now;
            var hasRequestedRevision = false;
            var workHoursDate        = DateTime.Now;

            foreach (var workHours in workHoursToSubmit)
            {
                // Only count not submitted and requieres revision
                if (workHours.Fields.ItemState == ItemState.NotSubmitted || workHours.Fields.ItemState == ItemState.RequiresRevision)
                {
                    //Update the workHoursDate so we can assamble the message of the notification
                    workHoursDate = DateTime.ParseExact(workHours.Fields.Date, "yyyyMMdd", CultureInfo.InvariantCulture);

                    // To track if there is an entry that has a requiered revision
                    if (!hasRequestedRevision && workHours.Fields.ItemState == ItemState.RequiresRevision)
                    {
                        hasRequestedRevision = true;
                    }

                    teamHoursRow.Fields.Date             = workHours.Fields.Date;
                    teamHoursRow.Fields.ObjectIdentifier = workHours.Fields.ObjectIdentifier;

                    teamHoursRow.Fields.MeetingHours   += workHours.Fields.MeetingHours;
                    teamHoursRow.Fields.MeetingMinutes += workHours.Fields.MeetingMinutes;

                    if (workHours.Fields.MeetingAdjustedHours != 0 || workHours.Fields.MeetingAdjustedMinutes != 0)
                    {
                        teamHoursRow.Fields.MeetingAdjustedHours   += workHours.Fields.MeetingAdjustedHours;
                        teamHoursRow.Fields.MeetingAdjustedMinutes += workHours.Fields.MeetingAdjustedMinutes;
                    }
                    else
                    {
                        teamHoursRow.Fields.MeetingAdjustedHours   += workHours.Fields.MeetingHours;
                        teamHoursRow.Fields.MeetingAdjustedMinutes += workHours.Fields.MeetingMinutes;
                    }

                    teamHoursRow.Fields.EmailHours   += workHours.Fields.EmailHours;
                    teamHoursRow.Fields.EmailMinutes += workHours.Fields.EmailMinutes;

                    if (workHours.Fields.EmailAdjustedHours != 0 || workHours.Fields.EmailAdjustedMinutes != 0)
                    {
                        teamHoursRow.Fields.EmailAdjustedHours   += workHours.Fields.EmailAdjustedHours;
                        teamHoursRow.Fields.EmailAdjustedMinutes += workHours.Fields.EmailAdjustedMinutes;
                    }
                    else
                    {
                        teamHoursRow.Fields.EmailAdjustedHours   += workHours.Fields.EmailHours;
                        teamHoursRow.Fields.EmailAdjustedMinutes += workHours.Fields.EmailMinutes;
                    }

                    teamHoursRow.Fields.OtherHours   += workHours.Fields.OtherHours;
                    teamHoursRow.Fields.OtherMinutes += workHours.Fields.OtherMinutes;

                    if (workHours.Fields.OtherAdjustedHours != 0 || workHours.Fields.OtherAdjustedMinutes != 0)
                    {
                        teamHoursRow.Fields.OtherAdjustedHours   += workHours.Fields.OtherAdjustedHours;
                        teamHoursRow.Fields.OtherAdjustedMinutes += workHours.Fields.OtherAdjustedMinutes;
                    }
                    else
                    {
                        teamHoursRow.Fields.OtherAdjustedHours   += workHours.Fields.OtherHours;
                        teamHoursRow.Fields.OtherAdjustedMinutes += workHours.Fields.OtherMinutes;
                    }

                    teamHoursRow.Fields.TeamHoursItemState = ItemState.NotSubmitted;
                    teamHoursRow.Fields.ItemState          = ItemState.Submitted;
                    teamHoursRow.Fields.SubmittedDate      = submittedDate;

                    // Create JSON object to update WORK HOURS (aka employee entries) in SharePoint
                    dynamic workHoursFieldsObject = new JObject();
                    if (String.IsNullOrEmpty(managerObjectIdentifier))
                    {
                        // Skip submit to manager and send to HR since user does not has manager
                        workHoursFieldsObject.TeamHoursItemState     = ItemState.Submitted.ToString();
                        workHoursFieldsObject.TeamHoursSubmittedDate = submittedDate;
                    }
                    workHoursFieldsObject.ItemState     = ItemState.Submitted.ToString();
                    workHoursFieldsObject.SubmittedDate = submittedDate;

                    dynamic workHoursRootObject = new JObject();
                    workHoursRootObject.fields = workHoursFieldsObject;

                    // Update List Item in WorkHours List
                    await _graphSharePointService.UpdateSiteListItemAsync(workHoursSiteList, workHours.Id, workHoursRootObject.ToString());
                }
            }

            if (teamHoursRow.Fields.ObjectIdentifier != null)
            {
                // Adjust minutes to hours due the sum (above)
                var timeSpan = new TimeSpan(teamHoursRow.Fields.MeetingHours, teamHoursRow.Fields.MeetingMinutes, 0);
                teamHoursRow.Fields.MeetingHours   = Convert.ToInt16(timeSpan.Hours + (timeSpan.Days * 24));
                teamHoursRow.Fields.MeetingMinutes = Convert.ToInt16(timeSpan.Minutes);

                timeSpan = new TimeSpan(teamHoursRow.Fields.MeetingAdjustedHours, teamHoursRow.Fields.MeetingAdjustedMinutes, 0);
                teamHoursRow.Fields.MeetingAdjustedHours   = Convert.ToInt16(timeSpan.Hours + (timeSpan.Days * 24));
                teamHoursRow.Fields.MeetingAdjustedMinutes = Convert.ToInt16(timeSpan.Minutes);

                timeSpan = new TimeSpan(teamHoursRow.Fields.EmailHours, teamHoursRow.Fields.EmailMinutes, 0);
                teamHoursRow.Fields.EmailHours   = Convert.ToInt16(timeSpan.Hours + (timeSpan.Days * 24));
                teamHoursRow.Fields.EmailMinutes = Convert.ToInt16(timeSpan.Minutes);

                timeSpan = new TimeSpan(teamHoursRow.Fields.EmailAdjustedHours, teamHoursRow.Fields.EmailAdjustedMinutes, 0);
                teamHoursRow.Fields.EmailAdjustedHours   = Convert.ToInt16(timeSpan.Hours + (timeSpan.Days * 24));
                teamHoursRow.Fields.EmailAdjustedMinutes = Convert.ToInt16(timeSpan.Minutes);

                timeSpan = new TimeSpan(teamHoursRow.Fields.OtherHours, teamHoursRow.Fields.OtherMinutes, 0);
                teamHoursRow.Fields.OtherHours   = Convert.ToInt16(timeSpan.Hours + (timeSpan.Days * 24));
                teamHoursRow.Fields.OtherMinutes = Convert.ToInt16(timeSpan.Minutes);

                timeSpan = new TimeSpan(teamHoursRow.Fields.OtherAdjustedHours, teamHoursRow.Fields.OtherAdjustedMinutes, 0);
                teamHoursRow.Fields.OtherAdjustedHours   = Convert.ToInt16(timeSpan.Hours + (timeSpan.Days * 24));
                teamHoursRow.Fields.OtherAdjustedMinutes = Convert.ToInt16(timeSpan.Minutes);


                // Create JSON object to add a new list item in team Hours list in SharePoint
                dynamic teamHoursFieldsObject = new JObject();
                teamHoursFieldsObject.ObjectIdentifier       = teamHoursRow.Fields.ObjectIdentifier;
                teamHoursFieldsObject.Date                   = teamHoursRow.Fields.Date;
                teamHoursFieldsObject.MeetingHours           = teamHoursRow.Fields.MeetingHours;
                teamHoursFieldsObject.MeetingMinutes         = teamHoursRow.Fields.MeetingMinutes;
                teamHoursFieldsObject.MeetingAdjustedHours   = teamHoursRow.Fields.MeetingAdjustedHours;
                teamHoursFieldsObject.MeetingAdjustedMinutes = teamHoursRow.Fields.MeetingAdjustedMinutes;
                teamHoursFieldsObject.EmailHours             = teamHoursRow.Fields.EmailHours;
                teamHoursFieldsObject.EmailMinutes           = teamHoursRow.Fields.EmailMinutes;
                teamHoursFieldsObject.EmailAdjustedHours     = teamHoursRow.Fields.EmailAdjustedHours;
                teamHoursFieldsObject.EmailAdjustedMinutes   = teamHoursRow.Fields.EmailAdjustedMinutes;
                teamHoursFieldsObject.OtherHours             = teamHoursRow.Fields.OtherHours;
                teamHoursFieldsObject.OtherMinutes           = teamHoursRow.Fields.OtherMinutes;
                teamHoursFieldsObject.OtherAdjustedHours     = teamHoursRow.Fields.OtherAdjustedHours;
                teamHoursFieldsObject.OtherAdjustedMinutes   = teamHoursRow.Fields.OtherAdjustedMinutes;
                teamHoursFieldsObject.AdjustedHoursReason    = "" + teamHoursRow.Fields.AdjustedHoursReason;
                if (String.IsNullOrEmpty(managerObjectIdentifier))
                {
                    // Skip submit to manager and send to HR since user does not has manager
                    teamHoursFieldsObject.TeamHoursItemState     = ItemState.Submitted.ToString();
                    teamHoursFieldsObject.TeamHoursSubmittedDate = submittedDate;
                }
                else
                {
                    teamHoursFieldsObject.TeamHoursItemState = teamHoursRow.Fields.TeamHoursItemState.ToString();
                }
                teamHoursFieldsObject.ItemState     = teamHoursRow.Fields.ItemState.ToString();
                teamHoursFieldsObject.SubmittedDate = teamHoursRow.Fields.SubmittedDate;

                dynamic teamHoursRootObject = new JObject();
                teamHoursRootObject.fields = teamHoursFieldsObject;

                // If submit is not due to a request revision, create team hours entry otherwise we only update the existing one
                if (hasRequestedRevision)
                {
                    // Update existing team hours entry (this is the case for requesting revision)
                    List <QueryOption> options = new List <QueryOption>();
                    options.Add(new QueryOption("filter", @"startswith(fields/Date,'" + teamHoursRow.Fields.Date + "') and startswith(fields/ObjectIdentifier,'" + teamHoursRow.Fields.ObjectIdentifier + "')"));

                    var teamHoursResults = await _graphSharePointService.GetSiteListItemsAsync(teamHoursSiteList, options);

                    var updateResults = await _graphSharePointService.UpdateSiteListItemAsync(teamHoursSiteList, teamHoursResults[0].Id, teamHoursRootObject.ToString());
                }
                else
                {
                    // Create List Item in TeamHours list
                    var createResults = await _graphSharePointService.CreateSiteListItemAsync(teamHoursSiteList, teamHoursRootObject.ToString());
                }

                completedSubmit = "OK";


                // Create notification and send email
                //var messageBody = _workflowServiceHelper.ComposeMessageBody(NotificationType.SubmitWorkHours, workHoursDate);
                //await _workflowServiceHelper.SendNotificationAsync(managerOfUser, NotificationType.SubmitWorkHours, messageBody);

                return(completedSubmit);
            }

            return("Nothing to Submit");
        }
 public Task <ListCollectionPage <WorkHours> > GetPageItemsAsync(ListCollectionPage <WorkHours> listCollectionPage, int page)
 {
     throw new NotImplementedException();
 }
Example #28
0
        public async Task <ListCollectionPage <TeamHours> > GetSearchResultsAsync(DateTime date, string searchQuery, int pageSize = 10)
        {
            try
            {
                if (String.IsNullOrEmpty(searchQuery))
                {
                    return(await GetItemsAsync(date, pageSize));
                }

                // Set the cap for search results
                var searchMaxResults = 100;

                var siteList = new SiteList();

                // Get the user object identifier
                var userObjectIdentifier = _userContext.User.FindFirst(AzureAdAuthenticationBuilderExtensions.ObjectIdentifierType)?.Value;

                // Try fetching the first cache entry
                var cacheKey           = "1_" + userObjectIdentifier + date.ToString("yyyyMM");
                var listCollectionPage = new ListCollectionPage <TeamHours>();
                var cacheEntry         = await _teamHoursCache.TryRetrieveFromCacheAsync(listCollectionPage, cacheKey);

                if (cacheEntry != null && cacheEntry.SearchQuery != searchQuery && !String.IsNullOrEmpty(cacheEntry.SearchQuery))
                {
                    // Different search so clear cache to start new search
                    await _teamHoursCache.ClearCacheAsync("_" + userObjectIdentifier + date.ToString("yyyyMM"));

                    cacheEntry = null;
                }

                var teamHoursList = new List <TeamHours>();

                // Search for matches in entries from cache and add to teamHoursList
                string lowerSearchQuery = searchQuery.ToLowerInvariant();
                var    cacheIndex       = 1;
                while (cacheEntry != null)
                {
                    siteList = cacheEntry.SiteList;
                    cacheIndex++;
                    teamHoursList.AddRange(cacheEntry.DataList.Select(x => x).Where(s => s.Fields.DisplayName.ToLowerInvariant().Contains(lowerSearchQuery)));
                    cacheKey   = cacheIndex.ToString() + "_" + userObjectIdentifier + date.ToString("yyyyMM");
                    cacheEntry = await _teamHoursCache.TryRetrieveFromCacheAsync(listCollectionPage, cacheKey);
                }

                // At least 1 entry found in cache, keep getting next until we have 50 search results or there are no more records
                if (cacheIndex > 1)
                {
                    // Get last cache entry
                    cacheIndex--;
                    cacheKey   = cacheIndex.ToString() + "_" + userObjectIdentifier + date.ToString("yyyyMM");
                    cacheEntry = await _teamHoursCache.TryRetrieveFromCacheAsync(listCollectionPage, cacheKey);
                }

                var nextItems = cacheEntry;
                if (nextItems == null && teamHoursList?.Count == 0)
                {
                    nextItems = await GetItemsResultsAsync(date, pageSize, searchQuery);

                    teamHoursList.AddRange(nextItems.DataList.Select(x => x).Where(s => s.Fields.DisplayName.ToLowerInvariant().Contains(lowerSearchQuery)));
                    siteList = nextItems.SiteList;
                }

                while (!String.IsNullOrEmpty(nextItems.SkipToken) && teamHoursList?.Count < searchMaxResults)
                {
                    nextItems = await GetNextItemsAsync(cacheEntry);

                    siteList = nextItems.SiteList;
                    teamHoursList.AddRange(nextItems.DataList.Select(x => x).Where(s => s.Fields.DisplayName.ToLowerInvariant().Contains(lowerSearchQuery)));
                }

                // Re-create the cache with the search results
                if (teamHoursList?.Count > 0)
                {
                    // First clear cache
                    await _teamHoursCache.ClearCacheAsync("_" + userObjectIdentifier + date.ToString("yyyyMM"));

                    listCollectionPage                  = new ListCollectionPage <TeamHours>();
                    listCollectionPage.QueryDate        = date.ToString("yyyyMM");
                    listCollectionPage.ObjectIdentifier = userObjectIdentifier;
                    listCollectionPage.CurrentPageIndex = 1;
                    listCollectionPage.PageSize         = pageSize;
                    listCollectionPage.SearchQuery      = searchQuery;
                    listCollectionPage.SiteList         = siteList;
                    listCollectionPage.DataList         = new List <TeamHours>();

                    var pageSizeCounter = 0;
                    foreach (var item in teamHoursList)
                    {
                        if (!String.IsNullOrEmpty(item.Fields.ObjectIdentifier)) // Avoid failing when TeamHours list is corrupt
                        {
                            listCollectionPage.DataList.Add(item);
                            pageSizeCounter++;
                            if (pageSizeCounter == pageSize || pageSizeCounter == teamHoursList.Count)
                            {
                                cacheKey = listCollectionPage.CurrentPageIndex.ToString() + "_" + userObjectIdentifier + date.ToString("yyyyMM");
                                await _teamHoursCache.SaveToCacheAsync(listCollectionPage, cacheKey);

                                listCollectionPage.CurrentPageIndex++;
                            }
                        }
                        else
                        {
                            _logger.LogWarning("TeamHours List contains a record with empty ObjectIdentifier");
                        }
                    }

                    cacheKey = "1_" + userObjectIdentifier + date.ToString("yyyyMM");
                    return(await _teamHoursCache.TryRetrieveFromCacheAsync(listCollectionPage, cacheKey));
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting team hour items in repository: " + ex.Message);
                throw;
            }
        }
Example #29
0
 public async Task <ListCollectionPage <UserProfile> > GetPageItemsAsync(ListCollectionPage <UserProfile> listCollectionPage, int page)
 {
     throw new NotImplementedException();
 }
Example #30
0
        // Private methods

        private async Task <ListCollectionPage <TeamHours> > GetItemsResultsAsync(DateTime date, int pageSize, string searchQuery = "")
        {
            try
            {
                // Get the user object identifier
                var userObjectIdentifier = _userContext.User.FindFirst(AzureAdAuthenticationBuilderExtensions.ObjectIdentifierType)?.Value;

                // Prepare call to graph to fetch teamhours records from SharePoint

                var listCollectionPage = new ListCollectionPage <TeamHours>();
                listCollectionPage.QueryDate        = date.ToString("yyyyMM");
                listCollectionPage.ObjectIdentifier = userObjectIdentifier;
                listCollectionPage.CurrentPageIndex = 1;
                listCollectionPage.PageSize         = pageSize;
                listCollectionPage.SearchQuery      = searchQuery;
                listCollectionPage.SiteList         = await _graphSharePointService.GetSiteListAsync(userObjectIdentifier, ListSchema.TeamHoursListSchema);

                // Get the direct reports of the manager (paged)
                var directReports = await _graphUserService.GetUserDirectReportsAsync(userObjectIdentifier, String.Empty, pageSize);

                listCollectionPage.SkipToken = directReports.SkipToken;

                // Get all Team hours for the date
                if (_teamHoursDataList?.Count == 0 || _teamHoursDataList[0].Fields.Date != date.ToString("yyyyMM"))
                {
                    var teamHoursResults = await _graphSharePointService.GetSiteListItemsAsync(listCollectionPage.SiteList, date.ToString("yyyyMM"));

                    foreach (var teamHoursItem in teamHoursResults)
                    {
                        var teamHoursFields = ConvertToTeamHours(teamHoursItem);

                        var userInfo = await _graphUserService.GetUserBasicAsync(teamHoursFields.ObjectIdentifier);

                        teamHoursFields.DisplayName = userInfo.DisplayName ?? "";

                        _teamHoursDataList.Add(new TeamHours
                        {
                            Id     = teamHoursItem.Id,
                            ListId = listCollectionPage.SiteList.ListId,
                            Fields = teamHoursFields
                        });
                    }
                }

                var teamHoursDataList = new List <TeamHours>();
                foreach (var item in directReports.DataList)
                {
                    var teamHoursId = String.Empty;

                    var teamHoursFields = new TeamHoursFields
                    {
                        ObjectIdentifier   = item.Id,
                        Date               = date.ToString("yyyyMM"),
                        ItemState          = ItemState.NotSubmitted,
                        TeamHoursItemState = ItemState.NotSubmitted
                    };

                    foreach (var teamHoursItem in _teamHoursDataList)
                    {
                        if (teamHoursItem.Fields.ObjectIdentifier == item.Id)
                        {
                            teamHoursId     = teamHoursItem.Id;
                            teamHoursFields = teamHoursItem.Fields;
                        }
                    }

                    if (String.IsNullOrEmpty(teamHoursFields.DisplayName))
                    {
                        var userInfo = await _graphUserService.GetUserBasicAsync(teamHoursFields.ObjectIdentifier);

                        teamHoursFields.DisplayName = userInfo.DisplayName ?? "";
                    }

                    teamHoursDataList.Add(new TeamHours
                    {
                        Id     = teamHoursId,
                        ListId = listCollectionPage.SiteList.ListId,
                        Fields = teamHoursFields
                    });
                }

                listCollectionPage.DataList = teamHoursDataList;

                return(listCollectionPage);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting team hour items in repository: " + ex.Message);
                throw;
            }
        }