public async Task <WorkEntry> CreateAsync(WorkEntry workEntry)
        {
            if (workEntry.HoursSpent <= 0 || workEntry.HoursSpent > 24)
            {
                throw new ArgumentOutOfRangeException(nameof(workEntry.HoursSpent));
            }

            if (workEntry.Id == Guid.Empty)
            {
                workEntry.Id = Guid.NewGuid();
            }

            if (string.IsNullOrWhiteSpace(workEntry.UserId) || !_userContextAccessor.IsAdminUser())
            {
                workEntry.UserId = _userContextAccessor.GetUserId();
            }

            try
            {
                _dbContext.Add(workEntry);
                await _dbContext.SaveChangesAsync().ConfigureAwait(false);

                return(workEntry);
            }
            catch (DbUpdateException e)
            {
                if (_dbErrorHandler.IsDuplicateKeyError(e, "UserId", "Date"))
                {
                    throw new ArgumentException($"Duplicate entry for date {workEntry.Date:yyyy-MM-dd}");
                }

                throw;
            }
        }
        public async Task UpdateAsync_AnotherUser_ReturnsNull(bool isAdmin, bool isNullResult)
        {
            // Arrange
            using var dbContext = CreateDbContext();
            var user = await CreateTestUserAsync(dbContext);

            var anotherUser = await CreateTestUserAsync(dbContext);

            var userContextAccessorMock = new Mock <IUserContextAccessor>();

            userContextAccessorMock.Setup(m => m.GetUserId()).Returns(user.Id);
            userContextAccessorMock.Setup(m => m.IsAdminUser()).Returns(isAdmin);

            var workEntriesService = new WorkEntriesService(dbContext, Mock.Of <IDbErrorHandler>(), userContextAccessorMock.Object);
            var entry = await CreateWorkEntry(dbContext, anotherUser.Id);

            // Act
            var entryToUpdate = new WorkEntry
            {
                Id         = entry.Id,
                Date       = new DateTime(2021, 1, 1),
                HoursSpent = 6,
                Notes      = "Some notes..."
            };

            entry = await workEntriesService.UpdateAsync(entryToUpdate);

            Assert.Equal(isNullResult, entry == null);
        }
        public async Task UpdateAsync_EntryDoesNotExists_ReturnsNull()
        {
            // Arrange
            using var dbContext = CreateDbContext();
            var user = await CreateTestUserAsync(dbContext);

            var userContextAccessorMock = new Mock <IUserContextAccessor>();

            userContextAccessorMock.Setup(m => m.GetUserId()).Returns(user.Id);
            userContextAccessorMock.Setup(m => m.IsAdminUser()).Returns(false);

            var workEntriesService = new WorkEntriesService(dbContext, Mock.Of <IDbErrorHandler>(), userContextAccessorMock.Object);

            // Act
            var entryToUpdate = new WorkEntry
            {
                Id         = Guid.NewGuid(),
                Date       = new DateTime(2021, 1, 1),
                HoursSpent = 6,
                UserId     = user.Id + "1",
                Notes      = "Some notes..."
            };

            var entry = await workEntriesService.UpdateAsync(entryToUpdate);

            Assert.Null(entry);
        }
        public async Task CreateAsync_ExplicitUserId(bool isAdmin, string currentUserId, string createdByUserId, string expectedEntryUserId)
        {
            // Arrange
            using var dbContext = CreateDbContext();

            var userContextAccessorMock = new Mock <IUserContextAccessor>();

            userContextAccessorMock.Setup(m => m.GetUserId()).Returns(currentUserId);
            userContextAccessorMock.Setup(m => m.IsAdminUser()).Returns(isAdmin);

            var workEntriesService = new WorkEntriesService(dbContext, Mock.Of <IDbErrorHandler>(), userContextAccessorMock.Object);

            // Act
            var entry = new WorkEntry
            {
                HoursSpent = 5,
                Date       = DateTime.Now.Date,
                Notes      = "Notes",
                UserId     = createdByUserId
            };

            entry = await workEntriesService.CreateAsync(entry);

            // Assert
            Assert.Equal(expectedEntryUserId, entry.UserId);
        }
