public async Task <ActionResult <TimesheetDTO> > PostTimesheet(TimesheetDTO timesheet) { var user = await _userManager.FindByNameAsync(User?.Identity?.Name); if (user != null) { timesheet.UserId = user.Id; } var isTimesheetForValidMonth = !_context.Timesheet.Any(t => t.Date.Year.Equals(timesheet.Date.Year) && t.Date.Month.Equals(timesheet.Date.Month) && t.UserId.Equals(user.Id)); if (!isTimesheetForValidMonth) { return(BadRequest(new { Message = "Timesheet for selected month already exists!" })); } var timesheetObj = DtoToModel.DtoToTimesheet(timesheet); var validStates = States.GetStatesValues(); if (!validStates.Contains(timesheet.State)) { return(BadRequest("Provided status does not exist!")); } await _context.Timesheet.AddAsync(timesheetObj); await _context.SaveChangesAsync(); var dto = ModelToDto.TimesheetToDto(timesheetObj); return(CreatedAtAction("GetTimesheet", new { id = timesheet.Id }, dto)); }
public static TimesheetDTO TimesheetToDto(Timesheet timesheet) { var rows = RowsCollectionToDto(timesheet.Rows); var timesheetDto = new TimesheetDTO { Date = timesheet.Date, Id = timesheet.Id, Rows = rows, UserId = timesheet.UserId, State = timesheet.State }; return(timesheetDto); }
private static double TimesheetDtoToSummaryNetAmount(TimesheetDTO dto, ICollection <UserRateAmount> rateAmounts) { var output = (from row in dto.Rows let hoursCount = row.Days.Sum(day => day.ReportedHours) let netPrice = rateAmounts.First(amount => amount.RateTypeId.Equals(row.RateTypeId)) .RateAmount select Math.Round(hoursCount * netPrice, 2)).Sum(); return(output); }
public async Task <ActionResult> ModifyTimesheetRecord([FromBody] TimesheetDTO timesheet) { if (TimesheetRecordExists(timesheet.RecordID)) { // Call BLL TimesheetRecord Modify method with all the parameters object BLLResponse = new TimesheetBLL(_context).ModifyTimesheetRecordBLL(timesheetModRecord: timesheet, userClaims: User); if (BLLResponse.GetType().BaseType == typeof(Exception)) { // Create log entries for Debug log ((APIException)BLLResponse).Exceptions.ForEach(ex => Logger.Msg <TimesheetsController>((Exception)ex, Serilog.Events.LogEventLevel.Debug)); // Return response from API return(BadRequest(new { errors = ((APIException)BLLResponse).Exceptions.Select(x => x.Message).ToArray() })); } else { try { TimesheetDTO modTimesheet = (TimesheetDTO)BLLResponse; // Find the existing record based on ID Timesheet currentRecord = _context.Timesheets.Where(x => x.RecordID == modTimesheet.RecordID).First(); // Modify the record currentRecord.AssignmentID = modTimesheet.AssignmentID; currentRecord.StartTime = modTimesheet.StartTime; currentRecord.EndTime = modTimesheet.EndTime; currentRecord.TimeAllocation = modTimesheet.TimeAllocation; // Save changes await _context.SaveChangesAsync(); Logger.Msg <TimesheetsController>($"[{User.FindFirstValue("email")}] [MODIFY] RecordID: {currentRecord.RecordID} successful", Serilog.Events.LogEventLevel.Information); // Return modified record as a DTO TimesheetDTO response = new TimesheetDTO(currentRecord); return(Ok(response)); } catch (Exception ex) { // Local log entry. Database reconciliation issues are more serious so reported as Error Logger.Msg <TimesheetsController>($"[MODIFY] Database sync error {ex.Message}", Serilog.Events.LogEventLevel.Error); // Return response to client return(StatusCode(500, new { errors = "Database update failed. Contact the administrator to resolve this issue." })); } } } else { return(NotFound()); } } // End of ModifyTimesheetRecord
private TimesheetDTO CreateMockTimesheetDTO() { var dto = new TimesheetDTO { Id = 1, State = States.Open, UserId = _sampleUserId, Date = _sampleDate, Rows = CreateMockRowDtos() }; return(dto); }
} // End of GetTimesheetRecordBLL /// <summary> /// Business logic for processing Timesheet record addition /// </summary> /// <param name="timesheetRecord"></param> /// <param name="userClaims"></param> /// <returns></returns> internal object AddTimesheetRecordBLL(TimesheetDTO timesheetRecord, ClaimsPrincipal userClaims) { // Check if the current user is a staff member (or Super Admin) bool isUserStaff = userClaims.IsInRole("Staff") || userClaims.IsInRole("SuperAdmin"); // Get the StudentID of the currrent user (or 0) int currentStudentID = isUserStaff ? 0 : _context.Users.Where(x => x.Email == userClaims.FindFirstValue("email")).Include(users => users.StudentData).FirstOrDefault()?.StudentData.StudentID ?? 0; if (timesheetRecord.StudentID == 0 && !isUserStaff) { timesheetRecord.StudentID = currentStudentID; } // Create a new APIException object to store possible exceptions as checks are performed. APIException exceptionList = new APIException(); Dictionary <string, bool> exceptionTests = new Dictionary <string, bool>() { { "Specified StudentID does not exist", !_context.Students.Any(x => x.StudentID == timesheetRecord.StudentID) }, { "StudentID cannot differ from the authenticated user", !(timesheetRecord.StudentID == currentStudentID || isUserStaff) }, { "Student account matching the StudentID must be active", !(_context.Students.Where(x => x.StudentID == timesheetRecord.StudentID).Include(student => student.UserData).FirstOrDefault().UserData.Active || isUserStaff) }, { "Specified AssignmentID does not exist", !_context.Tasks.Any(x => x.TaskID == timesheetRecord.AssignmentID) }, { "Specified date is older than 7 days", ((DateTime.Today - timesheetRecord.Date).Days > 7) && !isUserStaff }, { "Specified date cannot be in the future", !(timesheetRecord.Date <= DateTime.Today) }, { "TimeAllocation has to be a positive number, or zero", !(timesheetRecord.TimeAllocation >= 0) }, { "TimeAllocation has to be less than or equal to 18h", !(timesheetRecord.TimeAllocation <= 18) } // { "Only one record per AssignmentID per date is allowed", _context.Timesheets.Any(x => x.Date == timesheetRecord.Date && x.AssignmentID == timesheetRecord.AssignmentID && x.StudentID == timesheetRecord.StudentID) } }; foreach (KeyValuePair <string, bool> kvp in exceptionTests) { if (kvp.Value) { exceptionList.AddExMessage(kvp.Key); } } if (!exceptionList.HasExceptions) { // Round the TimeAlllocation to 15 min (0.25h) // Ref: https://stackoverflow.com/a/2826278/12802214 timesheetRecord.TimeAllocation = Math.Round(timesheetRecord.TimeAllocation * 4, MidpointRounding.AwayFromZero) / 4; return(timesheetRecord); } else { return(exceptionList); } } // End of AddTimesheetRecordBLL
public void setPoint(TimesheetDTO timesheetObject) { string dateTimeInString = commonMethods.convertDateTimeInDbFormatString(timesheetObject.getDateTime()); try { db.connect(); string sql = "INSERT INTO timesheet (timesheet_id, timesheet_employee_id, dateTime, timesheet_type_id) VALUES (NULL, " + timesheetObject.getTimesheetEmployeeId() + ", '" + dateTimeInString + "', " + timesheetObject.getTimesheetTypeId() + ");"; db.executeSql(sql); } catch (Exception ex) { MessageBox.Show("Erro ao tentar inserir o token: " + ex.Message.ToString()); } }
public async Task <ActionResult> AddTimesheetRecord(TimesheetDTO timesheetRecord) { // Call BLL Task Add method with all the parameters object BLLResponse = new TimesheetBLL(_context).AddTimesheetRecordBLL(timesheetRecord: timesheetRecord, userClaims: User); if (BLLResponse.GetType().BaseType == typeof(Exception)) { // Create log entries for Debug log ((APIException)BLLResponse).Exceptions.ForEach(ex => Logger.Msg <TimesheetsController>((Exception)ex, Serilog.Events.LogEventLevel.Debug)); // Return response from API return(BadRequest(new { errors = ((APIException)BLLResponse).Exceptions.Select(x => x.Message).ToArray() })); } else { try { TimesheetDTO newTimesheetDTO = (TimesheetDTO)BLLResponse; Timesheet newTimesheet = new Timesheet { StudentID = newTimesheetDTO.StudentID, AssignmentID = newTimesheetDTO.AssignmentID, Date = newTimesheetDTO.Date, StartTime = newTimesheetDTO.StartTime, EndTime = newTimesheetDTO.EndTime, TimeAllocation = newTimesheetDTO.TimeAllocation }; _context.Timesheets.Add(newTimesheet); await _context.SaveChangesAsync(); Logger.Msg <TimesheetsController>($"[{User.FindFirstValue("email")}] [ADD] Timesheet '{newTimesheet.RecordID}' successful", Serilog.Events.LogEventLevel.Information); // Convert back to DTO and return to user TimesheetDTO response = new TimesheetDTO(newTimesheet); return(Ok(response)); } catch (Exception ex) { // Local log entry. Database reconciliation issues are more serious so reported as Error Logger.Msg <TimesheetsController>($"[ADD] Database sync error {ex.Message}", Serilog.Events.LogEventLevel.Error); // Return response to client return(StatusCode(500, new { errors = "Database update failed. Contact the administrator to resolve this issue." })); } } } // End of AddTimesheetRecord
public static Timesheet DtoToTimesheet(TimesheetDTO dto) { var rows = DtosToRows(dto.Rows); var timesheet = new Timesheet { Id = dto.Id, Date = dto.Date, State = dto.State, UserId = dto.UserId, Rows = new List <Row>() }; rows.ForAll(row => timesheet.Rows.Add(row)); return(timesheet); }
private static ICollection <InvoiceItemDTO> TimesheetDtoToInvoiceItemDtos(TimesheetDTO dto, ICollection <RateType> rateTypes, ICollection <UserRateAmount> rateAmounts) { return((from row in dto.Rows let hoursCount = row.Days.Sum(day => day.ReportedHours) let netPrice = rateAmounts.First(amount => amount.RateTypeId.Equals(row.RateTypeId)).RateAmount let netAmount = hoursCount * netPrice select new InvoiceItemDTO() { Title = rateTypes.First(type => type.Id.Equals(row.RateTypeId)).DisplayName, Count = hoursCount.ToString(CultureInfo.InvariantCulture), GrossAmount = Math.Round(netAmount * 1.23, 2).ToString(CultureInfo.InvariantCulture), NetAmount = Math.Round(netAmount, 2).ToString(CultureInfo.InvariantCulture), Metric = "godzina", NetPrice = netPrice.ToString(CultureInfo.InvariantCulture), TaxAmount = Math.Round(netAmount * 0.23, 2).ToString(CultureInfo.InvariantCulture), TaxRate = "23%" }).ToList()); }
private void button1_Click(object sender, EventArgs e) { if (comboBoxPointType.SelectedItem == null) { MessageBox.Show("É necessário, primeiro, selecionar um tipo.", "ALERTA", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { int timesheetTypeId = comboBoxPointType.SelectedIndex + 1; TimesheetDTO newTimesheet = new TimesheetDTO(); newTimesheet.setTimesheetEmployeeId(employeeId); newTimesheet.setDateTime(DateTime.Now); newTimesheet.setTimesheetTypeId(timesheetTypeId); timesheetRepository.setPoint(newTimesheet); this.buildTimesheetTable(); } }
public async Task <IActionResult> PutTimesheet(int id, TimesheetDTO timesheet) { if (id != timesheet.Id) { return(BadRequest()); } var currentUser = await _userManager.FindByNameAsync(User?.Identity?.Name); var isCorrectUser = _context.Timesheet.AsNoTracking().Any(t => t.Id == id && t.UserId == currentUser.Id); if (!isCorrectUser) { return(Forbid()); } var timesheetObj = DtoToModel.DtoToTimesheet(timesheet); var validStates = States.GetStatesValues(); if (!validStates.Contains(timesheet.State)) { return(BadRequest()); } var isModificationAllowed = _context.Timesheet.AsNoTracking().First(t => t.Id.Equals(id)).State != States.Closed; if (!isModificationAllowed) { return(BadRequest()); } // new Rows var newRows = timesheetObj.Rows.Where(row => row.Id.Equals(0)); foreach (var newRow in newRows) { await _context.Row.AddAsync(newRow); } // edited Rows var oldRows = timesheetObj.Rows.Where(row => row.Id > 0); foreach (var oldRow in oldRows) { _context.Entry(oldRow).State = EntityState.Modified; } // main entity _context.Entry(timesheetObj).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TimesheetExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }