namespace IOL.GreatOffice.Api.Endpoints.V1.Entries; public class CreateEntryRoute : RouteBaseSync.WithRequest.WithActionResult { private readonly AppDbContext _context; public CreateEntryRoute(AppDbContext context) { _context = context; } /// /// Create a time entry. /// /// /// [ApiVersion(ApiSpecV1.VERSION_STRING)] [BasicAuthentication(AppConstants.TOKEN_ALLOW_CREATE)] [ProducesResponseType(200)] [ProducesResponseType(400, Type = typeof(ErrorResult))] [ProducesResponseType(404, Type = typeof(ErrorResult))] [HttpPost("~/v{version:apiVersion}/entries/create")] public override ActionResult Handle(TimeEntry.TimeEntryDto timeEntryTimeEntryDto) { if (timeEntryTimeEntryDto.Stop == default) { return BadRequest(new ErrorResult("Invalid form", "A stop date is required")); } if (timeEntryTimeEntryDto.Start == default) { return BadRequest(new ErrorResult("Invalid form", "A start date is required")); } if (timeEntryTimeEntryDto.Category == default) { return BadRequest(new ErrorResult("Invalid form", "A category is required")); } var category = _context.TimeCategories .Where(c => c.UserId == LoggedInUser.Id) .SingleOrDefault(c => c.Id == timeEntryTimeEntryDto.Category.Id); if (category == default) { return NotFound(new ErrorResult("Not found", $"Could not find category {timeEntryTimeEntryDto.Category.Name}")); } var entry = new TimeEntry(LoggedInUser.Id) { Category = category, Start = timeEntryTimeEntryDto.Start.ToUniversalTime(), Stop = timeEntryTimeEntryDto.Stop.ToUniversalTime(), Description = timeEntryTimeEntryDto.Description, }; if (timeEntryTimeEntryDto.Labels?.Count > 0) { var labels = _context.TimeLabels .Where(c => c.UserId == LoggedInUser.Id) .Where(c => timeEntryTimeEntryDto.Labels.Select(p => p.Id).Contains(c.Id)) .ToList(); if (labels.Count != timeEntryTimeEntryDto.Labels.Count) { return NotFound(new ErrorResult("Not found", "Could not find all of the specified labels")); } entry.Labels = labels; } _context.TimeEntries.Add(entry); _context.SaveChanges(); return Ok(entry.AsDto); } }