Example #5
0
        /// <summary>
        /// Syncs the Jira entry with the work entry
        /// </summary>
        /// <param name="jEntry">Jira entry to update</param>
        /// <param name="wEntry">Work entry to update Jira with</param>
        /// <returns>True if updated successfully</returns>
        public bool SyncWorkEntry(JiraWorkEntry jEntry, WorkEntry wEntry)
        {
            jEntry.TimeSpent        = wEntry.TimeSpent;
            jEntry.TimeSpentSeconds = 0;

            Logger.DebugFormat("Syncronizing {0} in {1}", wEntry.TogglId, wEntry.IssueId);

            try
            {
                using (IHttpResponse response = GetResponse(() => GetWorkEntryRequest(jEntry, jEntry.Self, "PUT")))
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        EncounteredError = false;
                        WorkEntryUpdated?.Invoke(wEntry);
                        return(true);
                    }
                    else
                    {
                        EncounteredError = true;
                        WorkEntryUpdateFailed?.Invoke(wEntry);
                        Logger.WarnFormat("Didn't get the expected status code back when syncing a work entry for {0}. Got {1}", wEntry.IssueId, response.StatusCode);
                    }
                }
            }
            catch (WebException we)
            {
                EncounteredError = true;
                WorkEntryUpdateFailed?.Invoke(wEntry);
                Logger.Error("Unable to sync web entry", we);
            }

            return(false);
        }
        public async Task <WorkEntry> UpdateAsync(WorkEntry entry)
        {
            if (entry.HoursSpent <= 0 || entry.HoursSpent > 24)
            {
                throw new ArgumentOutOfRangeException(nameof(entry.HoursSpent));
            }

            if (entry is null)
            {
                throw new ArgumentNullException(nameof(entry));
            }

            var dbEntry = await GetByIdAsync(entry.Id).ConfigureAwait(false);

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

            dbEntry.Date       = entry.Date;
            dbEntry.Notes      = entry.Notes;
            dbEntry.HoursSpent = entry.HoursSpent;

            await _dbContext.SaveChangesAsync().ConfigureAwait(false);

            return(dbEntry);
        }
        public async Task CreateAsync_InitsEmptyFields()
        {
            // Arrange
            string testUserId = Guid.NewGuid().ToString();

            using var dbContext = CreateDbContext();

            var userContextAccessorMock = new Mock <IUserContextAccessor>();

            userContextAccessorMock.Setup(m => m.GetUserId()).Returns(testUserId);

            var workEntriesService = new WorkEntriesService(dbContext, Mock.Of <IDbErrorHandler>(), userContextAccessorMock.Object);

            // Act
            var entry = new WorkEntry
            {
                HoursSpent = 5,
                Date       = DateTime.Now.Date,
                Notes      = "Notes"
            };

            var createdEntry = await workEntriesService.CreateAsync(entry);

            // Assert
            Assert.NotEqual(Guid.Empty, createdEntry.Id);
            Assert.Equal(testUserId, createdEntry.UserId);
            Assert.Equal(entry.Date, createdEntry.Date);
            Assert.Equal(entry.Notes, createdEntry.Notes);
            Assert.Equal(entry.HoursSpent, createdEntry.HoursSpent);
        }
Example #8
0
        private void TestValid(string issueId, string comment, string seperator = ": ")
        {
            var entry = WorkEntry.Create(GetEntry($"{issueId}{seperator}{comment}"));

            Assert.IsNotNull(entry);
            Assert.AreEqual(issueId, entry.IssueId);
            Assert.AreEqual(comment, entry.Comment);
        }
 private static void AssertEqual(WorkEntry expected, WorkEntry actual)
 {
     Assert.Equal(expected.Id, actual.Id);
     Assert.Equal(expected.Date, actual.Date);
     Assert.Equal(expected.HoursSpent, actual.HoursSpent);
     Assert.Equal(expected.Notes, actual.Notes);
     Assert.Equal(expected.UserId, actual.UserId);
 }
Example #10
0
        public override WorkEntry ToWorkEntry()
        {
            WorkEntry entry = base.ToWorkEntry();

            entry.Id     = Id;
            entry.UserId = UserId;

            return(entry);
        }
 private async void HandleSelectedItem()
 {
     if (SelectedEntry != null)
     {
         string name = SelectedEntry.Name;
         _selectedEntry = null;
         await Navigation.PushAsync(new EditBookEntries(NewBook, name));
     }
 }
        public void SetWorkEntry(WorkEntry entry)
        {
            CurrentEntry = entry;
            lbl_ClientTrackerUser.Content = entry.User.FirstName + " " + entry.User.LastName;
            lbl_DateTime.Content = entry.StartTime.ToString("g");
            lbl_WorkType.Content = entry.TypeOfWorkDone.ToString();
            lbl_Duration.Content = Math.Round(entry.TimeWorked.TotalMinutes, 2).ToString() + " minutes";

            txtBox_Notes.Text = entry.Notes;
        }
Example #13
0
        public async Task Update(int id, WorkEntry newValue)
        {
            if (!this.Exists(id))
            {
                throw new KeyNotFoundException();
            }
            var entity = await _context.WorkEntries.FirstOrDefaultAsync(w => w.Id == id);

            entity = newValue;
            _context.WorkEntries.Update(entity);
        }
		public object Deserialize(JsonValue json, JsonMapper mapper)
		{
			WorkEntry entry = null;
			if ( json != null && !json.IsNull )
			{
				entry = new WorkEntry();
				entry.StartDate = json.ContainsName("start_date") ? json.GetValue<string>("start_date") : String.Empty;
				entry.EndDate   = json.ContainsName("end_date"  ) ? json.GetValue<string>("end_date"  ) : String.Empty;
				
				entry.Employer  = mapper.Deserialize<Reference>(json.GetValue("employer"));
			}
			return entry;
		}
Example #15
0
        public WorkEntryDto(WorkEntry workEntry)
        {
            if (workEntry is null)
            {
                throw new ArgumentNullException(nameof(workEntry));
            }

            Id         = workEntry.Id;
            Date       = workEntry.Date;
            HoursSpent = workEntry.HoursSpent;
            Notes      = workEntry.Notes;
            UserId     = workEntry.UserId;
        }
Example #16
0
        public WorkEntry ToWork()
        {
            WorkEntry e = new WorkEntry();

            e.Name        = Name;
            e.Description = Description;
            e.ImagePath   = ImagePath;
            foreach (Tag t in Tags)
            {
                e.Tags.Add(new WorkTag(t.Name, t.Value));
            }

            return(e);
        }
        public object Deserialize(JsonValue json, JsonMapper mapper)
        {
            WorkEntry entry = null;

            if (json != null && !json.IsNull)
            {
                entry           = new WorkEntry();
                entry.StartDate = json.ContainsName("start_date") ? json.GetValue <string>("start_date") : String.Empty;
                entry.EndDate   = json.ContainsName("end_date") ? json.GetValue <string>("end_date") : String.Empty;

                entry.Employer = mapper.Deserialize <Reference>(json.GetValue("employer"));
            }
            return(entry);
        }
        public NewEntryViewModel(INavigation navigation, WorkBook book)
        {
            Navigation    = navigation;
            NewBook       = book;
            NewEntry      = new WorkEntry();
            CurrentTags   = new ObservableCollection <WorkTag>();
            AddImage      = new Command(OnAddImage);
            AddTag        = new Command(OnAddTag);
            RemoveLastTag = new Command(OnRemoveLastTag);
            SaveEntry     = new Command(OnSaveEntry);
            DiscardEntry  = new Command(OnDiscardEntry);
            ToggleView    = new Command(OnToggleView);
            Return        = new Command(OnReturn);

            TagsVisible        = true;
            DescriptionVisible = false;
        }
        public ActionResult LogHours(WorkEntry entry)
        {
            if (entry.Hours > 0)
            {
                entry.UserName = UserModel.Current.UserName;
                entry.Logged   = DateTime.Now;

                _repositories.WorkEntries.Add(entry);
                _repositories.WorkEntries.SaveChanges();

                TempData["message"] = "Your hours have been logged and you have been successfully logged out.";
            }

            TempData["message"] = "You have been successfully logged out.";

            return(RedirectToAction("SignOut", "Account"));
        }
Example #20
0
        /// <summary>
        /// Adds the gived entry to the worklog of its issue
        /// </summary>
        /// <param name="wEntry">Worklog entry to add</param>
        /// <returns>True if added successfully</returns>
        public bool AddWorkEntry(WorkEntry wEntry)
        {
            JiraWorkEntry jEntry = new JiraWorkEntry
            {
                Started   = GetStartTime(wEntry),
                Comment   = wEntry.CommentWithMarker,
                TimeSpent = wEntry.TimeSpent
            };

            Logger.DebugFormat("Creating a entry for {0} corresponding to {1}.", wEntry.IssueId, wEntry.TogglId);
            HttpWebRequest request = GetRequest(string.Format(GetWorklogUrl, wEntry.IssueId), true);

            request.ContentType = "application/json;charset=UTF-8";
            request.Method      = "POST";

            try
            {
                WriteWorkEntry(jEntry, request);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode == HttpStatusCode.Created)
                    {
                        Logger.DebugFormat("Work entry created for issue {0}", wEntry.IssueId);
                        EncounteredError = false;
                        WorkEntryCreated?.Invoke(wEntry);
                        return(true);
                    }
                    else
                    {
                        WorkEntryCreationFailed?.Invoke(wEntry);
                        Logger.WarnFormat("Didn't get the expected status code back when creating a work entry for {0}. Got {1}", wEntry.IssueId, response.StatusCode);
                    }
                }
            }
            catch (WebException we)
            {
                WorkEntryCreationFailed?.Invoke(wEntry);
                Logger.Error("Unable add work entry", we);
            }

            EncounteredError = true;
            return(false);
        }
        private static async Task <WorkEntry> CreateWorkEntry(ApplicationDbContext dbContext, string createdBy, Action <WorkEntry> modifier = null)
        {
            var entry = new WorkEntry
            {
                Id         = Guid.NewGuid(),
                HoursSpent = 5,
                Date       = DateTime.Now.Date,
                Notes      = "Notes",
                UserId     = createdBy
            };

            if (modifier != null)
            {
                modifier(entry);
            }

            dbContext.Add(entry);
            await dbContext.SaveChangesAsync();

            return(entry);
        }
        public async Task UpdateAsync_EntryExists_UpdatesEntry()
        {
            // Arrange
            using var dbContext = CreateDbContext();
            var user = await CreateTestUserAsync(dbContext);

            var entry = await CreateWorkEntry(dbContext, user.Id);

            var userContextAccessorMock = new Mock <IUserContextAccessor>();

            userContextAccessorMock.Setup(m => m.GetUserId()).Returns(user.Id);
            userContextAccessorMock.Setup(m => m.IsAdminUser()).Returns(false);

            var workEntriesService = new WorkEntriesService(dbContext, Mock.Of <IDbErrorHandler>(), userContextAccessorMock.Object);

            // Act
            var entryToUpdate = new WorkEntry
            {
                Id         = entry.Id,
                Date       = new DateTime(2021, 1, 1),
                HoursSpent = 6,
                UserId     = user.Id + "1",
                Notes      = "Some notes..."
            };

            entry = await workEntriesService.UpdateAsync(entryToUpdate);

            Assert.NotEqual(entryToUpdate.UserId, entry.UserId);

            // Line above tests that a user can't update the UserId field.
            // Now assign the same user id to compare all properties of both objects,
            // otherwise assert will fail
            entryToUpdate.UserId = entry.UserId;
            AssertEqual(entryToUpdate, entry);

            // assert entry state directly in the database
            entry = await dbContext.WorkEntries.FindAsync(entry.Id);

            AssertEqual(entryToUpdate, entry);
        }
Example #23
0
        /// <summary>
        /// Syncs the Jira entry with the work entry
        /// </summary>
        /// <param name="jEntry">Jira entry to update</param>
        /// <param name="wEntry">Work entry to update Jira with</param>
        /// <returns>True if updated successfully</returns>
        public bool SyncWorkEntry(JiraWorkEntry jEntry, WorkEntry wEntry)
        {
            jEntry.TimeSpent        = wEntry.TimeSpent;
            jEntry.TimeSpentSeconds = 0;

            Logger.DebugFormat("Syncronizing {0} in {1}", wEntry.TogglId, wEntry.IssueId);
            HttpWebRequest request = GetRequest(jEntry.Self, false);

            request.ContentType = "application/json;charset=UTF-8";
            request.Method      = "PUT";

            try
            {
                WriteWorkEntry(jEntry, request);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        EncounteredError = false;
                        WorkEntryUpdated?.Invoke(wEntry);
                        return(true);
                    }
                    else
                    {
                        EncounteredError = true;
                        WorkEntryUpdateFailed?.Invoke(wEntry);
                        Logger.WarnFormat("Didn't get the expected status code back when syncing a work entry for {0}. Got {1}", wEntry.IssueId, response.StatusCode);
                    }
                }
            }
            catch (WebException we)
            {
                EncounteredError = true;
                WorkEntryUpdateFailed?.Invoke(wEntry);
                Logger.Error("Unable to sync web entry", we);
            }

            return(false);
        }
Example #24
0
        /// <summary>
        /// Adds the gived entry to the worklog of its issue
        /// </summary>
        /// <param name="wEntry">Worklog entry to add</param>
        /// <returns>True if added successfully</returns>
        public bool AddWorkEntry(WorkEntry wEntry)
        {
            JiraWorkEntry jEntry = new JiraWorkEntry
            {
                Started   = GetStartTime(wEntry),
                Comment   = wEntry.CommentWithMarker,
                TimeSpent = wEntry.TimeSpent
            };

            Logger.DebugFormat("Creating a entry for {0} corresponding to {1}.", wEntry.IssueId, wEntry.TogglId);


            try
            {
                using (IHttpResponse response = GetResponse(() => GetWorkEntryRequest(jEntry, ServerUrl + string.Format(GetWorklogUrl, wEntry.IssueId), "POST")))
                {
                    if (response.StatusCode == HttpStatusCode.Created)
                    {
                        Logger.DebugFormat("Work entry created for issue {0}", wEntry.IssueId);
                        EncounteredError = false;
                        WorkEntryCreated?.Invoke(wEntry);
                        return(true);
                    }
                    else
                    {
                        WorkEntryCreationFailed?.Invoke(wEntry);
                        Logger.WarnFormat("Didn't get the expected status code back when creating a work entry for {0}. Got {1}", wEntry.IssueId, response.StatusCode);
                    }
                }
            }
            catch (WebException we)
            {
                WorkEntryCreationFailed?.Invoke(wEntry);
                Logger.Error("Unable add work entry", we);
            }

            EncounteredError = true;
            return(false);
        }
Example #25
0
        public async Task <ActionResult> PostWorkingGroupSchedule([FromBody] WorkEntry workEntry)
        {
            try
            {
                await _workEntry.Add(workEntry);
            }
            catch (DbUpdateConcurrencyException e)
            {
                _logger.LogError(e.Message);
                return(Problem(e.Message));
            }
            catch (DbUpdateException e)
            {
                _logger.LogError(e.Message);
                return(Problem(e.Message));
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return(Problem(e.Message));
            }

            return(CreatedAtAction("PostWorkingDay", new { workEntry.Id, workEntry }));
        }
Example #26
0
 public void Create_NoDesc()
 {
     Assert.IsNull(WorkEntry.Create(GetEntry(null)));
 }
Example #27
0
 public void Create_NoDash()
 {
     Assert.IsNull(WorkEntry.Create(GetEntry("P12: Foo")));
 }
Example #28
0
 public void Create_LowerCaseLetterProj()
 {
     Assert.IsNull(WorkEntry.Create(GetEntry("p-1")));
 }
Example #29
0
 /// <summary>
 /// Returns a string containing the start time of the entry in a correct format for Jira
 /// </summary>
 /// <param name="wEntry">Entry to get start time from</param>
 /// <returns>Start time of the entry in a correctly formatted string</returns>
 private static string GetStartTime(WorkEntry wEntry)
 {
     return(wEntry.Start.ToString(TimeFormat) + wEntry.Start.ToString("zzz").Replace(":", ""));
 }
Example #30
0
 public async Task Add(WorkEntry toAdd)
 {
     _context.WorkEntries.Add(toAdd);
     await _context.SaveChangesAsync();
 }
Example #31
0
 public void Create_NoNumberWithDesc()
 {
     Assert.IsNull(WorkEntry.Create(GetEntry("P- Hello")));
 }
Example #32
0
 public void Create_NoNumber()
 {
     Assert.IsNull(WorkEntry.Create(GetEntry("P-")));
 }