diff --git a/src/deskstar-backend/Deskstar/Controllers/AuthController.cs b/src/deskstar-backend/Deskstar/Controllers/AuthController.cs index a97051f4..32222fb5 100644 --- a/src/deskstar-backend/Deskstar/Controllers/AuthController.cs +++ b/src/deskstar-backend/Deskstar/Controllers/AuthController.cs @@ -1,5 +1,4 @@ using Deskstar.Core.Exceptions; -using Deskstar.Entities; using Deskstar.Models; using Deskstar.Usecases; using Microsoft.AspNetCore.Authorization; @@ -12,9 +11,9 @@ namespace Deskstar.Controllers; [Produces("text/plain")] public class AuthController : ControllerBase { - private readonly ILogger _logger; private readonly IAuthUsecases _authUsecases; private readonly IConfiguration _configuration; + private readonly ILogger _logger; public AuthController(ILogger logger, IAuthUsecases authUsecases, IConfiguration configuration) { @@ -24,14 +23,13 @@ public AuthController(ILogger logger, IAuthUsecases authUsecases } /// - /// Login functionality + /// Login functionality /// /// JWT, if users is approved and psw is correct /// - /// Sample request: - /// Post /auth/createToken + /// Sample request: + /// Post /auth/createToken /// - /// /// Login succesful /// Credentials wrong or user not approved [HttpPost("createToken")] @@ -41,22 +39,18 @@ public AuthController(ILogger logger, IAuthUsecases authUsecases public IActionResult CreateToken(CreateTokenUser user) { var returnValue = _authUsecases.CheckCredentials(user.MailAddress, user.Password); - if (returnValue.Message == LoginReturn.Ok) - { - return Ok(_authUsecases.CreateToken(_configuration, user.MailAddress)); - } + if (returnValue.Message == LoginReturn.Ok) return Ok(_authUsecases.CreateToken(_configuration, user.MailAddress)); return Unauthorized(returnValue.Message.ToString()); } /// - /// Register functionality + /// Register functionality /// /// - /// Sample request: - /// Post /auth/register + /// Sample request: + /// Post /auth/register /// - /// /// User added to db /// Mail already in use /// Company not found @@ -75,14 +69,14 @@ public IActionResult Register(RegisterUser registerUser) _ => BadRequest(result.Message.ToString()) }; } + /// - /// Register functionality + /// Register functionality /// /// - /// Sample request: - /// Post /auth/registerAdmin + /// Sample request: + /// Post /auth/registerAdmin /// - /// /// Admin added to db /// Mail or Company name already in use [HttpPost("registerAdmin")] @@ -93,7 +87,8 @@ public IActionResult RegisterAdmin(RegisterAdminDto registerAdmin) { try { - var admin = _authUsecases.RegisterAdmin(registerAdmin.FirstName, registerAdmin.LastName, registerAdmin.MailAddress, registerAdmin.Password, registerAdmin.CompanyName); + var admin = _authUsecases.RegisterAdmin(registerAdmin.FirstName, registerAdmin.LastName, + registerAdmin.MailAddress, registerAdmin.Password, registerAdmin.CompanyName); return Ok(); } catch (ArgumentInvalidException e) @@ -102,7 +97,7 @@ public IActionResult RegisterAdmin(RegisterAdminDto registerAdmin) } catch (Exception e) { - return Problem(statusCode: 500, detail:e.Message); + return Problem(statusCode: 500, detail: e.Message); } } } diff --git a/src/deskstar-backend/Deskstar/Controllers/BookingController.cs b/src/deskstar-backend/Deskstar/Controllers/BookingController.cs index 2f3c99e6..9973384d 100644 --- a/src/deskstar-backend/Deskstar/Controllers/BookingController.cs +++ b/src/deskstar-backend/Deskstar/Controllers/BookingController.cs @@ -7,7 +7,9 @@ * * MIT License */ + using Deskstar.Core; +using Deskstar.Entities; using Deskstar.Models; using Deskstar.Usecases; using Microsoft.AspNetCore.Authorization; @@ -20,285 +22,276 @@ namespace Deskstar.Controllers; [Produces("application/json")] public class BookingController : ControllerBase { - private readonly IBookingUsecases _bookingUsecases; - private readonly ILogger _logger; - private readonly IAutoMapperConfiguration _autoMapperConfiguration; + private readonly IAutoMapperConfiguration _autoMapperConfiguration; + private readonly IBookingUsecases _bookingUsecases; + private readonly ILogger _logger; - public BookingController(ILogger logger, IBookingUsecases bookingUsecases, IAutoMapperConfiguration autoMapperConfiguration) - { - _logger = logger; - _bookingUsecases = bookingUsecases; - _autoMapperConfiguration = autoMapperConfiguration; - } + public BookingController(ILogger logger, IBookingUsecases bookingUsecases, + IAutoMapperConfiguration autoMapperConfiguration) + { + _logger = logger; + _bookingUsecases = bookingUsecases; + _autoMapperConfiguration = autoMapperConfiguration; + } - /// - /// Returns a paginated bookings ranging from a start to an end timestamp. - /// - /// A List of Bookings and the total amount of bookings for the user in JSON Format (can be empty) - /// - /// Sample request: - /// Get /bookings?n=100&skip=50&direction=DESC&from=1669021730904&end=1669121730904 with JWT Token - /// - /// - /// Returns the booking list and amounts of bookings of user - /// Bad Request - /// Internal Server Error - [HttpGet] - [Authorize] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult GetBookingsByDirection(int n = int.MaxValue, int skip = 0, string direction = "DESC", long start = 0, long end = 0) - { - var userId = RequestInteractions.ExtractIdFromRequest(Request); + /// + /// Returns a paginated bookings ranging from a start to an end timestamp. + /// + /// A List of Bookings and the total amount of bookings for the user in JSON Format (can be empty) + /// + /// Sample request: + /// Get /bookings?n=100&skip=50&direction=DESC&from=1669021730904&end=1669121730904 with JWT Token + /// + /// Returns the booking list and amounts of bookings of user + /// Bad Request + /// Internal Server Error + [HttpGet] + [Authorize] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult GetBookingsByDirection(int n = int.MaxValue, int skip = 0, string direction = "DESC", + long start = 0, long end = 0) + { + var userId = RequestInteractions.ExtractIdFromRequest(Request); - DateTime startDateTime; - DateTime endDateTime; + DateTime startDateTime; + DateTime endDateTime; - try - { - if (start == 0) - startDateTime = DateTime.Now; - else - startDateTime = DateTimeOffset.FromUnixTimeMilliseconds(start).DateTime; + try + { + if (start == 0) + startDateTime = DateTime.Now; + else + startDateTime = DateTimeOffset.FromUnixTimeMilliseconds(start).DateTime; - if (end == 0) - endDateTime = DateTime.MaxValue; - else - endDateTime = DateTimeOffset.FromUnixTimeMilliseconds(end).DateTime; + if (end == 0) + endDateTime = DateTime.MaxValue; + else + endDateTime = DateTimeOffset.FromUnixTimeMilliseconds(end).DateTime; - if (n < 0) - throw new FormatException("n must be greater than zero"); - if (skip < 0) - throw new FormatException("skip must be zero or greater"); - if (direction.ToUpper() != "ASC" && direction.ToUpper() != "DESC") - throw new FormatException("direction must either be 'ASC' or 'DESC'"); + if (n < 0) + throw new FormatException("n must be greater than zero"); + if (skip < 0) + throw new FormatException("skip must be zero or greater"); + if (direction.ToUpper() != "ASC" && direction.ToUpper() != "DESC") + throw new FormatException("direction must either be 'ASC' or 'DESC'"); - if (start > end) - { - var swap = end; - end = start; - start = swap; - } + if (start > end) + { + var swap = end; + end = start; + start = swap; + } + } + catch (FormatException e) + { + _logger.LogError(e, e.Message); + return BadRequest(e.Message); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return BadRequest(e.Message); + } - } - catch (FormatException e) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - try - { - var bookings = _bookingUsecases.GetFilteredBookings(userId, n, skip, direction, startDateTime, endDateTime); - var amountOfBookings = _bookingUsecases.CountValidBookings(userId, direction, startDateTime, endDateTime); + try + { + var bookings = _bookingUsecases.GetFilteredBookings(userId, n, skip, direction, startDateTime, endDateTime); + var amountOfBookings = _bookingUsecases.CountValidBookings(userId, direction, startDateTime, endDateTime); - var mapper = _autoMapperConfiguration.GetConfiguration().CreateMapper(); - var mapped = bookings.Select((b) => mapper.Map(b)).ToList(); + var mapper = _autoMapperConfiguration.GetConfiguration().CreateMapper(); + var mapped = bookings.Select(b => mapper.Map(b)).ToList(); - var paginated = new PaginatedBookingsDto - { - AmountOfBookings = amountOfBookings, - Bookings = mapped, - }; + var paginated = new PaginatedBookingsDto + { + AmountOfBookings = amountOfBookings, + Bookings = mapped + }; - return Ok(paginated); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } + return Ok(paginated); } - - - /// - /// Offers next ten Bookings for Token-User - /// - /// A List of Bookings in JSON Format (can be empty) - /// - /// Sample request: - /// Get /bookings/recent with JWT Token - /// - /// - /// Returns the booking list - /// User not found - [HttpGet("recent")] - [Authorize] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [Produces("application/json")] - public IActionResult RecentBookings() + catch (Exception e) { - var userId = RequestInteractions.ExtractIdFromRequest(Request); - try - { - var bookings = _bookingUsecases.GetRecentBookings(userId); - return Ok(bookings); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - } - return NotFound(); + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); } + } - /// - /// Creates a new Booking for Token-User - /// - /// Created Booking in JSON Format - /// - /// Sample request: - /// Post /bookings with JWT Token - /// - /// - /// Returns the created booking - /// User not found - /// Desk not found - /// Desk is not available at that time - /// Bad Request - - [HttpPost] - [Authorize] - [ProducesResponseType(StatusCodes.Status201Created)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status409Conflict)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [Produces("application/json")] - public IActionResult CreateBooking([FromBody] BookingRequest bookingRequest) + /// + /// Offers next ten Bookings for Token-User + /// + /// A List of Bookings in JSON Format (can be empty) + /// + /// Sample request: + /// Get /bookings/recent with JWT Token + /// + /// Returns the booking list + /// User not found + [HttpGet("recent")] + [Authorize] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [Produces("application/json")] + public IActionResult RecentBookings() + { + var userId = RequestInteractions.ExtractIdFromRequest(Request); + try { + var bookings = _bookingUsecases.GetRecentBookings(userId); + return Ok(bookings); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + } - if (bookingRequest.StartTime.Equals(DateTime.MinValue) || bookingRequest.EndTime.Equals(DateTime.MinValue) || bookingRequest.DeskId.Equals(Guid.Empty)) - { - return BadRequest("Required fields are missing"); - } + return NotFound(); + } - var userId = RequestInteractions.ExtractIdFromRequest(Request); - //ToDo: require Frontend to Use Universaltime - bookingRequest.StartTime = bookingRequest.StartTime.ToLocalTime(); - bookingRequest.EndTime = bookingRequest.EndTime.ToLocalTime(); + /// + /// Creates a new Booking for Token-User + /// + /// Created Booking in JSON Format + /// + /// Sample request: + /// Post /bookings with JWT Token + /// + /// Returns the created booking + /// User not found + /// Desk not found + /// Desk is not available at that time + /// Bad Request + [HttpPost] + [Authorize] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [Produces("application/json")] + public IActionResult CreateBooking([FromBody] BookingRequest bookingRequest) + { + if (bookingRequest.StartTime.Equals(DateTime.MinValue) || bookingRequest.EndTime.Equals(DateTime.MinValue) || + bookingRequest.DeskId.Equals(Guid.Empty)) return BadRequest("Required fields are missing"); - try - { - _bookingUsecases.CreateBooking(userId, bookingRequest); - return Ok(); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return e.Message switch - { - "User not found" => NotFound(e.Message), - "Desk not found" => NotFound(e.Message), - "Time slot not available" => Conflict(e.Message), - _ => Problem(statusCode: 500) - }; - } - } + var userId = RequestInteractions.ExtractIdFromRequest(Request); - /// - /// Deletes a Booking for Token-User - /// - /// Deleted Booking in JSON Format - /// - /// Sample request: - /// Delete /bookings/{bookingId} with JWT Token - /// - /// - /// Returns the deleted booking - /// User not found - /// Booking not found - /// User is not allowed to delete this booking - /// Bad Request - [HttpDelete("{bookingId}")] - [Authorize] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status403Forbidden)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [Produces("application/json")] + //ToDo: require Frontend to Use Universaltime + bookingRequest.StartTime = bookingRequest.StartTime.ToLocalTime(); + bookingRequest.EndTime = bookingRequest.EndTime.ToLocalTime(); - public IActionResult DeleteBooking(string bookingId) + try { - var userId = RequestInteractions.ExtractIdFromRequest(Request); - try - { - var booking = _bookingUsecases.DeleteBooking(userId, new Guid(bookingId)); - return Ok(booking); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return e.Message switch - { - "User not found" => NotFound(e.Message), - "Booking not found" => NotFound(e.Message), - "You are not allowed to delete this booking" => Forbid(e.Message), - _ => Problem(statusCode: 500) - }; - } + _bookingUsecases.CreateBooking(userId, bookingRequest); + return Ok(); } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return e.Message switch + { + "User not found" => NotFound(e.Message), + "Desk not found" => NotFound(e.Message), + "Time slot not available" => Conflict(e.Message), + _ => Problem(statusCode: 500) + }; + } + } - /// - /// Updates a Booking for Token-User - /// - /// Updated Booking in JSON Format - /// - /// Sample request: - /// Put /bookings/{bookingId} with JWT Token - /// - /// - /// Returns the updated booking - /// User not found - /// Booking not found - /// User is not allowed to update this booking - /// Desk is not available at that time - /// Bad Request - [HttpPut("{bookingId}")] - [Authorize] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status403Forbidden)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status409Conflict)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [Produces("application/json")] - public IActionResult UpdateBooking(string bookingId, [FromBody] UpdateBookingRequest updateBookingRequest) + /// + /// Deletes a Booking for Token-User + /// + /// Deleted Booking in JSON Format + /// + /// Sample request: + /// Delete /bookings/{bookingId} with JWT Token + /// + /// Returns the deleted booking + /// User not found + /// Booking not found + /// User is not allowed to delete this booking + /// Bad Request + [HttpDelete("{bookingId}")] + [Authorize] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [Produces("application/json")] + public IActionResult DeleteBooking(string bookingId) + { + var userId = RequestInteractions.ExtractIdFromRequest(Request); + try { - if (updateBookingRequest.StartTime.Equals(DateTime.MinValue) || updateBookingRequest.EndTime.Equals(DateTime.MinValue)) - { - return BadRequest("Required fields are missing"); - } + var booking = _bookingUsecases.DeleteBooking(userId, new Guid(bookingId)); + return Ok(booking); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return e.Message switch + { + "User not found" => NotFound(e.Message), + "Booking not found" => NotFound(e.Message), + "You are not allowed to delete this booking" => Forbid(e.Message), + _ => Problem(statusCode: 500) + }; + } + } + + /// + /// Updates a Booking for Token-User + /// + /// Updated Booking in JSON Format + /// + /// Sample request: + /// Put /bookings/{bookingId} with JWT Token + /// + /// Returns the updated booking + /// User not found + /// Booking not found + /// User is not allowed to update this booking + /// Desk is not available at that time + /// Bad Request + [HttpPut("{bookingId}")] + [Authorize] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [Produces("application/json")] + public IActionResult UpdateBooking(string bookingId, [FromBody] UpdateBookingRequest updateBookingRequest) + { + if (updateBookingRequest.StartTime.Equals(DateTime.MinValue) || + updateBookingRequest.EndTime.Equals(DateTime.MinValue)) return BadRequest("Required fields are missing"); - var userId = RequestInteractions.ExtractIdFromRequest(Request); + var userId = RequestInteractions.ExtractIdFromRequest(Request); - // ToDo: require Frontend to Use Universaltime - updateBookingRequest.StartTime = updateBookingRequest.StartTime.ToLocalTime(); - updateBookingRequest.EndTime = updateBookingRequest.EndTime.ToLocalTime(); + // ToDo: require Frontend to Use Universaltime + updateBookingRequest.StartTime = updateBookingRequest.StartTime.ToLocalTime(); + updateBookingRequest.EndTime = updateBookingRequest.EndTime.ToLocalTime(); - try - { - var booking = _bookingUsecases.UpdateBooking(userId, new Guid(bookingId), updateBookingRequest); - return Ok(); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return e.Message switch - { - "User not found" => NotFound(e.Message), - "Booking not found" => NotFound(e.Message), - "You are not allowed to update this booking" => Forbid(e.Message), - "Time slot not available" => Conflict(e.Message), - _ => Problem(statusCode: 500) - }; - } + try + { + var booking = _bookingUsecases.UpdateBooking(userId, new Guid(bookingId), updateBookingRequest); + return Ok(); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return e.Message switch + { + "User not found" => NotFound(e.Message), + "Booking not found" => NotFound(e.Message), + "You are not allowed to update this booking" => Forbid(e.Message), + "Time slot not available" => Conflict(e.Message), + _ => Problem(statusCode: 500) + }; } -} \ No newline at end of file + } +} diff --git a/src/deskstar-backend/Deskstar/Controllers/CompanyController.cs b/src/deskstar-backend/Deskstar/Controllers/CompanyController.cs index ebe33e06..1c4a849e 100644 --- a/src/deskstar-backend/Deskstar/Controllers/CompanyController.cs +++ b/src/deskstar-backend/Deskstar/Controllers/CompanyController.cs @@ -7,10 +7,9 @@ * * MIT License */ -using Deskstar.Core; + using Deskstar.Models; using Deskstar.Usecases; -using Deskstar.Entities; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -21,12 +20,13 @@ namespace Deskstar.Controllers; [Produces("application/json")] public class CompanyController : ControllerBase { + private readonly IAutoMapperConfiguration _autoMapperConfiguration; private readonly ICompanyUsecases _companyUsecases; private readonly ILogger _logger; - private readonly IAutoMapperConfiguration _autoMapperConfiguration; - public CompanyController(ILogger logger, ICompanyUsecases companyUsecases, IAutoMapperConfiguration autoMapperConfiguration) + public CompanyController(ILogger logger, ICompanyUsecases companyUsecases, + IAutoMapperConfiguration autoMapperConfiguration) { _logger = logger; _companyUsecases = companyUsecases; @@ -34,11 +34,11 @@ public CompanyController(ILogger logger, ICompanyUsecases com } /// - /// Get all companies + /// Get all companies /// /// A list of companies /// - /// Sample request: Get /companies + /// Sample request: Get /companies /// /// Returns a list of companies /// Internal Server Error diff --git a/src/deskstar-backend/Deskstar/Controllers/HealthCheckController.cs b/src/deskstar-backend/Deskstar/Controllers/HealthCheckController.cs index 77509c24..095ce8a9 100644 --- a/src/deskstar-backend/Deskstar/Controllers/HealthCheckController.cs +++ b/src/deskstar-backend/Deskstar/Controllers/HealthCheckController.cs @@ -8,31 +8,31 @@ namespace Deskstar.Controllers; [Produces("text/plain")] public class HealthCheckController : ControllerBase { - private readonly ILogger _logger; + private readonly ILogger _logger; - public HealthCheckController(ILogger logger) - { - _logger = logger; - } + public HealthCheckController(ILogger logger) + { + _logger = logger; + } - [HttpGet()] - [AllowAnonymous] - public string Get() - { - return "Hello World! We're live."; - } + [HttpGet] + [AllowAnonymous] + public string Get() + { + return "Hello World! We're live."; + } - [HttpGet("withToken")] - [Authorize] - public string Auth() - { - return "authenticated. We're live."; - } + [HttpGet("withToken")] + [Authorize] + public string Auth() + { + return "authenticated. We're live."; + } - [HttpGet("admin")] - [Authorize(Policy = "Admin")] - public string Admin() - { - return "you are an admin"; - } + [HttpGet("admin")] + [Authorize(Policy = "Admin")] + public string Admin() + { + return "you are an admin"; + } } diff --git a/src/deskstar-backend/Deskstar/Controllers/ResourceController.cs b/src/deskstar-backend/Deskstar/Controllers/ResourceController.cs index f0f075a8..cfc5e42d 100644 --- a/src/deskstar-backend/Deskstar/Controllers/ResourceController.cs +++ b/src/deskstar-backend/Deskstar/Controllers/ResourceController.cs @@ -1,10 +1,11 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Deskstar.Usecases; -using Deskstar.Models; +using AutoMapper; using Deskstar.Core; -using Deskstar.Entities; using Deskstar.Core.Exceptions; +using Deskstar.Entities; +using Deskstar.Models; +using Deskstar.Usecases; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; namespace Deskstar.Controllers; @@ -13,11 +14,11 @@ namespace Deskstar.Controllers; [Produces("application/json")] public class ResourceController : ControllerBase { - private readonly IResourceUsecases _resourceUsecases; - private readonly IUserUsecases _userUsecases; private readonly ILogger _logger; - private readonly AutoMapper.IMapper _mapper; + private readonly IMapper _mapper; + private readonly IResourceUsecases _resourceUsecases; + private readonly IUserUsecases _userUsecases; public ResourceController(ILogger logger, IResourceUsecases resourceUsecases, IUserUsecases userUsecases, IAutoMapperConfiguration autoMapperConfiguration) @@ -27,14 +28,14 @@ public ResourceController(ILogger logger, IResourceUsecases _userUsecases = userUsecases; _mapper = autoMapperConfiguration.GetConfiguration().CreateMapper(); } + /// - /// Updates a Desk. + /// Updates a Desk. /// /// - /// Sample request: - /// PUT /resources/desks/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// PUT /resources/desks/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Not Found @@ -66,7 +67,8 @@ public IActionResult UpdateDesk(string deskId, UpdateDeskDto dto) _logger.LogError(e, e.Message); return NotFound(e.Message); } - catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) + catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException + or OverflowException) { _logger.LogError(e, e.Message); return BadRequest(e.Message); @@ -79,13 +81,12 @@ public IActionResult UpdateDesk(string deskId, UpdateDeskDto dto) } /// - /// Updates a Desk Type. + /// Updates a Desk Type. /// /// - /// Sample request: - /// PUT /resources/desktypes/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// PUT /resources/desktypes/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Not Found @@ -115,7 +116,8 @@ public IActionResult UpdateDeskType(string deskTypeId, UpdateDeskTypeDto dto) _logger.LogError(e, e.Message); return NotFound(e.Message); } - catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) + catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException + or OverflowException) { _logger.LogError(e, e.Message); return BadRequest(e.Message); @@ -128,13 +130,12 @@ public IActionResult UpdateDeskType(string deskTypeId, UpdateDeskTypeDto dto) } /// - /// Updates a Building. + /// Updates a Building. /// /// - /// Sample request: - /// PUT /resources/buildings/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// PUT /resources/buildings/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Not Found @@ -164,7 +165,8 @@ public IActionResult UpdateBuilding(string buildingId, UpdateBuildingDto dto) _logger.LogError(e, e.Message); return NotFound(e.Message); } - catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) + catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException + or OverflowException) { _logger.LogError(e, e.Message); return BadRequest(e.Message); @@ -177,13 +179,12 @@ public IActionResult UpdateBuilding(string buildingId, UpdateBuildingDto dto) } /// - /// Updates a Floor. + /// Updates a Floor. /// /// - /// Sample request: - /// PUT /resources/floors/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// PUT /resources/floors/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Not Found @@ -214,7 +215,8 @@ public IActionResult UpdateFloor(string floorId, UpdateFloorDto dto) _logger.LogError(e, e.Message); return NotFound(e.Message); } - catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) + catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException + or OverflowException) { _logger.LogError(e, e.Message); return BadRequest(e.Message); @@ -227,13 +229,12 @@ public IActionResult UpdateFloor(string floorId, UpdateFloorDto dto) } /// - /// Updates a Room. + /// Updates a Room. /// /// - /// Sample request: - /// PUT /resources/rooms/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// PUT /resources/rooms/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Not Found @@ -264,7 +265,8 @@ public IActionResult UpdateRoom(string roomId, UpdateRoomDto dto) _logger.LogError(e, e.Message); return NotFound(e.Message); } - catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) + catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException + or OverflowException) { _logger.LogError(e, e.Message); return BadRequest(e.Message); @@ -275,15 +277,15 @@ public IActionResult UpdateRoom(string roomId, UpdateRoomDto dto) return Problem(statusCode: 500); } } + /// - /// Returns a list of Buildings. + /// Returns a list of Buildings. /// /// A List of Buildings in JSON Format (can be empty) /// - /// Sample request: - /// GET /resources/buildings with JWT Token + /// Sample request: + /// GET /resources/buildings with JWT Token /// - /// /// Returns the buildings list /// Bad Request /// Internal Server Error @@ -309,13 +311,12 @@ public IActionResult GetAllBuildings() } /// - /// Creates a new Building. + /// Creates a new Building. /// /// - /// Sample request: - /// POST /resources/buildings with JWT-Admin Token + /// Sample request: + /// POST /resources/buildings with JWT-Admin Token /// - /// /// CreateBuildingResponseObject /// Bad Request /// Not Found @@ -357,13 +358,12 @@ public IActionResult CreateBuilding(CreateBuildingDto buildingDto) } /// - /// Restores a Building. + /// Restores a Building. /// /// - /// Sample request: - /// POST /resources/buildings/restore/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// POST /resources/buildings/restore/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Internal Server Error @@ -399,13 +399,12 @@ public IActionResult RestoreBuilding(string buildingId) } /// - /// Deletes a Building. + /// Deletes a Building. /// /// - /// Sample request: - /// DELETE /resources/buildings/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// DELETE /resources/buildings/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Internal Server Error @@ -441,14 +440,13 @@ public IActionResult DeleteBuilding(string buildingId) } /// - /// Returns a list of Floors. + /// Returns a list of Floors. /// /// A List of Floors in JSON Format by BuildingId (can be empty) /// - /// Sample request: - /// GET /resources/buildings/3de7afbf-0289-4ba6-bada-a34353c5548a/floors with JWT Token + /// Sample request: + /// GET /resources/buildings/3de7afbf-0289-4ba6-bada-a34353c5548a/floors with JWT Token /// - /// /// Returns the floor list /// Bad Request /// Internal Server Error @@ -507,14 +505,13 @@ public IActionResult GetFloorsByBuildingId(string buildingId) // } /// - /// Returns a list of all Floors. + /// Returns a list of all Floors. /// /// A List of Floors in JSON Format (can be empty) /// - /// Sample request: - /// GET /resources/floors with JWT Token + /// Sample request: + /// GET /resources/floors with JWT Token /// - /// /// Returns the floor list /// Internal Server Error [HttpGet("floors")] @@ -534,17 +531,17 @@ public IActionResult GetAllFloors() { return Problem(statusCode: 500, detail: e.Message); } + return Ok(floor.ToList()); } /// - /// Creates a new Floor. + /// Creates a new Floor. /// /// - /// Sample request: - /// POST /resources/floors with JWT-Admin Token + /// Sample request: + /// POST /resources/floors with JWT-Admin Token /// - /// /// CreateFloorResponseObject /// Bad Request /// Not Found @@ -585,13 +582,12 @@ public IActionResult CreateFloor(CreateFloorDto floorDto) } /// - /// Deletes a Floor. + /// Deletes a Floor. /// /// - /// Sample request: - /// DELETE /resources/floors/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// DELETE /resources/floors/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Internal Server Error @@ -627,13 +623,12 @@ public IActionResult DeleteFloor(string floorId) } /// - /// Restores a floor. + /// Restores a floor. /// /// - /// Sample request: - /// POST /resources/floors/restore/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// POST /resources/floors/restore/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Internal Server Error @@ -669,14 +664,13 @@ public IActionResult RestoreFloor(string floorID) } /// - /// Returns a list of Rooms. + /// Returns a list of Rooms. /// /// A List of Rooms in JSON Format by FloorId (can be empty) /// - /// Sample request: - /// GET /resources/floors/3de7afbf-0289-4ba6-bada-a34353c5548a/rooms with JWT Token + /// Sample request: + /// GET /resources/floors/3de7afbf-0289-4ba6-bada-a34353c5548a/rooms with JWT Token /// - /// /// Returns the rooms list /// Bad Request /// Internal Server Error @@ -735,14 +729,13 @@ public IActionResult GetRoomsByFloorId(string floorId) // } /// - /// Returns a list of all Rooms. + /// Returns a list of all Rooms. /// /// A List of Rooms in JSON Format (can be empty) /// - /// Sample request: - /// GET /resources/rooms with JWT Token + /// Sample request: + /// GET /resources/rooms with JWT Token /// - /// /// Returns the rooms list /// Internal Server Error [HttpGet("rooms")] @@ -767,13 +760,12 @@ public IActionResult GetAllRooms() } /// - /// Creates a new Room. + /// Creates a new Room. /// /// - /// Sample request: - /// POST /resources/rooms with JWT-Admin Token + /// Sample request: + /// POST /resources/rooms with JWT-Admin Token /// - /// /// CreateRoomResponseObject /// Bad Request /// Not Found @@ -815,13 +807,12 @@ public IActionResult CreateRoom(CreateRoomDto roomDto) } /// - /// Deletes a Room. + /// Deletes a Room. /// /// - /// Sample request: - /// DELETE /resources/rooms/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// DELETE /resources/rooms/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Internal Server Error @@ -857,13 +848,12 @@ public IActionResult DeleteRoom(string roomId) } /// - /// Restores a room. + /// Restores a room. /// /// - /// Sample request: - /// POST /resources/rooms/restore/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// POST /resources/rooms/restore/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Internal Server Error @@ -899,15 +889,14 @@ public IActionResult RestoreRoom(string roomId) } /// - /// Returns a list of Desks. + /// Returns a list of Desks. /// /// A List of Desks in JSON Format by RoomId (can be empty) /// - /// Sample request: - /// GET /resources/rooms/3de7afbf-0289-4ba6-bada-a34353c5548a/desks?start=1669021730904&end=1669121730904 - /// with JWT Token + /// Sample request: + /// GET /resources/rooms/3de7afbf-0289-4ba6-bada-a34353c5548a/desks?start=1669021730904&end=1669121730904 + /// with JWT Token /// - /// /// Returns the desks list /// Bad Request /// Internal Server Error @@ -969,14 +958,13 @@ public IActionResult GetDesksByRoomId(string roomId, long start = 0, long end = // } /// - /// Returns a list of all Desks. + /// Returns a list of all Desks. /// /// A List of Desks in JSON Format by RoomId (can be empty) /// - /// Sample request: - /// GET /resources/desks with JWT Token + /// Sample request: + /// GET /resources/desks with JWT Token /// - /// /// Returns the desks list /// Internal Server Error [HttpGet("desks")] @@ -1001,15 +989,14 @@ public IActionResult GetAllDesks() } /// - /// Returns details of Desks. + /// Returns details of Desks. /// /// A List of Desks in JSON Format by RoomId (can be empty) /// - /// Sample request: - /// GET /resources/desks/3de7afbf-0289-4ba6-bada-a34353c5548a?start=1669021730904&end=1669121730904 - /// with JWT Token + /// Sample request: + /// GET /resources/desks/3de7afbf-0289-4ba6-bada-a34353c5548a?start=1669021730904&end=1669121730904 + /// with JWT Token /// - /// /// Returns the buildings list /// Bad Request /// Internal Server Error @@ -1027,10 +1014,7 @@ public IActionResult GetDeskDetailsByDeskId(string deskId, long start = 0, long startDateTime = start == 0 ? DateTime.Now : DateTimeOffset.FromUnixTimeMilliseconds(start).DateTime; endDateTime = end == 0 ? DateTime.MaxValue : DateTimeOffset.FromUnixTimeMilliseconds(end).DateTime; - if (start > end) - { - (endDateTime, startDateTime) = (startDateTime, endDateTime); - } + if (start > end) (endDateTime, startDateTime) = (startDateTime, endDateTime); } catch (FormatException e) { @@ -1057,13 +1041,12 @@ public IActionResult GetDeskDetailsByDeskId(string deskId, long start = 0, long } /// - /// Creates a new Desk. + /// Creates a new Desk. /// /// - /// Sample request: - /// POST /resources/desks with JWT-Admin Token + /// Sample request: + /// POST /resources/desks with JWT-Admin Token /// - /// /// CreateDeskResponseObject /// Bad Request /// Not Found @@ -1106,13 +1089,12 @@ public IActionResult CreateDesk(CreateDeskDto deskDto) } /// - /// Deletes a Desk. + /// Deletes a Desk. /// /// - /// Sample request: - /// DELETE /resources/desks/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// DELETE /resources/desks/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Internal Server Error @@ -1148,13 +1130,12 @@ public IActionResult DeleteDesk(string deskId) } /// - /// Restores a Desk. + /// Restores a Desk. /// /// - /// Sample request: - /// POST /resources/desks/restore/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// POST /resources/desks/restore/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Internal Server Error @@ -1190,13 +1171,12 @@ public IActionResult RestoreDesk(string deskId) } /// - /// Creates a new DeskType. + /// Creates a new DeskType. /// /// - /// Sample request: - /// POST /resources/desktypes with JWT-Admin Token + /// Sample request: + /// POST /resources/desktypes with JWT-Admin Token /// - /// /// CreateDeskTypeResponseObject /// Bad Request /// Internal Server Error @@ -1224,13 +1204,12 @@ public IActionResult CreateDeskType(CreateDeskTypeDto deskTypeDto) } /// - /// Return a list of desk types + /// Return a list of desk types /// /// - /// Sample request: - /// Get /resources/desktypes with JWT-Admin Token + /// Sample request: + /// Get /resources/desktypes with JWT-Admin Token /// - /// /// List /// Bad Request /// Internal Server Error @@ -1259,13 +1238,12 @@ public IActionResult ReadDeskTypes() } /// - /// Deletes a desk type. + /// Deletes a desk type. /// /// - /// Sample request: - /// DELETE /resources/desktypes/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// DELETE /resources/desktypes/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Internal Server Error @@ -1301,13 +1279,12 @@ public IActionResult DeleteDeskType(string deskTypeId) } /// - /// Restores a deskType. + /// Restores a deskType. /// /// - /// Sample request: - /// POST /resources/desktypes/restore/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// Sample request: + /// POST /resources/desktypes/restore/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token /// - /// /// Ok /// Bad Request /// Internal Server Error diff --git a/src/deskstar-backend/Deskstar/Controllers/UserController.cs b/src/deskstar-backend/Deskstar/Controllers/UserController.cs index f8ac1b31..e9fd20ad 100755 --- a/src/deskstar-backend/Deskstar/Controllers/UserController.cs +++ b/src/deskstar-backend/Deskstar/Controllers/UserController.cs @@ -7,13 +7,14 @@ * * MIT License */ + using Deskstar.Core; -using Deskstar.Models; +using Deskstar.Core.Exceptions; using Deskstar.Entities; +using Deskstar.Models; using Deskstar.Usecases; -using Deskstar.Core.Exceptions; -using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; namespace Deskstar.Controllers; @@ -22,348 +23,341 @@ namespace Deskstar.Controllers; [Produces("application/json")] public class UserController : ControllerBase { - private readonly IUserUsecases _userUsecases; - private readonly ILogger _logger; - private readonly IAutoMapperConfiguration _autoMapperConfiguration; + private readonly IAutoMapperConfiguration _autoMapperConfiguration; + private readonly ILogger _logger; + private readonly IUserUsecases _userUsecases; - public UserController(ILogger logger, IUserUsecases userUsecases, - IAutoMapperConfiguration autoMapperConfiguration) - { - _logger = logger; - _userUsecases = userUsecases; - _autoMapperConfiguration = autoMapperConfiguration; - } + public UserController(ILogger logger, IUserUsecases userUsecases, + IAutoMapperConfiguration autoMapperConfiguration) + { + _logger = logger; + _userUsecases = userUsecases; + _autoMapperConfiguration = autoMapperConfiguration; + } - /// - /// Returns all users for a specific company - /// - /// List of user information in JSON Format - /// - /// Sample request: - /// Get /users with JWT Token - /// - /// - /// List of user information in JSON Format - /// Not Found - /// Internal Server Error - [HttpGet] - [Authorize(Policy = "Admin")] - [ProducesResponseType(typeof(UserProfileDto), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult Get() + /// + /// Returns all users for a specific company + /// + /// List of user information in JSON Format + /// + /// Sample request: + /// Get /users with JWT Token + /// + /// List of user information in JSON Format + /// Not Found + /// Internal Server Error + [HttpGet] + [Authorize(Policy = "Admin")] + [ProducesResponseType(typeof(UserProfileDto), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult Get() + { + var adminId = RequestInteractions.ExtractIdFromRequest(Request); + try { - var adminId = RequestInteractions.ExtractIdFromRequest(Request); - try - { - var entities = _userUsecases.ReadAllUsers(adminId); + var entities = _userUsecases.ReadAllUsers(adminId); - var mapper = _autoMapperConfiguration.GetConfiguration().CreateMapper(); - var users = entities.Select(user => mapper.Map(user)).ToList(); + var mapper = _autoMapperConfiguration.GetConfiguration().CreateMapper(); + var users = entities.Select(user => mapper.Map(user)).ToList(); - return Ok(users); - } - catch (EntityNotFoundException e) - { - _logger.LogError(e, e.Message); - return NotFound(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } + return Ok(users); } - - /// - /// Returns user specific information - /// - /// User information in JSON Format - /// - /// Sample request: - /// Get /users/me with JWT Token - /// - /// - /// Returns information about the logged in user - /// Not Found - /// Internal Server Error - [HttpGet("me")] - [Authorize] - [ProducesResponseType(typeof(UserProfileDto), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult GetMe() + catch (EntityNotFoundException e) + { + _logger.LogError(e, e.Message); + return NotFound(e.Message); + } + catch (Exception e) { - var userId = RequestInteractions.ExtractIdFromRequest(Request); + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); + } + } - try - { - var me = _userUsecases.ReadSpecificUser(userId); + /// + /// Returns user specific information + /// + /// User information in JSON Format + /// + /// Sample request: + /// Get /users/me with JWT Token + /// + /// Returns information about the logged in user + /// Not Found + /// Internal Server Error + [HttpGet("me")] + [Authorize] + [ProducesResponseType(typeof(UserProfileDto), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult GetMe() + { + var userId = RequestInteractions.ExtractIdFromRequest(Request); - var mapper = _autoMapperConfiguration.GetConfiguration().CreateMapper(); - var UserProfileDto = mapper.Map(me); + try + { + var me = _userUsecases.ReadSpecificUser(userId); - return Ok(UserProfileDto); - } - catch (EntityNotFoundException e) - { - _logger.LogError(e, e.Message); - return NotFound(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } - } + var mapper = _autoMapperConfiguration.GetConfiguration().CreateMapper(); + var UserProfileDto = mapper.Map(me); - /// - /// Lets an admin approve a users registration for their company - /// - /// empty response - /// - /// Sample request: - /// Post /users/{userId}/approve - /// - /// - /// Empty Response - /// Bad Request - /// Forbid - /// Not Found - /// Internal Server Error - [HttpPost("{userId}/approve")] - [Authorize(Policy = "Admin")] - [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status403Forbidden)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - public IActionResult ApproveUser(string userId) + return Ok(UserProfileDto); + } + catch (EntityNotFoundException e) { - var adminId = RequestInteractions.ExtractIdFromRequest(Request); - - try - { - _userUsecases.ApproveUser(adminId, userId); - return Ok(); - } - catch (ArgumentInvalidException e) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - catch (InsufficientPermissionException e) - { - _logger.LogError(e, e.Message); - return Forbid(e.Message); - } - catch (EntityNotFoundException e) - { - _logger.LogError(e, e.Message); - return NotFound(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } + _logger.LogError(e, e.Message); + return NotFound(e.Message); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); } + } - /// - /// Lets an admin decline a users registration for their company - /// - /// empty response - /// - /// Sample request: - /// Post /users/{userId}/decline - /// - /// - /// Empty Response - /// Bad Request - /// Forbid - /// Not Found - /// Internal Server Error - [HttpPost("{userId}/decline")] - [Authorize(Policy = "Admin")] - [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status403Forbidden)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - public IActionResult DeclineUser(string userId) + /// + /// Lets an admin approve a users registration for their company + /// + /// empty response + /// + /// Sample request: + /// Post /users/{userId}/approve + /// + /// Empty Response + /// Bad Request + /// Forbid + /// Not Found + /// Internal Server Error + [HttpPost("{userId}/approve")] + [Authorize(Policy = "Admin")] + [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public IActionResult ApproveUser(string userId) + { + var adminId = RequestInteractions.ExtractIdFromRequest(Request); + + try + { + _userUsecases.ApproveUser(adminId, userId); + return Ok(); + } + catch (ArgumentInvalidException e) { - var adminId = RequestInteractions.ExtractIdFromRequest(Request); + _logger.LogError(e, e.Message); + return BadRequest(e.Message); + } + catch (InsufficientPermissionException e) + { + _logger.LogError(e, e.Message); + return Forbid(e.Message); + } + catch (EntityNotFoundException e) + { + _logger.LogError(e, e.Message); + return NotFound(e.Message); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); + } + } + + /// + /// Lets an admin decline a users registration for their company + /// + /// empty response + /// + /// Sample request: + /// Post /users/{userId}/decline + /// + /// Empty Response + /// Bad Request + /// Forbid + /// Not Found + /// Internal Server Error + [HttpPost("{userId}/decline")] + [Authorize(Policy = "Admin")] + [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public IActionResult DeclineUser(string userId) + { + var adminId = RequestInteractions.ExtractIdFromRequest(Request); - try - { - _userUsecases.DeclineUser(adminId, userId); - return Ok(); - } - catch (ArgumentInvalidException e) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - catch (InsufficientPermissionException e) - { - _logger.LogError(e, e.Message); - return Forbid(e.Message); - } - catch (EntityNotFoundException e) - { - _logger.LogError(e, e.Message); - return NotFound(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } + try + { + _userUsecases.DeclineUser(adminId, userId); + return Ok(); + } + catch (ArgumentInvalidException e) + { + _logger.LogError(e, e.Message); + return BadRequest(e.Message); + } + catch (InsufficientPermissionException e) + { + _logger.LogError(e, e.Message); + return Forbid(e.Message); + } + catch (EntityNotFoundException e) + { + _logger.LogError(e, e.Message); + return NotFound(e.Message); } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); + } + } - /// - /// Update user information - /// - /// empty response - /// - /// Sample request: - /// Post /users/me - /// - /// - /// Empty Response - /// Not Found - /// Internal Server Error - [HttpPost("me")] - [Authorize] - [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - public IActionResult UpdateUser(UserProfileDto userDto) + /// + /// Update user information + /// + /// empty response + /// + /// Sample request: + /// Post /users/me + /// + /// Empty Response + /// Not Found + /// Internal Server Error + [HttpPost("me")] + [Authorize] + [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public IActionResult UpdateUser(UserProfileDto userDto) + { + var userId = RequestInteractions.ExtractIdFromRequest(Request); + try { - var userId = RequestInteractions.ExtractIdFromRequest(Request); - try - { - var mapper = _autoMapperConfiguration.GetConfiguration().CreateMapper(); - var user = mapper.Map(userDto); + var mapper = _autoMapperConfiguration.GetConfiguration().CreateMapper(); + var user = mapper.Map(userDto); - _userUsecases.UpdateUser(userId, user); + _userUsecases.UpdateUser(userId, user); - return Ok(); - } - catch (EntityNotFoundException e) - { - _logger.LogError(e, e.Message); - return NotFound(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } + return Ok(); + } + catch (EntityNotFoundException e) + { + _logger.LogError(e, e.Message); + return NotFound(e.Message); } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); + } + } - /// - /// Update given user information - /// - /// empty response - /// - /// Sample request: - /// Post /edit - /// - /// - /// Empty Response - /// Bad Request - /// Forbid - /// Not Found - /// Internal Server Error - [HttpPost("edit")] - [Authorize(Policy = "Admin")] - [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status403Forbidden)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - public IActionResult UpdateGivenUser(UserProfileDto userDto) + /// + /// Update given user information + /// + /// empty response + /// + /// Sample request: + /// Post /edit + /// + /// Empty Response + /// Bad Request + /// Forbid + /// Not Found + /// Internal Server Error + [HttpPost("edit")] + [Authorize(Policy = "Admin")] + [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public IActionResult UpdateGivenUser(UserProfileDto userDto) + { + var adminId = RequestInteractions.ExtractIdFromRequest(Request); + try + { + var mapper = _autoMapperConfiguration.GetConfiguration().CreateMapper(); + var user = mapper.Map(userDto); + _userUsecases.UpdateUser(adminId, user); + return Ok(); + } + catch (ArgumentInvalidException e) { - var adminId = RequestInteractions.ExtractIdFromRequest(Request); - try - { - var mapper = _autoMapperConfiguration.GetConfiguration().CreateMapper(); - var user = mapper.Map(userDto); - _userUsecases.UpdateUser(adminId,user); - return Ok(); - } - catch (ArgumentInvalidException e) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - catch (InsufficientPermissionException e) - { - _logger.LogError(e, e.Message); - return Forbid(e.Message); - } - catch (EntityNotFoundException e) - { - _logger.LogError(e, e.Message); - return NotFound(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } + _logger.LogError(e, e.Message); + return BadRequest(e.Message); } + catch (InsufficientPermissionException e) + { + _logger.LogError(e, e.Message); + return Forbid(e.Message); + } + catch (EntityNotFoundException e) + { + _logger.LogError(e, e.Message); + return NotFound(e.Message); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); + } + } - /// - /// Delete given user - /// - /// empty response - /// - /// Sample request: - /// Post /delete/{userId} - /// - /// - /// Empty Response - /// Not Found - /// Internal Server Error - [HttpDelete("{userId}")] - [Authorize(Policy = "Admin")] - [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status403Forbidden)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - public IActionResult DeleteGivenUser(string userId) + /// + /// Delete given user + /// + /// empty response + /// + /// Sample request: + /// Post /delete/{userId} + /// + /// Empty Response + /// Not Found + /// Internal Server Error + [HttpDelete("{userId}")] + [Authorize(Policy = "Admin")] + [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public IActionResult DeleteGivenUser(string userId) + { + var adminId = RequestInteractions.ExtractIdFromRequest(Request); + try + { + _userUsecases.DeleteUser(adminId, userId); + return Ok(); + } + catch (ArgumentInvalidException e) + { + _logger.LogError(e, e.Message); + return BadRequest(e.Message); + } + catch (InsufficientPermissionException e) + { + _logger.LogError(e, e.Message); + return Forbid(e.Message); + } + catch (EntityNotFoundException e) + { + _logger.LogError(e, e.Message); + return NotFound(e.Message); + } + catch (Exception e) { - var adminId = RequestInteractions.ExtractIdFromRequest(Request); - try - { - _userUsecases.DeleteUser(adminId, userId); - return Ok(); - } - catch (ArgumentInvalidException e) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - catch (InsufficientPermissionException e) - { - _logger.LogError(e, e.Message); - return Forbid(e.Message); - } - catch (EntityNotFoundException e) - { - _logger.LogError(e, e.Message); - return NotFound(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); } + } } diff --git a/src/deskstar-backend/Deskstar/Core/Exceptions/ArgumentInvalidException.cs b/src/deskstar-backend/Deskstar/Core/Exceptions/ArgumentInvalidException.cs index 2ac57f0f..46d6cc8c 100644 --- a/src/deskstar-backend/Deskstar/Core/Exceptions/ArgumentInvalidException.cs +++ b/src/deskstar-backend/Deskstar/Core/Exceptions/ArgumentInvalidException.cs @@ -2,5 +2,7 @@ namespace Deskstar.Core.Exceptions; public class ArgumentInvalidException : ArgumentException { - public ArgumentInvalidException(string message) : base(message) { } -} \ No newline at end of file + public ArgumentInvalidException(string message) : base(message) + { + } +} diff --git a/src/deskstar-backend/Deskstar/Core/Exceptions/EntityNotFoundException.cs b/src/deskstar-backend/Deskstar/Core/Exceptions/EntityNotFoundException.cs index 10a504ec..860bbb5f 100644 --- a/src/deskstar-backend/Deskstar/Core/Exceptions/EntityNotFoundException.cs +++ b/src/deskstar-backend/Deskstar/Core/Exceptions/EntityNotFoundException.cs @@ -2,5 +2,7 @@ namespace Deskstar.Core.Exceptions; public class EntityNotFoundException : ArgumentException { - public EntityNotFoundException(string message) : base(message) { } -} \ No newline at end of file + public EntityNotFoundException(string message) : base(message) + { + } +} diff --git a/src/deskstar-backend/Deskstar/Core/Exceptions/InsufficientPermissionException.cs b/src/deskstar-backend/Deskstar/Core/Exceptions/InsufficientPermissionException.cs index 394e87ee..d7f4ad64 100644 --- a/src/deskstar-backend/Deskstar/Core/Exceptions/InsufficientPermissionException.cs +++ b/src/deskstar-backend/Deskstar/Core/Exceptions/InsufficientPermissionException.cs @@ -2,5 +2,7 @@ namespace Deskstar.Core.Exceptions; public class InsufficientPermissionException : ArgumentException { - public InsufficientPermissionException(string message) : base(message) { } -} \ No newline at end of file + public InsufficientPermissionException(string message) : base(message) + { + } +} diff --git a/src/deskstar-backend/Deskstar/Core/RequestInteractions.cs b/src/deskstar-backend/Deskstar/Core/RequestInteractions.cs index 366e6929..2d5bc3ac 100644 --- a/src/deskstar-backend/Deskstar/Core/RequestInteractions.cs +++ b/src/deskstar-backend/Deskstar/Core/RequestInteractions.cs @@ -7,6 +7,7 @@ * * MIT License */ + using System.IdentityModel.Tokens.Jwt; using Microsoft.Net.Http.Headers; @@ -14,11 +15,11 @@ namespace Deskstar.Core; public class RequestInteractions { - public static Guid ExtractIdFromRequest(HttpRequest request) - { - var accessToken = request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty); - var handler = new JwtSecurityTokenHandler(); - var jwtSecurityToken = handler.ReadJwtToken(accessToken); - return new Guid(jwtSecurityToken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value); - } -} \ No newline at end of file + public static Guid ExtractIdFromRequest(HttpRequest request) + { + var accessToken = request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty); + var handler = new JwtSecurityTokenHandler(); + var jwtSecurityToken = handler.ReadJwtToken(accessToken); + return new Guid(jwtSecurityToken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value); + } +} diff --git a/src/deskstar-backend/Deskstar/Core/constants.cs b/src/deskstar-backend/Deskstar/Core/constants.cs index 87d445bd..a70d04fe 100644 --- a/src/deskstar-backend/Deskstar/Core/constants.cs +++ b/src/deskstar-backend/Deskstar/Core/constants.cs @@ -7,28 +7,27 @@ * * MIT License */ -namespace Deskstar.Core + +namespace Deskstar.Core; + +public class Constants { - public class Constants - { - public static readonly string CONFIG_DB_HOST = "Db:Host"; - public static readonly string CONFIG_DB_DATABASE = "Db:Database"; - public static readonly string CONFIG_DB_USERNAME = "Db:Username"; - public static readonly string CONFIG_DB_PASSWORD = "Db:Password"; - public static readonly string CONFIG_EMAIL_PASSWORD = "Email:PSW"; - public static readonly string CONFIG_EMAIL_HOST= "Email:Host"; - public static readonly string CONFIG_EMAIL_PORT= "Email:Port"; - public static readonly string CONFIG_EMAIL_USERNAME= "Email:Address"; - - - public static readonly string ENV_DB_HOST = "DB__HOST"; - public static readonly string ENV_DB_DATABASE = "DB__DATABASE"; - public static readonly string ENV_DB_USERNAME = "DB__USERNAME"; - public static readonly string ENV_DB_PASSWORD = "DB__PASSWORD"; - public static readonly string ENV_EMAIL_PASSWORD = "EMAIL__PSW"; - public static readonly string ENV_EMAIL_HOST= "EMAIL__HOST"; - public static readonly string ENV_EMAIL_PORT= "EMAIL__PORT"; - public static readonly string ENV_EMAIL_USERNAME= "EMAIL__Address"; - - } -} \ No newline at end of file + public static readonly string CONFIG_DB_HOST = "Db:Host"; + public static readonly string CONFIG_DB_DATABASE = "Db:Database"; + public static readonly string CONFIG_DB_USERNAME = "Db:Username"; + public static readonly string CONFIG_DB_PASSWORD = "Db:Password"; + public static readonly string CONFIG_EMAIL_PASSWORD = "Email:PSW"; + public static readonly string CONFIG_EMAIL_HOST = "Email:Host"; + public static readonly string CONFIG_EMAIL_PORT = "Email:Port"; + public static readonly string CONFIG_EMAIL_USERNAME = "Email:Address"; + + + public static readonly string ENV_DB_HOST = "DB__HOST"; + public static readonly string ENV_DB_DATABASE = "DB__DATABASE"; + public static readonly string ENV_DB_USERNAME = "DB__USERNAME"; + public static readonly string ENV_DB_PASSWORD = "DB__PASSWORD"; + public static readonly string ENV_EMAIL_PASSWORD = "EMAIL__PSW"; + public static readonly string ENV_EMAIL_HOST = "EMAIL__HOST"; + public static readonly string ENV_EMAIL_PORT = "EMAIL__PORT"; + public static readonly string ENV_EMAIL_USERNAME = "EMAIL__Address"; +} diff --git a/src/deskstar-backend/Deskstar/DataAccess/DataContext.cs b/src/deskstar-backend/Deskstar/DataAccess/DataContext.cs index 2c4fd962..2778e5ac 100644 --- a/src/deskstar-backend/Deskstar/DataAccess/DataContext.cs +++ b/src/deskstar-backend/Deskstar/DataAccess/DataContext.cs @@ -1,273 +1,271 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.InMemory; -using Deskstar.Entities; +using Deskstar.Entities; +using Microsoft.EntityFrameworkCore; -namespace Deskstar.DataAccess +namespace Deskstar.DataAccess; + +public partial class DataContext : DbContext { - public partial class DataContext : DbContext + public DataContext() { - public DataContext() - { - } + } - public DataContext(DbContextOptions options) - : base(options) - { - } - - public virtual DbSet Bookings { get; set; } = null!; - public virtual DbSet Buildings { get; set; } = null!; - public virtual DbSet Companies { get; set; } = null!; - public virtual DbSet Desks { get; set; } = null!; - public virtual DbSet DeskTypes { get; set; } = null!; - public virtual DbSet Floors { get; set; } = null!; - public virtual DbSet Roles { get; set; } = null!; - public virtual DbSet Rooms { get; set; } = null!; - public virtual DbSet Users { get; set; } = null!; - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - if (!optionsBuilder.IsConfigured) - { - //For migration purposes... - // optionsBuilder.UseNpgsql($"Host=localhost;Database=postgres;Username=postgres;Password=postgres"); - optionsBuilder.UseInMemoryDatabase(databaseName: "TestDB"); - } - } - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity(entity => - { - entity.ToTable("Booking"); + public DataContext(DbContextOptions options) + : base(options) + { + } + + public virtual DbSet Bookings { get; set; } = null!; + public virtual DbSet Buildings { get; set; } = null!; + public virtual DbSet Companies { get; set; } = null!; + public virtual DbSet Desks { get; set; } = null!; + public virtual DbSet DeskTypes { get; set; } = null!; + public virtual DbSet Floors { get; set; } = null!; + public virtual DbSet Roles { get; set; } = null!; + public virtual DbSet Rooms { get; set; } = null!; + public virtual DbSet Users { get; set; } = null!; + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + if (!optionsBuilder.IsConfigured) + //For migration purposes... + // optionsBuilder.UseNpgsql($"Host=localhost;Database=postgres;Username=postgres;Password=postgres"); + optionsBuilder.UseInMemoryDatabase("TestDB"); + } - entity.Property(e => e.BookingId) - .HasColumnName("BookingID") - .HasDefaultValueSql("gen_random_uuid()"); + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity(entity => + { + entity.ToTable("Booking"); - entity.Property(e => e.DeskId).HasColumnName("DeskID"); + entity.Property(e => e.BookingId) + .HasColumnName("BookingID") + .HasDefaultValueSql("gen_random_uuid()"); - entity.Property(e => e.EndTime).HasColumnType("timestamp without time zone"); + entity.Property(e => e.DeskId).HasColumnName("DeskID"); - entity.Property(e => e.StartTime).HasColumnType("timestamp without time zone"); + entity.Property(e => e.EndTime).HasColumnType("timestamp without time zone"); - entity.Property(e => e.Timestamp) - .HasColumnType("timestamp without time zone") - .HasDefaultValueSql("CURRENT_TIMESTAMP(2)"); + entity.Property(e => e.StartTime).HasColumnType("timestamp without time zone"); - entity.Property(e => e.UserId).HasColumnName("UserID"); + entity.Property(e => e.Timestamp) + .HasColumnType("timestamp without time zone") + .HasDefaultValueSql("CURRENT_TIMESTAMP(2)"); - entity.HasOne(d => d.Desk) - .WithMany(p => p.Bookings) - .HasForeignKey(d => d.DeskId) - .OnDelete(DeleteBehavior.ClientSetNull) - .HasConstraintName("Booking_Desk_null_fk"); + entity.Property(e => e.UserId).HasColumnName("UserID"); - entity.HasOne(d => d.User) - .WithMany(p => p.Bookings) - .HasForeignKey(d => d.UserId) - .OnDelete(DeleteBehavior.ClientSetNull) - .HasConstraintName("Booking_User_null_fk"); - }); + entity.HasOne(d => d.Desk) + .WithMany(p => p.Bookings) + .HasForeignKey(d => d.DeskId) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("Booking_Desk_null_fk"); - modelBuilder.Entity(entity => - { - entity.ToTable("Building"); + entity.HasOne(d => d.User) + .WithMany(p => p.Bookings) + .HasForeignKey(d => d.UserId) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("Booking_User_null_fk"); + }); - entity.Property(e => e.BuildingId) - .HasColumnName("BuildingID") - .HasDefaultValueSql("gen_random_uuid()"); + modelBuilder.Entity(entity => + { + entity.ToTable("Building"); - entity.Property(e => e.BuildingName).HasColumnType("character varying"); + entity.Property(e => e.BuildingId) + .HasColumnName("BuildingID") + .HasDefaultValueSql("gen_random_uuid()"); - entity.Property(e => e.CompanyId).HasColumnName("CompanyID"); + entity.Property(e => e.BuildingName).HasColumnType("character varying"); - entity.Property(e => e.Location).HasColumnType("character varying"); + entity.Property(e => e.CompanyId).HasColumnName("CompanyID"); - entity.Property(e => e.IsMarkedForDeletion).HasDefaultValueSql("false"); + entity.Property(e => e.Location).HasColumnType("character varying"); - entity.HasOne(d => d.Company) - .WithMany(p => p.Buildings) - .HasForeignKey(d => d.CompanyId) - .OnDelete(DeleteBehavior.ClientSetNull) - .HasConstraintName("foreign_key_name"); - }); + entity.Property(e => e.IsMarkedForDeletion).HasDefaultValueSql("false"); - modelBuilder.Entity(entity => - { - entity.ToTable("Company"); + entity.HasOne(d => d.Company) + .WithMany(p => p.Buildings) + .HasForeignKey(d => d.CompanyId) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("foreign_key_name"); + }); - entity.Property(e => e.CompanyId) - .HasColumnName("CompanyID") - .HasDefaultValueSql("gen_random_uuid()"); + modelBuilder.Entity(entity => + { + entity.ToTable("Company"); - entity.Property(e => e.CompanyName).HasColumnType("character varying"); - }); + entity.Property(e => e.CompanyId) + .HasColumnName("CompanyID") + .HasDefaultValueSql("gen_random_uuid()"); - modelBuilder.Entity(entity => - { - entity.ToTable("Desk"); + entity.Property(e => e.CompanyName).HasColumnType("character varying"); + }); - entity.Property(e => e.DeskId) - .HasColumnName("DeskID") - .HasDefaultValueSql("gen_random_uuid()"); + modelBuilder.Entity(entity => + { + entity.ToTable("Desk"); - entity.Property(e => e.DeskName).HasColumnType("character varying"); + entity.Property(e => e.DeskId) + .HasColumnName("DeskID") + .HasDefaultValueSql("gen_random_uuid()"); - entity.Property(e => e.DeskTypeId).HasColumnName("DeskTypeID"); + entity.Property(e => e.DeskName).HasColumnType("character varying"); - entity.Property(e => e.RoomId).HasColumnName("RoomID"); + entity.Property(e => e.DeskTypeId).HasColumnName("DeskTypeID"); - entity.HasOne(d => d.DeskType) - .WithMany(p => p.Desks) - .HasForeignKey(d => d.DeskTypeId) - .OnDelete(DeleteBehavior.ClientSetNull) - .HasConstraintName("Desk_DeskType_null_fk"); + entity.Property(e => e.RoomId).HasColumnName("RoomID"); - entity.HasOne(d => d.Room) - .WithMany(p => p.Desks) - .HasForeignKey(d => d.RoomId) - .OnDelete(DeleteBehavior.ClientSetNull) - .HasConstraintName("Desk_Room_null_fk"); + entity.HasOne(d => d.DeskType) + .WithMany(p => p.Desks) + .HasForeignKey(d => d.DeskTypeId) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("Desk_DeskType_null_fk"); - entity.Property(e => e.IsMarkedForDeletion).HasDefaultValueSql("false"); - }); + entity.HasOne(d => d.Room) + .WithMany(p => p.Desks) + .HasForeignKey(d => d.RoomId) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("Desk_Room_null_fk"); - modelBuilder.Entity(entity => - { - entity.ToTable("DeskType"); + entity.Property(e => e.IsMarkedForDeletion).HasDefaultValueSql("false"); + }); - entity.Property(e => e.DeskTypeId) - .HasColumnName("DeskTypeID") - .HasDefaultValueSql("gen_random_uuid()"); + modelBuilder.Entity(entity => + { + entity.ToTable("DeskType"); - entity.Property(e => e.CompanyId).HasColumnName("CompanyID"); + entity.Property(e => e.DeskTypeId) + .HasColumnName("DeskTypeID") + .HasDefaultValueSql("gen_random_uuid()"); - entity.Property(e => e.DeskTypeName).HasColumnType("character varying"); + entity.Property(e => e.CompanyId).HasColumnName("CompanyID"); - entity.HasOne(d => d.Company) - .WithMany(p => p.DeskTypes) - .HasForeignKey(d => d.CompanyId) - .OnDelete(DeleteBehavior.ClientSetNull) - .HasConstraintName("DeskType_Company_null_fk"); + entity.Property(e => e.DeskTypeName).HasColumnType("character varying"); - entity.Property(e => e.IsMarkedForDeletion).HasDefaultValueSql("false"); - }); + entity.HasOne(d => d.Company) + .WithMany(p => p.DeskTypes) + .HasForeignKey(d => d.CompanyId) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("DeskType_Company_null_fk"); - modelBuilder.Entity(entity => - { - entity.ToTable("Floor"); + entity.Property(e => e.IsMarkedForDeletion).HasDefaultValueSql("false"); + }); - entity.Property(e => e.FloorId) - .HasColumnName("FloorID") - .HasDefaultValueSql("gen_random_uuid()"); + modelBuilder.Entity(entity => + { + entity.ToTable("Floor"); - entity.Property(e => e.BuildingId).HasColumnName("BuildingID"); + entity.Property(e => e.FloorId) + .HasColumnName("FloorID") + .HasDefaultValueSql("gen_random_uuid()"); - entity.Property(e => e.FloorName).HasColumnType("character varying"); + entity.Property(e => e.BuildingId).HasColumnName("BuildingID"); - entity.HasOne(d => d.Building) - .WithMany(p => p.Floors) - .HasForeignKey(d => d.BuildingId) - .OnDelete(DeleteBehavior.ClientSetNull) - .HasConstraintName("Floor_Building_null_fk"); + entity.Property(e => e.FloorName).HasColumnType("character varying"); - entity.Property(e => e.IsMarkedForDeletion).HasDefaultValueSql("false"); - }); + entity.HasOne(d => d.Building) + .WithMany(p => p.Floors) + .HasForeignKey(d => d.BuildingId) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("Floor_Building_null_fk"); - modelBuilder.Entity(entity => - { - entity.ToTable("Role"); + entity.Property(e => e.IsMarkedForDeletion).HasDefaultValueSql("false"); + }); - entity.Property(e => e.RoleId) - .HasColumnName("RoleID") - .HasDefaultValueSql("gen_random_uuid()"); + modelBuilder.Entity(entity => + { + entity.ToTable("Role"); - entity.Property(e => e.CompanyId).HasColumnName("CompanyID"); + entity.Property(e => e.RoleId) + .HasColumnName("RoleID") + .HasDefaultValueSql("gen_random_uuid()"); - entity.Property(e => e.RoleName).HasColumnType("character varying"); + entity.Property(e => e.CompanyId).HasColumnName("CompanyID"); - entity.HasOne(d => d.Company) - .WithMany(p => p.Roles) - .HasForeignKey(d => d.CompanyId) - .OnDelete(DeleteBehavior.ClientSetNull) - .HasConstraintName("Role_Company_null_fk"); + entity.Property(e => e.RoleName).HasColumnType("character varying"); - entity.HasMany(d => d.Users) - .WithMany(p => p.Roles) - .UsingEntity>( - "UserRole", - l => l.HasOne().WithMany().HasForeignKey("UserId").OnDelete(DeleteBehavior.ClientSetNull).HasConstraintName("UserRole_User_null_fk"), - r => r.HasOne().WithMany().HasForeignKey("RoleId").OnDelete(DeleteBehavior.ClientSetNull).HasConstraintName("UserRole_Role_null_fk"), - j => - { - j.HasKey("RoleId", "UserId").HasName("UserRole_pk"); + entity.HasOne(d => d.Company) + .WithMany(p => p.Roles) + .HasForeignKey(d => d.CompanyId) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("Role_Company_null_fk"); - j.ToTable("UserRole"); + entity.HasMany(d => d.Users) + .WithMany(p => p.Roles) + .UsingEntity>( + "UserRole", + l => l.HasOne().WithMany().HasForeignKey("UserId").OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("UserRole_User_null_fk"), + r => r.HasOne().WithMany().HasForeignKey("RoleId").OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("UserRole_Role_null_fk"), + j => + { + j.HasKey("RoleId", "UserId").HasName("UserRole_pk"); - j.IndexerProperty("RoleId").HasColumnName("RoleID"); + j.ToTable("UserRole"); - j.IndexerProperty("UserId").HasColumnName("UserID"); - }); - }); + j.IndexerProperty("RoleId").HasColumnName("RoleID"); - modelBuilder.Entity(entity => - { - entity.ToTable("Room"); + j.IndexerProperty("UserId").HasColumnName("UserID"); + }); + }); - entity.Property(e => e.RoomId) - .HasColumnName("RoomID") - .HasDefaultValueSql("gen_random_uuid()"); + modelBuilder.Entity(entity => + { + entity.ToTable("Room"); - entity.Property(e => e.FloorId).HasColumnName("FloorID"); + entity.Property(e => e.RoomId) + .HasColumnName("RoomID") + .HasDefaultValueSql("gen_random_uuid()"); - entity.Property(e => e.RoomName).HasColumnType("character varying"); + entity.Property(e => e.FloorId).HasColumnName("FloorID"); - entity.HasOne(d => d.Floor) - .WithMany(p => p.Rooms) - .HasForeignKey(d => d.FloorId) - .OnDelete(DeleteBehavior.ClientSetNull) - .HasConstraintName("Room_Floor_null_fk"); + entity.Property(e => e.RoomName).HasColumnType("character varying"); - entity.Property(e => e.IsMarkedForDeletion).HasDefaultValueSql("false"); - }); + entity.HasOne(d => d.Floor) + .WithMany(p => p.Rooms) + .HasForeignKey(d => d.FloorId) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("Room_Floor_null_fk"); - modelBuilder.Entity(entity => - { - entity.ToTable("User"); + entity.Property(e => e.IsMarkedForDeletion).HasDefaultValueSql("false"); + }); - entity.HasIndex(e => e.MailAddress, "User_Mail") - .IsUnique(); + modelBuilder.Entity(entity => + { + entity.ToTable("User"); - entity.Property(e => e.UserId) - .HasColumnName("UserID") - .HasDefaultValueSql("gen_random_uuid()"); + entity.HasIndex(e => e.MailAddress, "User_Mail") + .IsUnique(); - entity.Property(e => e.CompanyId).HasColumnName("CompanyID"); + entity.Property(e => e.UserId) + .HasColumnName("UserID") + .HasDefaultValueSql("gen_random_uuid()"); - entity.Property(e => e.FirstName).HasColumnType("character varying"); + entity.Property(e => e.CompanyId).HasColumnName("CompanyID"); - entity.Property(e => e.IsApproved).HasDefaultValueSql("false"); - entity.Property(e => e.IsCompanyAdmin).HasDefaultValueSql("false"); + entity.Property(e => e.FirstName).HasColumnType("character varying"); - entity.Property(e => e.LastName).HasColumnType("character varying"); + entity.Property(e => e.IsApproved).HasDefaultValueSql("false"); + entity.Property(e => e.IsCompanyAdmin).HasDefaultValueSql("false"); - entity.Property(e => e.MailAddress).HasColumnType("character varying"); + entity.Property(e => e.LastName).HasColumnType("character varying"); - entity.Property(e => e.Password).HasColumnType("character varying"); + entity.Property(e => e.MailAddress).HasColumnType("character varying"); - entity.HasOne(d => d.Company) - .WithMany(p => p.Users) - .HasForeignKey(d => d.CompanyId) - .OnDelete(DeleteBehavior.ClientSetNull) - .HasConstraintName("CompanyID_fk"); + entity.Property(e => e.Password).HasColumnType("character varying"); - entity.Property(e => e.IsMarkedForDeletion).HasDefaultValueSql("false"); - }); + entity.HasOne(d => d.Company) + .WithMany(p => p.Users) + .HasForeignKey(d => d.CompanyId) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("CompanyID_fk"); - OnModelCreatingPartial(modelBuilder); - } + entity.Property(e => e.IsMarkedForDeletion).HasDefaultValueSql("false"); + }); - partial void OnModelCreatingPartial(ModelBuilder modelBuilder); + OnModelCreatingPartial(modelBuilder); } + + partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } diff --git a/src/deskstar-backend/Deskstar/Entities/Booking.cs b/src/deskstar-backend/Deskstar/Entities/Booking.cs index f41177db..53e0934e 100644 --- a/src/deskstar-backend/Deskstar/Entities/Booking.cs +++ b/src/deskstar-backend/Deskstar/Entities/Booking.cs @@ -1,18 +1,14 @@ -using System; -using System.Collections.Generic; +namespace Deskstar.Entities; -namespace Deskstar.Entities +public class Booking { - public partial class Booking - { - public Guid BookingId { get; set; } - public Guid UserId { get; set; } - public Guid DeskId { get; set; } - public DateTime Timestamp { get; set; } - public DateTime StartTime { get; set; } - public DateTime EndTime { get; set; } + public Guid BookingId { get; set; } + public Guid UserId { get; set; } + public Guid DeskId { get; set; } + public DateTime Timestamp { get; set; } + public DateTime StartTime { get; set; } + public DateTime EndTime { get; set; } - public virtual Desk Desk { get; set; } = null!; - public virtual User User { get; set; } = null!; - } + public virtual Desk Desk { get; set; } = null!; + public virtual User User { get; set; } = null!; } diff --git a/src/deskstar-backend/Deskstar/Entities/Building.cs b/src/deskstar-backend/Deskstar/Entities/Building.cs index cf1fde0d..99b39c01 100644 --- a/src/deskstar-backend/Deskstar/Entities/Building.cs +++ b/src/deskstar-backend/Deskstar/Entities/Building.cs @@ -1,22 +1,18 @@ -using System; -using System.Collections.Generic; +namespace Deskstar.Entities; -namespace Deskstar.Entities +public class Building { - public partial class Building - { - public Building() - { - Floors = new HashSet(); - } + public Building() + { + Floors = new HashSet(); + } - public Guid BuildingId { get; set; } - public string BuildingName { get; set; } = null!; - public Guid CompanyId { get; set; } - public string Location { get; set; } = null!; - public bool IsMarkedForDeletion { get; set; } = false; + public Guid BuildingId { get; set; } + public string BuildingName { get; set; } = null!; + public Guid CompanyId { get; set; } + public string Location { get; set; } = null!; + public bool IsMarkedForDeletion { get; set; } = false; - public virtual Company Company { get; set; } = null!; - public virtual ICollection Floors { get; set; } - } + public virtual Company Company { get; set; } = null!; + public virtual ICollection Floors { get; set; } } diff --git a/src/deskstar-backend/Deskstar/Entities/Company.cs b/src/deskstar-backend/Deskstar/Entities/Company.cs index 7c74daac..3288432c 100644 --- a/src/deskstar-backend/Deskstar/Entities/Company.cs +++ b/src/deskstar-backend/Deskstar/Entities/Company.cs @@ -1,24 +1,23 @@ -namespace Deskstar.Entities +namespace Deskstar.Entities; + +public class Company { - public partial class Company - { - public static readonly Company Null = new Company(); - - public Company() - { - Buildings = new HashSet(); - DeskTypes = new HashSet(); - Roles = new HashSet(); - Users = new HashSet(); - } + public static readonly Company Null = new(); + + public Company() + { + Buildings = new HashSet(); + DeskTypes = new HashSet(); + Roles = new HashSet(); + Users = new HashSet(); + } - public Guid CompanyId { get; set; } - public string CompanyName { get; set; } = null!; - public bool? Logo { get; set; } + public Guid CompanyId { get; set; } + public string CompanyName { get; set; } = null!; + public bool? Logo { get; set; } - public virtual ICollection Buildings { get; set; } - public virtual ICollection DeskTypes { get; set; } - public virtual ICollection Roles { get; set; } - public virtual ICollection Users { get; set; } - } + public virtual ICollection Buildings { get; set; } + public virtual ICollection DeskTypes { get; set; } + public virtual ICollection Roles { get; set; } + public virtual ICollection Users { get; set; } } diff --git a/src/deskstar-backend/Deskstar/Entities/Desk.cs b/src/deskstar-backend/Deskstar/Entities/Desk.cs index 64430bcc..29821d97 100644 --- a/src/deskstar-backend/Deskstar/Entities/Desk.cs +++ b/src/deskstar-backend/Deskstar/Entities/Desk.cs @@ -1,23 +1,19 @@ -using System; -using System.Collections.Generic; +namespace Deskstar.Entities; -namespace Deskstar.Entities +public class Desk { - public partial class Desk - { - public Desk() - { - Bookings = new HashSet(); - } + public Desk() + { + Bookings = new HashSet(); + } - public Guid DeskId { get; set; } - public string DeskName { get; set; } = null!; - public Guid RoomId { get; set; } - public Guid DeskTypeId { get; set; } - public bool IsMarkedForDeletion { get; set; } = false; + public Guid DeskId { get; set; } + public string DeskName { get; set; } = null!; + public Guid RoomId { get; set; } + public Guid DeskTypeId { get; set; } + public bool IsMarkedForDeletion { get; set; } = false; - public virtual DeskType DeskType { get; set; } = null!; - public virtual Room Room { get; set; } = null!; - public virtual ICollection Bookings { get; set; } - } + public virtual DeskType DeskType { get; set; } = null!; + public virtual Room Room { get; set; } = null!; + public virtual ICollection Bookings { get; set; } } diff --git a/src/deskstar-backend/Deskstar/Entities/DeskType.cs b/src/deskstar-backend/Deskstar/Entities/DeskType.cs index e2c98cd8..4833d047 100644 --- a/src/deskstar-backend/Deskstar/Entities/DeskType.cs +++ b/src/deskstar-backend/Deskstar/Entities/DeskType.cs @@ -1,21 +1,17 @@ -using System; -using System.Collections.Generic; +namespace Deskstar.Entities; -namespace Deskstar.Entities +public class DeskType { - public partial class DeskType - { - public DeskType() - { - Desks = new HashSet(); - } + public DeskType() + { + Desks = new HashSet(); + } - public Guid DeskTypeId { get; set; } - public string DeskTypeName { get; set; } = null!; - public Guid CompanyId { get; set; } - public bool IsMarkedForDeletion { get; set; } = false; + public Guid DeskTypeId { get; set; } + public string DeskTypeName { get; set; } = null!; + public Guid CompanyId { get; set; } + public bool IsMarkedForDeletion { get; set; } = false; - public virtual Company Company { get; set; } = null!; - public virtual ICollection Desks { get; set; } - } + public virtual Company Company { get; set; } = null!; + public virtual ICollection Desks { get; set; } } diff --git a/src/deskstar-backend/Deskstar/Entities/Floor.cs b/src/deskstar-backend/Deskstar/Entities/Floor.cs index 2e02ff97..932ef210 100644 --- a/src/deskstar-backend/Deskstar/Entities/Floor.cs +++ b/src/deskstar-backend/Deskstar/Entities/Floor.cs @@ -1,21 +1,17 @@ -using System; -using System.Collections.Generic; +namespace Deskstar.Entities; -namespace Deskstar.Entities +public class Floor { - public partial class Floor - { - public Floor() - { - Rooms = new HashSet(); - } + public Floor() + { + Rooms = new HashSet(); + } - public Guid FloorId { get; set; } - public Guid BuildingId { get; set; } - public string FloorName { get; set; } = null!; - public bool IsMarkedForDeletion { get; set; } = false; + public Guid FloorId { get; set; } + public Guid BuildingId { get; set; } + public string FloorName { get; set; } = null!; + public bool IsMarkedForDeletion { get; set; } = false; - public virtual Building Building { get; set; } = null!; - public virtual ICollection Rooms { get; set; } - } + public virtual Building Building { get; set; } = null!; + public virtual ICollection Rooms { get; set; } } diff --git a/src/deskstar-backend/Deskstar/Entities/Role.cs b/src/deskstar-backend/Deskstar/Entities/Role.cs index b141f342..8d9260b0 100644 --- a/src/deskstar-backend/Deskstar/Entities/Role.cs +++ b/src/deskstar-backend/Deskstar/Entities/Role.cs @@ -1,21 +1,17 @@ -using System; -using System.Collections.Generic; +namespace Deskstar.Entities; -namespace Deskstar.Entities +public class Role { - public partial class Role - { - public Role() - { - Users = new HashSet(); - } + public Role() + { + Users = new HashSet(); + } - public Guid RoleId { get; set; } - public string RoleName { get; set; } = null!; - public Guid CompanyId { get; set; } + public Guid RoleId { get; set; } + public string RoleName { get; set; } = null!; + public Guid CompanyId { get; set; } - public virtual Company Company { get; set; } = null!; + public virtual Company Company { get; set; } = null!; - public virtual ICollection Users { get; set; } - } + public virtual ICollection Users { get; set; } } diff --git a/src/deskstar-backend/Deskstar/Entities/Room.cs b/src/deskstar-backend/Deskstar/Entities/Room.cs index 18273a94..c92bdb9d 100644 --- a/src/deskstar-backend/Deskstar/Entities/Room.cs +++ b/src/deskstar-backend/Deskstar/Entities/Room.cs @@ -1,21 +1,17 @@ -using System; -using System.Collections.Generic; +namespace Deskstar.Entities; -namespace Deskstar.Entities +public class Room { - public partial class Room - { - public Room() - { - Desks = new HashSet(); - } + public Room() + { + Desks = new HashSet(); + } - public Guid RoomId { get; set; } - public Guid FloorId { get; set; } - public string RoomName { get; set; } = null!; - public bool IsMarkedForDeletion { get; set; } = false; + public Guid RoomId { get; set; } + public Guid FloorId { get; set; } + public string RoomName { get; set; } = null!; + public bool IsMarkedForDeletion { get; set; } = false; - public virtual Floor Floor { get; set; } = null!; - public virtual ICollection Desks { get; set; } - } + public virtual Floor Floor { get; set; } = null!; + public virtual ICollection Desks { get; set; } } diff --git a/src/deskstar-backend/Deskstar/Entities/User.cs b/src/deskstar-backend/Deskstar/Entities/User.cs index ef9bcd9f..84f31f35 100644 --- a/src/deskstar-backend/Deskstar/Entities/User.cs +++ b/src/deskstar-backend/Deskstar/Entities/User.cs @@ -1,30 +1,29 @@ -namespace Deskstar.Entities +namespace Deskstar.Entities; + +public class User { - public partial class User - { - public static readonly User Null = new User(); + public static readonly User Null = new(); - public User() - { - Bookings = new HashSet(); - Roles = new HashSet(); - } + public User() + { + Bookings = new HashSet(); + Roles = new HashSet(); + } - public Guid UserId { get; set; } - public string FirstName { get; set; } = null!; - public string LastName { get; set; } = null!; - public string MailAddress { get; set; } = null!; - public string Password { get; set; } = null!; - public Guid CompanyId { get; set; } - public bool IsApproved { get; set; } + public Guid UserId { get; set; } + public string FirstName { get; set; } = null!; + public string LastName { get; set; } = null!; + public string MailAddress { get; set; } = null!; + public string Password { get; set; } = null!; + public Guid CompanyId { get; set; } + public bool IsApproved { get; set; } - public bool IsCompanyAdmin { get; set; } + public bool IsCompanyAdmin { get; set; } - public bool IsMarkedForDeletion { get; set; } = false; + public bool IsMarkedForDeletion { get; set; } = false; - public virtual Company Company { get; set; } = null!; - public virtual ICollection Bookings { get; set; } + public virtual Company Company { get; set; } = null!; + public virtual ICollection Bookings { get; set; } - public virtual ICollection Roles { get; set; } - } + public virtual ICollection Roles { get; set; } } diff --git a/src/deskstar-backend/Deskstar/EnumSchemaFilter.cs b/src/deskstar-backend/Deskstar/EnumSchemaFilter.cs index 3eebc2b0..2057c4ed 100644 --- a/src/deskstar-backend/Deskstar/EnumSchemaFilter.cs +++ b/src/deskstar-backend/Deskstar/EnumSchemaFilter.cs @@ -1,5 +1,4 @@ -using System.Reflection; -using System.Runtime.Serialization; +using System.Runtime.Serialization; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; @@ -8,24 +7,24 @@ namespace Deskstar; public class EnumSchemaFilter : ISchemaFilter { - public void Apply(OpenApiSchema model, SchemaFilterContext context) + public void Apply(OpenApiSchema model, SchemaFilterContext context) + { + if (context.Type.IsEnum) { - if (context.Type.IsEnum) - { - model.Enum.Clear(); - foreach (string enumName in Enum.GetNames(context.Type)) - { - MemberInfo? memberInfo = context.Type.GetMember(enumName) - .FirstOrDefault(m => m.DeclaringType == context.Type); - EnumMemberAttribute? enumMemberAttribute = memberInfo == null - ? null - : memberInfo.GetCustomAttributes(typeof(EnumMemberAttribute), false).OfType() - .FirstOrDefault(); - string label = enumMemberAttribute == null || string.IsNullOrWhiteSpace(enumMemberAttribute.Value) - ? enumName - : enumMemberAttribute.Value; - model.Enum.Add(new OpenApiString(label)); - } - } + model.Enum.Clear(); + foreach (var enumName in Enum.GetNames(context.Type)) + { + var memberInfo = context.Type.GetMember(enumName) + .FirstOrDefault(m => m.DeclaringType == context.Type); + var enumMemberAttribute = memberInfo == null + ? null + : memberInfo.GetCustomAttributes(typeof(EnumMemberAttribute), false).OfType() + .FirstOrDefault(); + var label = enumMemberAttribute == null || string.IsNullOrWhiteSpace(enumMemberAttribute.Value) + ? enumName + : enumMemberAttribute.Value; + model.Enum.Add(new OpenApiString(label)); + } } -} \ No newline at end of file + } +} diff --git a/src/deskstar-backend/Deskstar/Models/AutoMapperConfiguration.cs b/src/deskstar-backend/Deskstar/Models/AutoMapperConfiguration.cs index f7c888f0..c2e9ec06 100644 --- a/src/deskstar-backend/Deskstar/Models/AutoMapperConfiguration.cs +++ b/src/deskstar-backend/Deskstar/Models/AutoMapperConfiguration.cs @@ -1,34 +1,33 @@ using AutoMapper; -namespace Deskstar.Models +namespace Deskstar.Models; + +public interface IAutoMapperConfiguration { - public interface IAutoMapperConfiguration - { - public MapperConfiguration GetConfiguration(); - } + public MapperConfiguration GetConfiguration(); +} - public class AutoMapperConfiguration : IAutoMapperConfiguration +public class AutoMapperConfiguration : IAutoMapperConfiguration +{ + public MapperConfiguration GetConfiguration() { - public MapperConfiguration GetConfiguration() + var config = new MapperConfiguration(cfg => { - var config = new MapperConfiguration(cfg => - { - UserProfileDto.CreateMappings(cfg); - UserProfileCompanyDto.createMappings(cfg); - DeskTypeDto.createMappings(cfg); - ExtendedBooking.createMappings(cfg); - CreateBuildingResponseObject.createMappings(cfg); - CreateDeskResponseObject.createMappings(cfg); - CreateDeskTypeResponseObject.createMappings(cfg); - CreateFloorResponseObject.createMappings(cfg); - CreateRoomResponseObject.createMappings(cfg); - UpdateBuildingResponseObject.createMappings(cfg); - UpdateDeskResponseObject.createMappings(cfg); - UpdateDeskTypeResponseObject.createMappings(cfg); - UpdateFloorResponseObject.createMappings(cfg); - UpdateRoomResponseObject.createMappings(cfg); - }); - return config; - } + UserProfileDto.CreateMappings(cfg); + UserProfileCompanyDto.createMappings(cfg); + DeskTypeDto.createMappings(cfg); + ExtendedBooking.createMappings(cfg); + CreateBuildingResponseObject.createMappings(cfg); + CreateDeskResponseObject.createMappings(cfg); + CreateDeskTypeResponseObject.createMappings(cfg); + CreateFloorResponseObject.createMappings(cfg); + CreateRoomResponseObject.createMappings(cfg); + UpdateBuildingResponseObject.createMappings(cfg); + UpdateDeskResponseObject.createMappings(cfg); + UpdateDeskTypeResponseObject.createMappings(cfg); + UpdateFloorResponseObject.createMappings(cfg); + UpdateRoomResponseObject.createMappings(cfg); + }); + return config; } -} \ No newline at end of file +} diff --git a/src/deskstar-backend/Deskstar/Models/BookingRequest.cs b/src/deskstar-backend/Deskstar/Models/BookingRequest.cs index 4789247c..e0bfbe52 100644 --- a/src/deskstar-backend/Deskstar/Models/BookingRequest.cs +++ b/src/deskstar-backend/Deskstar/Models/BookingRequest.cs @@ -4,10 +4,9 @@ namespace Deskstar.Models; public class BookingRequest { - [Required] - public Guid DeskId { get; set; } - [Required] - public DateTime StartTime { get; set; } - [Required] - public DateTime EndTime { get; set; } -} \ No newline at end of file + [Required] public Guid DeskId { get; set; } + + [Required] public DateTime StartTime { get; set; } + + [Required] public DateTime EndTime { get; set; } +} diff --git a/src/deskstar-backend/Deskstar/Models/CompanyDto.cs b/src/deskstar-backend/Deskstar/Models/CompanyDto.cs index 0af4400e..08acf475 100644 --- a/src/deskstar-backend/Deskstar/Models/CompanyDto.cs +++ b/src/deskstar-backend/Deskstar/Models/CompanyDto.cs @@ -1,21 +1,17 @@ using System.ComponentModel.DataAnnotations; using AutoMapper; +using Deskstar.Entities; namespace Deskstar.Models; public class CompanyDto { + [Required] public string CompanyId { get; set; } = null!; + + [Required] public string CompanyName { get; set; } = null!; + public static void createMappings(IMapperConfigurationExpression cfg) { - cfg.CreateMap(); - } - public CompanyDto() - { - + cfg.CreateMap(); } - - [Required] - public string CompanyId { get; set; } = null!; - [Required] - public string CompanyName { get; set; } = null!; } diff --git a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateBuildingDto.cs b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateBuildingDto.cs index 6b411466..9f5b1eaa 100644 --- a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateBuildingDto.cs +++ b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateBuildingDto.cs @@ -4,9 +4,7 @@ namespace Deskstar.Models; public class CreateBuildingDto { - [Required] - public string BuildingName { get; set; } = null!; + [Required] public string BuildingName { get; set; } = null!; - [Required] - public string Location { get; set; } = null!; -} \ No newline at end of file + [Required] public string Location { get; set; } = null!; +} diff --git a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateBuildingResponseObject.cs b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateBuildingResponseObject.cs index 6f2350e3..d486e597 100644 --- a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateBuildingResponseObject.cs +++ b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateBuildingResponseObject.cs @@ -1,21 +1,19 @@ using System.ComponentModel.DataAnnotations; using AutoMapper; +using Deskstar.Entities; namespace Deskstar.Models; public class CreateBuildingResponseObject { - public CreateBuildingResponseObject() { } + [Required] public Guid BuildingId { get; set; } + + [Required] public string BuildingName { get; set; } = null!; + + [Required] public string Location { get; set; } = null!; public static void createMappings(IMapperConfigurationExpression cfg) { - cfg.CreateMap(); + cfg.CreateMap(); } - - [Required] - public Guid BuildingId { get; set; } - [Required] - public string BuildingName { get; set; } = null!; - [Required] - public string Location { get; set; } = null!; } diff --git a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskDto.cs b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskDto.cs index 97675a92..470814a5 100644 --- a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskDto.cs +++ b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskDto.cs @@ -4,12 +4,9 @@ namespace Deskstar.Models; public class CreateDeskDto { - [Required] - public string RoomId { get; set; } = null!; + [Required] public string RoomId { get; set; } = null!; - [Required] - public string DeskName { get; set; } = null!; + [Required] public string DeskName { get; set; } = null!; - [Required] - public string DeskTypeId { get; set; } = null!; -} \ No newline at end of file + [Required] public string DeskTypeId { get; set; } = null!; +} diff --git a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskResponseObject.cs b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskResponseObject.cs index d1d4bcd7..3480e9b9 100644 --- a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskResponseObject.cs +++ b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskResponseObject.cs @@ -1,20 +1,17 @@ using System.ComponentModel.DataAnnotations; using AutoMapper; +using Deskstar.Entities; namespace Deskstar.Models; public class CreateDeskResponseObject { - public CreateDeskResponseObject() { } + [Required] public string DeskId { get; set; } = null!; - public static void createMappings(IMapperConfigurationExpression cfg) - { - cfg.CreateMap(); - } + [Required] public string DeskName { get; set; } = null!; - [Required] - public string DeskId { get; set; } = null!; - - [Required] - public string DeskName { get; set; } = null!; -} \ No newline at end of file + public static void createMappings(IMapperConfigurationExpression cfg) + { + cfg.CreateMap(); + } +} diff --git a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskTypeDto.cs b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskTypeDto.cs index ea838b2e..eca9d775 100644 --- a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskTypeDto.cs +++ b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskTypeDto.cs @@ -4,9 +4,5 @@ namespace Deskstar.Models; public class CreateDeskTypeDto { - public CreateDeskTypeDto() { } - - [Required] - public string DeskTypeName { get; set; } = null!; - -} \ No newline at end of file + [Required] public string DeskTypeName { get; set; } = null!; +} diff --git a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskTypeResponseObject.cs b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskTypeResponseObject.cs index 0ac38f56..2109d17f 100644 --- a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskTypeResponseObject.cs +++ b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateDeskTypeResponseObject.cs @@ -1,21 +1,17 @@ using System.ComponentModel.DataAnnotations; using AutoMapper; +using Deskstar.Entities; namespace Deskstar.Models; public class CreateDeskTypeResponseObject { - public CreateDeskTypeResponseObject() { } + [Required] public Guid DeskTypeId { get; set; } - public static void createMappings(IMapperConfigurationExpression cfg) - { - cfg.CreateMap(); - } + [Required] public string DeskTypeName { get; set; } = null!; - [Required] - public Guid DeskTypeId { get; set; } - - [Required] - public string DeskTypeName { get; set; } = null!; - -} \ No newline at end of file + public static void createMappings(IMapperConfigurationExpression cfg) + { + cfg.CreateMap(); + } +} diff --git a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateFloorDto.cs b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateFloorDto.cs index a0b6f9e1..91662fce 100644 --- a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateFloorDto.cs +++ b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateFloorDto.cs @@ -4,11 +4,7 @@ namespace Deskstar.Models; public class CreateFloorDto { - public CreateFloorDto() { } + [Required] public string BuildingId { get; set; } = null!; - [Required] - public string BuildingId { get; set; } = null!; - - [Required] - public string FloorName { get; set; } = null!; -} \ No newline at end of file + [Required] public string FloorName { get; set; } = null!; +} diff --git a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateFloorResponseObject.cs b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateFloorResponseObject.cs index 071956e9..fd69a81d 100644 --- a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateFloorResponseObject.cs +++ b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateFloorResponseObject.cs @@ -1,20 +1,17 @@ using System.ComponentModel.DataAnnotations; using AutoMapper; +using Deskstar.Entities; namespace Deskstar.Models; public class CreateFloorResponseObject { - public CreateFloorResponseObject() { } + [Required] public Guid FloorId { get; set; } - public static void createMappings(IMapperConfigurationExpression cfg) - { - cfg.CreateMap(); - } + [Required] public string FloorName { get; set; } = null!; - [Required] - public Guid FloorId { get; set; } - - [Required] - public string FloorName { get; set; } = null!; -} \ No newline at end of file + public static void createMappings(IMapperConfigurationExpression cfg) + { + cfg.CreateMap(); + } +} diff --git a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateRoomDto.cs b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateRoomDto.cs index 91dc4093..4bb0f928 100644 --- a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateRoomDto.cs +++ b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateRoomDto.cs @@ -4,11 +4,7 @@ namespace Deskstar.Models; public class CreateRoomDto { - public CreateRoomDto() { } + [Required] public string FloorId { get; set; } = null!; - [Required] - public string FloorId { get; set; } = null!; - - [Required] - public string RoomName { get; set; } = null!; -} \ No newline at end of file + [Required] public string RoomName { get; set; } = null!; +} diff --git a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateRoomResponseObject.cs b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateRoomResponseObject.cs index b7a97d81..eaf94baa 100644 --- a/src/deskstar-backend/Deskstar/Models/CreateResources/CreateRoomResponseObject.cs +++ b/src/deskstar-backend/Deskstar/Models/CreateResources/CreateRoomResponseObject.cs @@ -1,20 +1,17 @@ using System.ComponentModel.DataAnnotations; using AutoMapper; +using Deskstar.Entities; namespace Deskstar.Models; public class CreateRoomResponseObject { - public CreateRoomResponseObject() { } + [Required] public Guid RoomId { get; set; } - public static void createMappings(IMapperConfigurationExpression cfg) - { - cfg.CreateMap(); - } + [Required] public string RoomName { get; set; } = null!; - [Required] - public Guid RoomId { get; set; } - - [Required] - public string RoomName { get; set; } = null!; -} \ No newline at end of file + public static void createMappings(IMapperConfigurationExpression cfg) + { + cfg.CreateMap(); + } +} diff --git a/src/deskstar-backend/Deskstar/Models/CreateTokenUser.cs b/src/deskstar-backend/Deskstar/Models/CreateTokenUser.cs index 71cd7626..3570c053 100644 --- a/src/deskstar-backend/Deskstar/Models/CreateTokenUser.cs +++ b/src/deskstar-backend/Deskstar/Models/CreateTokenUser.cs @@ -1,13 +1,10 @@ using System.ComponentModel.DataAnnotations; -namespace Deskstar.Models +namespace Deskstar.Models; + +public class CreateTokenUser { - public class CreateTokenUser - { - [Required] - public string MailAddress { get; set; } = null!; - - [Required] - public string Password { get; set; } = null!; - } -} \ No newline at end of file + [Required] public string MailAddress { get; set; } = null!; + + [Required] public string Password { get; set; } = null!; +} diff --git a/src/deskstar-backend/Deskstar/Models/CurrentBuilding.cs b/src/deskstar-backend/Deskstar/Models/CurrentBuilding.cs index ba6a960a..1c79d448 100644 --- a/src/deskstar-backend/Deskstar/Models/CurrentBuilding.cs +++ b/src/deskstar-backend/Deskstar/Models/CurrentBuilding.cs @@ -1,17 +1,14 @@ -namespace Deskstar.Models; using System.ComponentModel.DataAnnotations; + +namespace Deskstar.Models; + public class CurrentBuilding { + [Required] public string BuildingId { get; set; } = null!; - [Required] - public string BuildingId { get; set; } = null!; - - [Required] - public string Location { get; set; } = null!; + [Required] public string Location { get; set; } = null!; - [Required] - public string BuildingName { get; set; } = null!; + [Required] public string BuildingName { get; set; } = null!; [Required] public bool IsMarkedForDeletion { get; set; } = false; - } diff --git a/src/deskstar-backend/Deskstar/Models/CurrentDesk.cs b/src/deskstar-backend/Deskstar/Models/CurrentDesk.cs index 1a093045..40c8bd0f 100644 --- a/src/deskstar-backend/Deskstar/Models/CurrentDesk.cs +++ b/src/deskstar-backend/Deskstar/Models/CurrentDesk.cs @@ -1,5 +1,4 @@ using System.ComponentModel.DataAnnotations; -using Deskstar.Entities; namespace Deskstar.Models; @@ -27,13 +26,11 @@ public class CurrentDesk [Required] public bool IsMarkedForDeletion { get; set; } = false; - [Required] - public List Bookings { get; set; } = new List(); + [Required] public List Bookings { get; set; } = new(); } public class BookingDesks { - [Required] public string BookingId { get; set; } = null!; [Required] public string UserId { get; set; } = null!; diff --git a/src/deskstar-backend/Deskstar/Models/CurrentFloor.cs b/src/deskstar-backend/Deskstar/Models/CurrentFloor.cs index 82de9c1b..c63effad 100644 --- a/src/deskstar-backend/Deskstar/Models/CurrentFloor.cs +++ b/src/deskstar-backend/Deskstar/Models/CurrentFloor.cs @@ -4,20 +4,15 @@ namespace Deskstar.Models; public class CurrentFloor { - [Required] - public string FloorId { get; set; } = null!; + [Required] public string FloorId { get; set; } = null!; - [Required] - public string FloorName { get; set; } = null!; + [Required] public string FloorName { get; set; } = null!; - [Required] - public string BuildingId { get; set; } = null!; + [Required] public string BuildingId { get; set; } = null!; - [Required] - public string BuildingName { get; set; } = null!; + [Required] public string BuildingName { get; set; } = null!; - [Required] - public string Location { get; set; } = null!; + [Required] public string Location { get; set; } = null!; [Required] public bool IsMarkedForDeletion { get; set; } = false; } diff --git a/src/deskstar-backend/Deskstar/Models/CurrentRoom.cs b/src/deskstar-backend/Deskstar/Models/CurrentRoom.cs index 3aedeb51..786cdce8 100644 --- a/src/deskstar-backend/Deskstar/Models/CurrentRoom.cs +++ b/src/deskstar-backend/Deskstar/Models/CurrentRoom.cs @@ -4,24 +4,17 @@ namespace Deskstar.Models; public class CurrentRoom { - [Required] - public string RoomId { get; set; } = null!; + [Required] public string RoomId { get; set; } = null!; - [Required] - public string RoomName { get; set; } = null!; + [Required] public string RoomName { get; set; } = null!; - [Required] - public string FloorId { get; set; } = null!; + [Required] public string FloorId { get; set; } = null!; - [Required] - public string Floor { get; set; } = null!; + [Required] public string Floor { get; set; } = null!; - [Required] - public string Building { get; set; } = null!; + [Required] public string Building { get; set; } = null!; - [Required] - public string Location { get; set; } = null!; + [Required] public string Location { get; set; } = null!; [Required] public bool IsMarkedForDeletion { get; set; } = false; - } diff --git a/src/deskstar-backend/Deskstar/Models/DeskTypeDto.cs b/src/deskstar-backend/Deskstar/Models/DeskTypeDto.cs index 52263f48..e05db2ff 100644 --- a/src/deskstar-backend/Deskstar/Models/DeskTypeDto.cs +++ b/src/deskstar-backend/Deskstar/Models/DeskTypeDto.cs @@ -1,25 +1,21 @@ using AutoMapper; +using Deskstar.Entities; namespace Deskstar.Models; public class DeskTypeDto { - public static readonly UserProfileDto Null = new UserProfileDto(); + public static readonly UserProfileDto Null = new(); - public DeskTypeDto() - { + public Guid DeskTypeId { get; set; } + public string DeskTypeName { get; set; } = null!; + public Guid CompanyId { get; set; } - } + public bool IsMarkedForDeletion { get; set; } public static void createMappings(IMapperConfigurationExpression cfg) { - cfg.CreateMap(); - cfg.CreateMap(); + cfg.CreateMap(); + cfg.CreateMap(); } - - public Guid DeskTypeId { get; set; } - public string DeskTypeName { get; set; } = null!; - public Guid CompanyId { get; set; } - - public bool IsMarkedForDeletion { get; set; } = false; } diff --git a/src/deskstar-backend/Deskstar/Models/ExtendedBooking.cs b/src/deskstar-backend/Deskstar/Models/ExtendedBooking.cs index 343e2967..5f6c33a6 100644 --- a/src/deskstar-backend/Deskstar/Models/ExtendedBooking.cs +++ b/src/deskstar-backend/Deskstar/Models/ExtendedBooking.cs @@ -1,47 +1,36 @@ using System.ComponentModel.DataAnnotations; using AutoMapper; +using Deskstar.Entities; namespace Deskstar.Models; public class ExtendedBooking { - public static void createMappings(IMapperConfigurationExpression cfg) - { - cfg.CreateMap() - .ForMember(dest => dest.BuildingName, act => act.MapFrom(src => src.Desk.Room.Floor.Building.BuildingName)) - .ForMember(dest => dest.FloorName, act => act.MapFrom(src => src.Desk.Room.Floor.FloorName)) - .ForMember(dest => dest.RoomName, act => act.MapFrom(src => src.Desk.Room.RoomName)) - .ForMember(dest => dest.DeskName, act => act.MapFrom(src => src.Desk.DeskName)) - .ForMember(dest => dest.usesDeletedDesk, act => act.MapFrom(src => src.Desk.IsMarkedForDeletion)); - } - public ExtendedBooking() - { - - } public Guid BookingId { get; set; } - [Required] - public DateTime Timestamp { get; set; } + [Required] public DateTime Timestamp { get; set; } - [Required] - public DateTime StartTime { get; set; } + [Required] public DateTime StartTime { get; set; } - [Required] - public DateTime EndTime { get; set; } + [Required] public DateTime EndTime { get; set; } - [Required] - public string DeskName { get; set; } = null!; + [Required] public string DeskName { get; set; } = null!; - [Required] - public string BuildingName { get; set; } = null!; + [Required] public string BuildingName { get; set; } = null!; - [Required] - public string FloorName { get; set; } = null!; + [Required] public string FloorName { get; set; } = null!; - [Required] - public string RoomName { get; set; } = null!; + [Required] public string RoomName { get; set; } = null!; - [Required] - public bool usesDeletedDesk { get; set; } + [Required] public bool usesDeletedDesk { get; set; } + public static void createMappings(IMapperConfigurationExpression cfg) + { + cfg.CreateMap() + .ForMember(dest => dest.BuildingName, act => act.MapFrom(src => src.Desk.Room.Floor.Building.BuildingName)) + .ForMember(dest => dest.FloorName, act => act.MapFrom(src => src.Desk.Room.Floor.FloorName)) + .ForMember(dest => dest.RoomName, act => act.MapFrom(src => src.Desk.Room.RoomName)) + .ForMember(dest => dest.DeskName, act => act.MapFrom(src => src.Desk.DeskName)) + .ForMember(dest => dest.usesDeletedDesk, act => act.MapFrom(src => src.Desk.IsMarkedForDeletion)); + } } diff --git a/src/deskstar-backend/Deskstar/Models/LoginResponse.cs b/src/deskstar-backend/Deskstar/Models/LoginResponse.cs index 09cc828a..4c3c78aa 100644 --- a/src/deskstar-backend/Deskstar/Models/LoginResponse.cs +++ b/src/deskstar-backend/Deskstar/Models/LoginResponse.cs @@ -2,17 +2,15 @@ namespace Deskstar.Models; - -public enum LoginReturn{ - NotYetApproved, - CredentialsWrong, - Deleted, - Ok +public enum LoginReturn +{ + NotYetApproved, + CredentialsWrong, + Deleted, + Ok } + public class LoginResponse { - - [Required] - public LoginReturn Message{ get; set; } - + [Required] public LoginReturn Message { get; set; } } diff --git a/src/deskstar-backend/Deskstar/Models/PaginatedBookingsDto.cs b/src/deskstar-backend/Deskstar/Models/PaginatedBookingsDto.cs index 2742bee4..bdb133f7 100644 --- a/src/deskstar-backend/Deskstar/Models/PaginatedBookingsDto.cs +++ b/src/deskstar-backend/Deskstar/Models/PaginatedBookingsDto.cs @@ -2,6 +2,6 @@ namespace Deskstar.Models; public class PaginatedBookingsDto { - public int AmountOfBookings { get; set; } - public List Bookings { get; set; } = null!; -} \ No newline at end of file + public int AmountOfBookings { get; set; } + public List Bookings { get; set; } = null!; +} diff --git a/src/deskstar-backend/Deskstar/Models/RegisterAdminDto.cs b/src/deskstar-backend/Deskstar/Models/RegisterAdminDto.cs index f9f5a08c..9c354968 100644 --- a/src/deskstar-backend/Deskstar/Models/RegisterAdminDto.cs +++ b/src/deskstar-backend/Deskstar/Models/RegisterAdminDto.cs @@ -1,22 +1,16 @@ using System.ComponentModel.DataAnnotations; -namespace Deskstar.Models +namespace Deskstar.Models; + +public class RegisterAdminDto { - public class RegisterAdminDto - { - [Required] - public string MailAddress { get; set; } = null!; - - [Required] - public string FirstName { get; set; } = null!; - - [Required] - public string LastName { get; set; } = null!; - - [Required] - public string Password { get; set; } = null!; - - [Required] - public string CompanyName { get; set; } = null!; - } -} \ No newline at end of file + [Required] public string MailAddress { get; set; } = null!; + + [Required] public string FirstName { get; set; } = null!; + + [Required] public string LastName { get; set; } = null!; + + [Required] public string Password { get; set; } = null!; + + [Required] public string CompanyName { get; set; } = null!; +} diff --git a/src/deskstar-backend/Deskstar/Models/RegisterResponse.cs b/src/deskstar-backend/Deskstar/Models/RegisterResponse.cs index 2f1730c6..6ba5efa4 100644 --- a/src/deskstar-backend/Deskstar/Models/RegisterResponse.cs +++ b/src/deskstar-backend/Deskstar/Models/RegisterResponse.cs @@ -4,13 +4,12 @@ namespace Deskstar.Models; public enum RegisterReturn { - Ok, - MailAddressInUse, - CompanyNotFound + Ok, + MailAddressInUse, + CompanyNotFound } public class RegisterResponse { - [Required] - public RegisterReturn Message { get; set; } -} \ No newline at end of file + [Required] public RegisterReturn Message { get; set; } +} diff --git a/src/deskstar-backend/Deskstar/Models/RegisterUser.cs b/src/deskstar-backend/Deskstar/Models/RegisterUser.cs index 8ad3c0ef..705b2f95 100644 --- a/src/deskstar-backend/Deskstar/Models/RegisterUser.cs +++ b/src/deskstar-backend/Deskstar/Models/RegisterUser.cs @@ -1,22 +1,16 @@ using System.ComponentModel.DataAnnotations; -namespace Deskstar.Models +namespace Deskstar.Models; + +public class RegisterUser { - public class RegisterUser - { - [Required] - public string MailAddress { get; set; } = null!; - - [Required] - public string FirstName { get; set; } = null!; - - [Required] - public string LastName { get; set; } = null!; - - [Required] - public string Password { get; set; } = null!; - - [Required] - public Guid CompanyId { get; set; } - } -} \ No newline at end of file + [Required] public string MailAddress { get; set; } = null!; + + [Required] public string FirstName { get; set; } = null!; + + [Required] public string LastName { get; set; } = null!; + + [Required] public string Password { get; set; } = null!; + + [Required] public Guid CompanyId { get; set; } +} diff --git a/src/deskstar-backend/Deskstar/Models/UpdateBookingRequest.cs b/src/deskstar-backend/Deskstar/Models/UpdateBookingRequest.cs index 22c6c3e0..a15cf827 100644 --- a/src/deskstar-backend/Deskstar/Models/UpdateBookingRequest.cs +++ b/src/deskstar-backend/Deskstar/Models/UpdateBookingRequest.cs @@ -1,10 +1,10 @@ using System.ComponentModel.DataAnnotations; namespace Deskstar.Models; + public class UpdateBookingRequest { - [Required] - public DateTime StartTime { get; set; } - [Required] - public DateTime EndTime { get; set; } -} \ No newline at end of file + [Required] public DateTime StartTime { get; set; } + + [Required] public DateTime EndTime { get; set; } +} diff --git a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateBuildingDto.cs b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateBuildingDto.cs index b6579ec6..88b1e44b 100644 --- a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateBuildingDto.cs +++ b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateBuildingDto.cs @@ -1,6 +1,7 @@ namespace Deskstar.Models; -public class UpdateBuildingDto{ - public string? BuildingName {get;set;} - public string? Location {get;set;} +public class UpdateBuildingDto +{ + public string? BuildingName { get; set; } + public string? Location { get; set; } } diff --git a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateBuildingResponseObject.cs b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateBuildingResponseObject.cs index 904e8765..a0baa34d 100644 --- a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateBuildingResponseObject.cs +++ b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateBuildingResponseObject.cs @@ -1,18 +1,19 @@ using System.ComponentModel.DataAnnotations; using AutoMapper; +using Deskstar.Entities; namespace Deskstar.Models; public class UpdateBuildingResponseObject { + [Required] public Guid BuildingId { get; set; } + + [Required] public string BuildingName { get; set; } = null!; + + [Required] public string Location { get; set; } = null!; + public static void createMappings(IMapperConfigurationExpression cfg) { - cfg.CreateMap(); + cfg.CreateMap(); } - [Required] - public Guid BuildingId { get; set; } - [Required] - public string BuildingName { get; set; } = null!; - [Required] - public string Location { get; set; } = null!; -} \ No newline at end of file +} diff --git a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskDto.cs b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskDto.cs index ef5b1102..9b106154 100644 --- a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskDto.cs +++ b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskDto.cs @@ -2,7 +2,7 @@ namespace Deskstar.Models; public class UpdateDeskDto { - public string? DeskName {get;set;} - public string? RoomId {get;set;} - public string? DeskTypeId {get;set;} -} \ No newline at end of file + public string? DeskName { get; set; } + public string? RoomId { get; set; } + public string? DeskTypeId { get; set; } +} diff --git a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskResponseObject.cs b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskResponseObject.cs index ce47cebd..3080324a 100644 --- a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskResponseObject.cs +++ b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskResponseObject.cs @@ -1,43 +1,44 @@ using System.ComponentModel.DataAnnotations; using AutoMapper; +using Deskstar.Entities; namespace Deskstar.Models; public class UpdateDeskResponseObject { + [Required] public Guid DeskId { get; set; } + + [Required] public string DeskName { get; set; } = null!; + + [Required] public Guid DeskTypeId { get; set; } + + [Required] public string DeskTypeName { get; set; } = null!; + + [Required] public Guid RoomId { get; set; } + + [Required] public string RoomName { get; set; } = null!; + + [Required] public Guid FloorId { get; set; } + + [Required] public string FloorName { get; set; } = null!; + + [Required] public Guid BuildingId { get; set; } + + [Required] public string BuildingName { get; set; } = null!; + + [Required] public string Location { get; set; } = null!; + public static void createMappings(IMapperConfigurationExpression cfg) { - cfg.CreateMap() - .ForMember(dest => dest.BuildingId, act => act.MapFrom(src => src.Room.Floor.Building.BuildingId)) - .ForMember(dest => dest.BuildingName, act => act.MapFrom(src => src.Room.Floor.Building.BuildingName)) - .ForMember(dest => dest.Location, act => act.MapFrom(src => src.Room.Floor.Building.Location)) - .ForMember(dest => dest.FloorId, act => act.MapFrom(src => src.Room.Floor.FloorId)) - .ForMember(dest => dest.FloorName, act => act.MapFrom(src => src.Room.Floor.FloorName)) - .ForMember(dest => dest.Location, act => act.MapFrom(src => src.Room.Floor.Building.Location)) - .ForMember(dest => dest.RoomId, act => act.MapFrom(src => src.Room.RoomId)) - .ForMember(dest => dest.RoomName, act => act.MapFrom(src => src.Room.RoomName)) - .ForMember(dest => dest.DeskTypeName, act => act.MapFrom(src => src.DeskType.DeskTypeName)); + cfg.CreateMap() + .ForMember(dest => dest.BuildingId, act => act.MapFrom(src => src.Room.Floor.Building.BuildingId)) + .ForMember(dest => dest.BuildingName, act => act.MapFrom(src => src.Room.Floor.Building.BuildingName)) + .ForMember(dest => dest.Location, act => act.MapFrom(src => src.Room.Floor.Building.Location)) + .ForMember(dest => dest.FloorId, act => act.MapFrom(src => src.Room.Floor.FloorId)) + .ForMember(dest => dest.FloorName, act => act.MapFrom(src => src.Room.Floor.FloorName)) + .ForMember(dest => dest.Location, act => act.MapFrom(src => src.Room.Floor.Building.Location)) + .ForMember(dest => dest.RoomId, act => act.MapFrom(src => src.Room.RoomId)) + .ForMember(dest => dest.RoomName, act => act.MapFrom(src => src.Room.RoomName)) + .ForMember(dest => dest.DeskTypeName, act => act.MapFrom(src => src.DeskType.DeskTypeName)); } - [Required] - public Guid DeskId { get; set; } - [Required] - public string DeskName { get; set; } = null!; - [Required] - public Guid DeskTypeId { get; set; } - [Required] - public string DeskTypeName { get; set; } = null!; - [Required] - public Guid RoomId { get; set; } - [Required] - public string RoomName { get; set; } = null!; - [Required] - public Guid FloorId { get; set; } - [Required] - public string FloorName { get; set; } = null!; - [Required] - public Guid BuildingId { get; set; } - [Required] - public string BuildingName { get; set; } = null!; - [Required] - public string Location { get; set; } = null!; -} \ No newline at end of file +} diff --git a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskTypeDto.cs b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskTypeDto.cs index c90c595b..fd6a5662 100644 --- a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskTypeDto.cs +++ b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskTypeDto.cs @@ -1,5 +1,6 @@ namespace Deskstar.Models; -public class UpdateDeskTypeDto{ - public string? DeskTypeName {get;set;} -} \ No newline at end of file +public class UpdateDeskTypeDto +{ + public string? DeskTypeName { get; set; } +} diff --git a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskTypeResponseObject.cs b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskTypeResponseObject.cs index 30af5024..050c9c6b 100644 --- a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskTypeResponseObject.cs +++ b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateDeskTypeResponseObject.cs @@ -1,17 +1,17 @@ using System.ComponentModel.DataAnnotations; using AutoMapper; +using Deskstar.Entities; namespace Deskstar.Models; public class UpdateDeskTypeResponseObject { + [Required] public Guid DeskTypeId { get; set; } + + [Required] public string DeskTypeName { get; set; } = null!; + public static void createMappings(IMapperConfigurationExpression cfg) { - cfg.CreateMap(); + cfg.CreateMap(); } - [Required] - public Guid DeskTypeId { get; set; } - [Required] - public string DeskTypeName { get; set; } = null!; - -} \ No newline at end of file +} diff --git a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateFloorDto.cs b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateFloorDto.cs index c022b1f0..bcb4cad3 100644 --- a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateFloorDto.cs +++ b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateFloorDto.cs @@ -1,6 +1,7 @@ namespace Deskstar.Models; -public class UpdateFloorDto{ - public string? FloorName {get;set;} - public string? BuildingId {get;set;} -} \ No newline at end of file +public class UpdateFloorDto +{ + public string? FloorName { get; set; } + public string? BuildingId { get; set; } +} diff --git a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateFloorResponseObject.cs b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateFloorResponseObject.cs index e4aec858..d249bfc3 100644 --- a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateFloorResponseObject.cs +++ b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateFloorResponseObject.cs @@ -1,25 +1,25 @@ using System.ComponentModel.DataAnnotations; using AutoMapper; +using Deskstar.Entities; namespace Deskstar.Models; public class UpdateFloorResponseObject { + [Required] public Guid FloorId { get; set; } + + [Required] public string FloorName { get; set; } = null!; + + [Required] public Guid BuildingId { get; set; } + + [Required] public string BuildingName { get; set; } = null!; + + [Required] public string Location { get; set; } = null!; + public static void createMappings(IMapperConfigurationExpression cfg) { - cfg.CreateMap() - .ForMember(dest => dest.BuildingName, act => act.MapFrom(src => src.Building.BuildingName)) - .ForMember(dest => dest.Location, act => act.MapFrom(src => src.Building.Location)); + cfg.CreateMap() + .ForMember(dest => dest.BuildingName, act => act.MapFrom(src => src.Building.BuildingName)) + .ForMember(dest => dest.Location, act => act.MapFrom(src => src.Building.Location)); } - - [Required] - public Guid FloorId { get; set; } - [Required] - public string FloorName { get; set; } = null!; - [Required] - public Guid BuildingId { get; set; } - [Required] - public string BuildingName { get; set; } = null!; - [Required] - public string Location { get; set; } = null!; -} \ No newline at end of file +} diff --git a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateRoomDto.cs b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateRoomDto.cs index 016e84fd..fe42bb16 100644 --- a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateRoomDto.cs +++ b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateRoomDto.cs @@ -2,6 +2,6 @@ namespace Deskstar.Models; public class UpdateRoomDto { - public string? FloorId {get;set;} - public string? RoomName {get;set;} -} \ No newline at end of file + public string? FloorId { get; set; } + public string? RoomName { get; set; } +} diff --git a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateRoomResponseObject.cs b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateRoomResponseObject.cs index 6c764dad..5eba064f 100644 --- a/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateRoomResponseObject.cs +++ b/src/deskstar-backend/Deskstar/Models/UpdateResources/UpdateRoomResponseObject.cs @@ -1,30 +1,31 @@ using System.ComponentModel.DataAnnotations; using AutoMapper; +using Deskstar.Entities; namespace Deskstar.Models; public class UpdateRoomResponseObject { + public Guid RoomId { get; set; } + + [Required] public string RoomName { get; set; } = null!; + + [Required] public Guid FloorId { get; set; } + + [Required] public string FloorName { get; set; } = null!; + + [Required] public Guid BuildingId { get; set; } + + [Required] public string BuildingName { get; set; } = null!; + + [Required] public string Location { get; set; } = null!; public static void createMappings(IMapperConfigurationExpression cfg) { - cfg.CreateMap() - .ForMember(dest => dest.BuildingName, act => act.MapFrom(src => src.Floor.Building.BuildingName)) - .ForMember(dest => dest.BuildingId, act => act.MapFrom(src => src.Floor.Building.BuildingId)) - .ForMember(dest => dest.FloorName, act => act.MapFrom(src => src.Floor.FloorName)) - .ForMember(dest => dest.Location, act => act.MapFrom(src => src.Floor.Building.Location)); + cfg.CreateMap() + .ForMember(dest => dest.BuildingName, act => act.MapFrom(src => src.Floor.Building.BuildingName)) + .ForMember(dest => dest.BuildingId, act => act.MapFrom(src => src.Floor.Building.BuildingId)) + .ForMember(dest => dest.FloorName, act => act.MapFrom(src => src.Floor.FloorName)) + .ForMember(dest => dest.Location, act => act.MapFrom(src => src.Floor.Building.Location)); } - public Guid RoomId { get; set; } - [Required] - public string RoomName { get; set; } = null!; - [Required] - public Guid FloorId { get; set; } - [Required] - public string FloorName { get; set; } = null!; - [Required] - public Guid BuildingId { get; set; } - [Required] - public string BuildingName { get; set; } = null!; - [Required] - public string Location { get; set; } = null!; -} \ No newline at end of file +} diff --git a/src/deskstar-backend/Deskstar/Models/UserProfileCompanyDto.cs b/src/deskstar-backend/Deskstar/Models/UserProfileCompanyDto.cs index f549d656..b6aa1735 100644 --- a/src/deskstar-backend/Deskstar/Models/UserProfileCompanyDto.cs +++ b/src/deskstar-backend/Deskstar/Models/UserProfileCompanyDto.cs @@ -1,23 +1,18 @@ using AutoMapper; +using Deskstar.Entities; -namespace Deskstar.Models -{ - public class UserProfileCompanyDto - { - public static readonly UserProfileCompanyDto Null = new UserProfileCompanyDto(); - - public static void createMappings(IMapperConfigurationExpression cfg) - { - cfg.CreateMap(); - } +namespace Deskstar.Models; - public UserProfileCompanyDto() - { +public class UserProfileCompanyDto +{ + public static readonly UserProfileCompanyDto Null = new(); - } + public Guid CompanyId { get; set; } + public string CompanyName { get; set; } = null!; + public bool? Logo { get; set; } - public Guid CompanyId { get; set; } - public string CompanyName { get; set; } = null!; - public bool? Logo { get; set; } - } + public static void createMappings(IMapperConfigurationExpression cfg) + { + cfg.CreateMap(); + } } diff --git a/src/deskstar-backend/Deskstar/Models/UserProfileDto.cs b/src/deskstar-backend/Deskstar/Models/UserProfileDto.cs index fc9b20ef..777fd3bb 100644 --- a/src/deskstar-backend/Deskstar/Models/UserProfileDto.cs +++ b/src/deskstar-backend/Deskstar/Models/UserProfileDto.cs @@ -7,37 +7,33 @@ * * MIT License */ -using AutoMapper; -namespace Deskstar.Models -{ - public class UserProfileDto - { - public static readonly UserProfileDto Null = new UserProfileDto(); +using AutoMapper; +using Deskstar.Entities; - public UserProfileDto() - { +namespace Deskstar.Models; - } +public class UserProfileDto +{ + public static readonly UserProfileDto Null = new(); - public static void CreateMappings(IMapperConfigurationExpression cfg) - { - cfg.CreateMap() - .ForMember(dest => dest.Company, act => act.MapFrom(src => src.Company)); - cfg.CreateMap() - .ForMember(dest => dest.Company, act => act.MapFrom(src => src.Company)); - } + public Guid UserId { get; set; } + public string FirstName { get; set; } = null!; + public string LastName { get; set; } = null!; + public string MailAddress { get; set; } = null!; + public Guid CompanyId { get; set; } + public bool IsApproved { get; set; } + public bool IsCompanyAdmin { get; set; } - public Guid UserId { get; set; } - public string FirstName { get; set; } = null!; - public string LastName { get; set; } = null!; - public string MailAddress { get; set; } = null!; - public Guid CompanyId { get; set; } - public bool IsApproved { get; set; } - public bool IsCompanyAdmin { get; set; } + public bool IsMarkedForDeletion { get; set; } - public bool IsMarkedForDeletion { get; set; } + public UserProfileCompanyDto? Company { get; set; } - public UserProfileCompanyDto? Company { get; set; } + public static void CreateMappings(IMapperConfigurationExpression cfg) + { + cfg.CreateMap() + .ForMember(dest => dest.Company, act => act.MapFrom(src => src.Company)); + cfg.CreateMap() + .ForMember(dest => dest.Company, act => act.MapFrom(src => src.Company)); } } diff --git a/src/deskstar-backend/Deskstar/Program.cs b/src/deskstar-backend/Deskstar/Program.cs index cc9141b2..1e4ff903 100644 --- a/src/deskstar-backend/Deskstar/Program.cs +++ b/src/deskstar-backend/Deskstar/Program.cs @@ -7,17 +7,15 @@ * * MIT License */ + using System.Text; -using AutoMapper; using Deskstar; using Deskstar.Core; - using Deskstar.DataAccess; using Deskstar.Helper; using Deskstar.Models; using Deskstar.Usecases; using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; @@ -62,9 +60,10 @@ if (dbHost == null || dbDatabase == null || dbUsername == null || dbPassword == null) { Console.Error.WriteLine($"missing db configuration. database configuration has host({dbHost != null})," + - $"database name({dbDatabase != null}), username({dbUsername != null}), password({dbPassword != null})"); + $"database name({dbDatabase != null}), username({dbUsername != null}), password({dbPassword != null})"); return; } + var emailPassword = builder.Configuration.GetValue(Constants.CONFIG_EMAIL_PASSWORD) ?? null; var emailHost = builder.Configuration.GetValue(Constants.CONFIG_EMAIL_HOST) ?? null; var emailPort = builder.Configuration.GetValue(Constants.CONFIG_EMAIL_PORT); @@ -76,7 +75,8 @@ return; } -builder.Services.AddDbContext(options => options.UseNpgsql($"Host={dbHost};Database={dbDatabase};Username={dbUsername};Password={dbPassword}")); +builder.Services.AddDbContext(options => + options.UseNpgsql($"Host={dbHost};Database={dbDatabase};Username={dbUsername};Password={dbPassword}")); EmailHelper.SetMailPort(emailPort); EmailHelper.SetMailHost(emailHost); EmailHelper.SetMailUsername(emailUsername); @@ -92,9 +92,9 @@ var app = builder.Build(); // global cors policy app.UseCors(x => x - .AllowAnyOrigin() - .AllowAnyMethod() - .AllowAnyHeader()); + .AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader()); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) diff --git a/src/deskstar-backend/Deskstar/Usecases/AuthUsecases.cs b/src/deskstar-backend/Deskstar/Usecases/AuthUsecases.cs index 4e189f73..6d9c9901 100644 --- a/src/deskstar-backend/Deskstar/Usecases/AuthUsecases.cs +++ b/src/deskstar-backend/Deskstar/Usecases/AuthUsecases.cs @@ -1,233 +1,223 @@ -using Deskstar.DataAccess; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; -using System.Security.Cryptography; using System.Text; -using Microsoft.IdentityModel.Tokens; -using Deskstar.Models; -using Deskstar.Entities; -using Microsoft.AspNetCore.Cryptography.KeyDerivation; -using Microsoft.AspNetCore.Identity; using System.Text.RegularExpressions; using Deskstar.Core.Exceptions; +using Deskstar.DataAccess; +using Deskstar.Entities; +using Deskstar.Models; +using Microsoft.AspNetCore.Identity; +using Microsoft.IdentityModel.Tokens; -namespace Deskstar.Usecases +namespace Deskstar.Usecases; + +public interface IAuthUsecases { - public interface IAuthUsecases + LoginResponse CheckCredentials(string mail, string password); + string CreateToken(IConfiguration configuration, string mail); + User RegisterAdmin(string firstName, string lastName, string mailAddress, string password, string companyName); + RegisterResponse RegisterUser(RegisterUser registerUser); +} + +public class AuthUsecases : IAuthUsecases +{ + private readonly DataContext _context; + private readonly PasswordHasher _hasher; + private readonly ILogger _logger; + + public AuthUsecases(ILogger logger, DataContext context) { - LoginResponse CheckCredentials(string mail, string password); - string CreateToken(IConfiguration configuration, string mail); - User RegisterAdmin(string firstName, string lastName, string mailAddress, string password, string companyName); - RegisterResponse RegisterUser(RegisterUser registerUser); + _logger = logger; + _context = context; + _hasher = new PasswordHasher(); } - public class AuthUsecases : IAuthUsecases + public LoginResponse CheckCredentials(string mail, string password) { - private readonly ILogger _logger; - private readonly DataContext _context; - private readonly PasswordHasher _hasher; - - public AuthUsecases(ILogger logger, DataContext context) - { - _logger = logger; - _context = context; - _hasher = new PasswordHasher(); - } - - public LoginResponse CheckCredentials(string mail, string password) + try { - try - { - var registerUser - = _context.Users.Single(u => u.MailAddress == mail); - if (registerUser.IsMarkedForDeletion) - return new LoginResponse + var registerUser + = _context.Users.Single(u => u.MailAddress == mail); + if (registerUser.IsMarkedForDeletion) + return new LoginResponse { Message = LoginReturn.Deleted }; - if (!registerUser - .IsApproved) - return new LoginResponse + if (!registerUser + .IsApproved) + return new LoginResponse { Message = LoginReturn.NotYetApproved }; - if (_hasher.VerifyHashedPassword(registerUser - , registerUser - .Password, password) - == PasswordVerificationResult.Success) - return new LoginResponse + if (_hasher.VerifyHashedPassword(registerUser + , registerUser + .Password, password) + == PasswordVerificationResult.Success) + return new LoginResponse { Message = LoginReturn.Ok }; - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - } - - return new LoginResponse - { - Message = LoginReturn.CredentialsWrong - }; } - - public string CreateToken(IConfiguration configuration, String mail) + catch (Exception e) { - var registerUser = _getUser(mail); - if (registerUser == User.Null) - { - return ""; - } - - var issuer = configuration["Jwt:Issuer"]; - var audience = configuration["Jwt:Audience"]; - var key = Encoding.ASCII.GetBytes - (configuration["Jwt:Key"]); - var tokenDescriptor = new SecurityTokenDescriptor - { - Subject = new ClaimsIdentity(new[] - { - new Claim(JwtRegisteredClaimNames.NameId, registerUser - .UserId.ToString()), - registerUser - .IsCompanyAdmin - ? new Claim("IsCompanyAdmin", "True") - : new Claim("IsNormalUser", "True"), - new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) - }), - Expires = DateTime.UtcNow.AddMinutes(30), - Issuer = issuer, - Audience = audience, - SigningCredentials = new SigningCredentials - (new SymmetricSecurityKey(key), - SecurityAlgorithms.HmacSha512Signature) - }; - var tokenHandler = new JwtSecurityTokenHandler(); - var token = tokenHandler.CreateToken(tokenDescriptor); - var stringToken = tokenHandler.WriteToken(token); - return stringToken; + _logger.LogError(e, e.Message); } - public RegisterResponse RegisterUser(RegisterUser registerUser) + return new LoginResponse { - if (string.IsNullOrEmpty(registerUser.FirstName)) - throw new ArgumentInvalidException($"'{nameof(registerUser.FirstName)}' is not set"); - if (string.IsNullOrEmpty(registerUser.LastName)) - throw new ArgumentInvalidException($"'{nameof(registerUser.LastName)}' is not set"); - if (string.IsNullOrEmpty(registerUser.MailAddress)) - throw new ArgumentInvalidException($"'{nameof(registerUser.MailAddress)}' is not set"); - if (string.IsNullOrEmpty(registerUser.Password)) - throw new ArgumentInvalidException($"'{nameof(registerUser.Password)}' is not set"); - var rx = new Regex( - "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\\])", - RegexOptions.IgnoreCase); - if (rx.Matches(registerUser.MailAddress).Count != 1) - throw new ArgumentInvalidException("Mailaddress is not valid"); - if (_getUser(registerUser.MailAddress) != User.Null) - { - return new RegisterResponse - { - Message = RegisterReturn.MailAddressInUse - }; - } + Message = LoginReturn.CredentialsWrong + }; + } - if (_getCompany(registerUser.CompanyId) == Company.Null) + public string CreateToken(IConfiguration configuration, string mail) + { + var registerUser = _getUser(mail); + if (registerUser == User.Null) return ""; + + var issuer = configuration["Jwt:Issuer"]; + var audience = configuration["Jwt:Audience"]; + var key = Encoding.ASCII.GetBytes + (configuration["Jwt:Key"]); + var tokenDescriptor = new SecurityTokenDescriptor + { + Subject = new ClaimsIdentity(new[] { - return new RegisterResponse - { - Message = RegisterReturn.CompanyNotFound - }; - } + new Claim(JwtRegisteredClaimNames.NameId, registerUser + .UserId.ToString()), + registerUser + .IsCompanyAdmin + ? new Claim("IsCompanyAdmin", "True") + : new Claim("IsNormalUser", "True"), + new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) + }), + Expires = DateTime.UtcNow.AddMinutes(30), + Issuer = issuer, + Audience = audience, + SigningCredentials = new SigningCredentials + (new SymmetricSecurityKey(key), + SecurityAlgorithms.HmacSha512Signature) + }; + var tokenHandler = new JwtSecurityTokenHandler(); + var token = tokenHandler.CreateToken(tokenDescriptor); + var stringToken = tokenHandler.WriteToken(token); + return stringToken; + } - var newUser = new User + public RegisterResponse RegisterUser(RegisterUser registerUser) + { + if (string.IsNullOrEmpty(registerUser.FirstName)) + throw new ArgumentInvalidException($"'{nameof(registerUser.FirstName)}' is not set"); + if (string.IsNullOrEmpty(registerUser.LastName)) + throw new ArgumentInvalidException($"'{nameof(registerUser.LastName)}' is not set"); + if (string.IsNullOrEmpty(registerUser.MailAddress)) + throw new ArgumentInvalidException($"'{nameof(registerUser.MailAddress)}' is not set"); + if (string.IsNullOrEmpty(registerUser.Password)) + throw new ArgumentInvalidException($"'{nameof(registerUser.Password)}' is not set"); + var rx = new Regex( + "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\\])", + RegexOptions.IgnoreCase); + if (rx.Matches(registerUser.MailAddress).Count != 1) + throw new ArgumentInvalidException("Mailaddress is not valid"); + if (_getUser(registerUser.MailAddress) != User.Null) + return new RegisterResponse { - CompanyId = registerUser.CompanyId, - MailAddress = registerUser.MailAddress, - FirstName = registerUser.FirstName, - LastName = registerUser.LastName, - IsApproved = false + Message = RegisterReturn.MailAddressInUse }; - newUser.Password = _hasher.HashPassword(newUser, registerUser.Password); - _context.Users.Add(newUser); - _context.SaveChanges(); + if (_getCompany(registerUser.CompanyId) == Company.Null) return new RegisterResponse { - Message = RegisterReturn.Ok + Message = RegisterReturn.CompanyNotFound }; - } - private User _getUser(string mail) + var newUser = new User { - try - { - return _context.Users.Single(u => u.MailAddress == mail); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return User.Null; - } - } - - private Company _getCompany(Guid id) + CompanyId = registerUser.CompanyId, + MailAddress = registerUser.MailAddress, + FirstName = registerUser.FirstName, + LastName = registerUser.LastName, + IsApproved = false + }; + newUser.Password = _hasher.HashPassword(newUser, registerUser.Password); + + _context.Users.Add(newUser); + _context.SaveChanges(); + return new RegisterResponse { - try - { - return _context.Companies.Single(c => c.CompanyId == id); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Company.Null; - } - } + Message = RegisterReturn.Ok + }; + } - public User RegisterAdmin(string firstName, string lastName, string mailAddress, string password, string companyName) - { - if (string.IsNullOrEmpty(firstName)) - throw new ArgumentInvalidException($"'{nameof(firstName)}' is not set"); + public User RegisterAdmin(string firstName, string lastName, string mailAddress, string password, string companyName) + { + if (string.IsNullOrEmpty(firstName)) + throw new ArgumentInvalidException($"'{nameof(firstName)}' is not set"); - if (string.IsNullOrEmpty(lastName)) - throw new ArgumentInvalidException($"'{nameof(lastName)}' is not set"); + if (string.IsNullOrEmpty(lastName)) + throw new ArgumentInvalidException($"'{nameof(lastName)}' is not set"); - if (string.IsNullOrEmpty(mailAddress)) - throw new ArgumentInvalidException($"'{nameof(mailAddress)}' is not set"); + if (string.IsNullOrEmpty(mailAddress)) + throw new ArgumentInvalidException($"'{nameof(mailAddress)}' is not set"); - if (string.IsNullOrEmpty(password)) - throw new ArgumentInvalidException($"'{nameof(password)}' is not set"); + if (string.IsNullOrEmpty(password)) + throw new ArgumentInvalidException($"'{nameof(password)}' is not set"); - if (string.IsNullOrEmpty(companyName)) - throw new ArgumentInvalidException($"'{nameof(companyName)}' is not set"); + if (string.IsNullOrEmpty(companyName)) + throw new ArgumentInvalidException($"'{nameof(companyName)}' is not set"); - var rx = new Regex( - "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\\])", - RegexOptions.IgnoreCase); - if (rx.Matches(mailAddress).Count != 1) - throw new ArgumentInvalidException($"E-Mail '{mailAddress}' is not valid"); - - if (_getUser(mailAddress) != User.Null) - throw new ArgumentInvalidException($"E-Mail '{mailAddress}' already in use"); + var rx = new Regex( + "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\\])", + RegexOptions.IgnoreCase); + if (rx.Matches(mailAddress).Count != 1) + throw new ArgumentInvalidException($"E-Mail '{mailAddress}' is not valid"); - var companyNameExists = _context.Companies.SingleOrDefault(c => c.CompanyName == companyName); - if (companyNameExists != null) - throw new ArgumentInvalidException($"Company name '{companyName}' already in use"); + if (_getUser(mailAddress) != User.Null) + throw new ArgumentInvalidException($"E-Mail '{mailAddress}' already in use"); - var companyId = Guid.NewGuid(); - var company = new Company { CompanyName = companyName, CompanyId = companyId }; + var companyNameExists = _context.Companies.SingleOrDefault(c => c.CompanyName == companyName); + if (companyNameExists != null) + throw new ArgumentInvalidException($"Company name '{companyName}' already in use"); - var admin = new User - { - CompanyId = companyId, - MailAddress = mailAddress, - FirstName = firstName, - LastName = lastName, - Company = company, - IsApproved = true, - IsCompanyAdmin = true, - }; - admin.Password = _hasher.HashPassword(admin, password); + var companyId = Guid.NewGuid(); + var company = new Company { CompanyName = companyName, CompanyId = companyId }; - _context.Companies.Add(company); - _context.Users.Add(admin); + var admin = new User + { + CompanyId = companyId, + MailAddress = mailAddress, + FirstName = firstName, + LastName = lastName, + Company = company, + IsApproved = true, + IsCompanyAdmin = true + }; + admin.Password = _hasher.HashPassword(admin, password); + + _context.Companies.Add(company); + _context.Users.Add(admin); + + _context.SaveChanges(); + + return admin; + } - _context.SaveChanges(); + private User _getUser(string mail) + { + try + { + return _context.Users.Single(u => u.MailAddress == mail); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return User.Null; + } + } - return admin; + private Company _getCompany(Guid id) + { + try + { + return _context.Companies.Single(c => c.CompanyId == id); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Company.Null; } } } diff --git a/src/deskstar-backend/Deskstar/Usecases/CompanyUsecases.cs b/src/deskstar-backend/Deskstar/Usecases/CompanyUsecases.cs index 8e0b5816..168951be 100644 --- a/src/deskstar-backend/Deskstar/Usecases/CompanyUsecases.cs +++ b/src/deskstar-backend/Deskstar/Usecases/CompanyUsecases.cs @@ -1,5 +1,4 @@ using Deskstar.DataAccess; -using Deskstar.Entities; using Deskstar.Models; namespace Deskstar.Usecases; @@ -27,10 +26,10 @@ public List GetCompanies() if (dbCompanies.ToList().Count == 0) return new List(); - var mapCompaniesToCompaniesDto = dbCompanies.Select((c) => new CompanyDto + var mapCompaniesToCompaniesDto = dbCompanies.Select(c => new CompanyDto { CompanyId = c.CompanyId.ToString(), - CompanyName = c.CompanyName, + CompanyName = c.CompanyName }).ToList(); return mapCompaniesToCompaniesDto; diff --git a/src/deskstar-backend/Deskstar/Usecases/ResourceUsecases.cs b/src/deskstar-backend/Deskstar/Usecases/ResourceUsecases.cs index 92f6b9f0..3e40a7ef 100644 --- a/src/deskstar-backend/Deskstar/Usecases/ResourceUsecases.cs +++ b/src/deskstar-backend/Deskstar/Usecases/ResourceUsecases.cs @@ -49,13 +49,10 @@ public class ResourceUsecases : IResourceUsecases private readonly DataContext _context; private readonly ILogger _logger; - private readonly IUserUsecases _userUsecases; - - public ResourceUsecases(ILogger logger, DataContext context, IUserUsecases userUsecases) + public ResourceUsecases(ILogger logger, DataContext context) { _logger = logger; _context = context; - _userUsecases = userUsecases; } public Building UpdateBuilding(Guid companyId, Guid buildingId, string? buildingName, string? location) { @@ -301,35 +298,6 @@ public List GetBuildings(Guid userId) public List GetFloors(Guid callerId, string buildingId) { IQueryable databaseFloors; - if (buildingId.Length == 0) - { - var callerDb = _context.Users.First(user => user.UserId == callerId); - try - { - databaseFloors = _context.Floors.Include(b => b.Building).ThenInclude(c => c.Company) - .Where(desk => desk.Building.Company.CompanyId == callerDb.CompanyId); - if (databaseFloors.ToList().Count == 0) - { - throw new ArgumentException($"There are no Floors in this Company with id '{callerDb.CompanyId}'"); - } - } - catch (Exception e) when (e is FormatException or ArgumentNullException or OverflowException) - { - _logger.LogError(e, e.Message); - throw new ArgumentException($"There are no Floor in this Company with id '{callerDb.CompanyId}'"); - } - - var mapFloorsToCurrentFloorsLocal = databaseFloors.Select(f => new CurrentFloor - { - BuildingName = f.Building.BuildingName, - FloorName = f.FloorName, - FloorId = f.FloorId.ToString(), - Location = f.Building.Location, - IsMarkedForDeletion = f.IsMarkedForDeletion - }); - - return mapFloorsToCurrentFloorsLocal.ToList(); - } Guid buildingGuidId; try @@ -344,7 +312,7 @@ public List GetFloors(Guid callerId, string buildingId) try { - databaseFloors = _context.Floors.Where(floor => floor.BuildingId == buildingGuidId); + databaseFloors = _context.Floors.Include(b=>b.Building).Where(floor => floor.BuildingId == buildingGuidId); if (databaseFloors.ToList().Count == 0) { var databaseBuilding = _context.Buildings.First(building => building.BuildingId == buildingGuidId); @@ -381,7 +349,8 @@ public List GetAllFloors(Guid userId) try { var companyId = _context.Users.Where(user => user.UserId == userId).Select(user => user.CompanyId).First(); - databaseFloors = _context.Floors.Where(floor => floor.Building.CompanyId == companyId); + databaseFloors = _context.Floors + .Include(b => b.Building).Where(floor => floor.Building.CompanyId == companyId); } catch (Exception e) when (e is FormatException or ArgumentNullException or OverflowException) { @@ -400,6 +369,7 @@ public List GetAllFloors(Guid userId) BuildingId = f.BuildingId.ToString(), BuildingName = f.Building.BuildingName, FloorName = f.FloorName, + Location = f.Building.Location, FloorId = f.FloorId.ToString(), IsMarkedForDeletion = f.IsMarkedForDeletion }); @@ -409,37 +379,6 @@ public List GetAllFloors(Guid userId) public List GetRooms(Guid callerId, string floorId) { IQueryable databaseRooms; - if (floorId.Length == 0) - { - var callerDb = _context.Users.First(user => user.UserId == callerId); - try - { - databaseRooms = _context.Rooms.Include(r => r.Floor) - .ThenInclude(b => b.Building).ThenInclude(c => c.Company) - .Where(desk => desk.Floor.Building.Company.CompanyId == callerDb.CompanyId); - if (databaseRooms.ToList().Count == 0) - { - throw new ArgumentException($"There are no Rooms in this Company with id '{callerDb.CompanyId}'"); - } - } - catch (Exception e) when (e is FormatException or ArgumentNullException or OverflowException) - { - _logger.LogError(e, e.Message); - throw new ArgumentException($"There are no Rooms in this Company with id '{callerDb.CompanyId}'"); - } - - var mapRoomsToCurrentRoomsLocal = databaseRooms.Select(r => new CurrentRoom - { - RoomId = r.RoomId.ToString(), - RoomName = r.RoomName, - Floor = r.Floor.FloorName, - Building = r.Floor.Building.BuildingName, - Location = r.Floor.Building.Location, - IsMarkedForDeletion = r.IsMarkedForDeletion - }); - return mapRoomsToCurrentRoomsLocal.ToList(); - } - Guid floorGuidId; try { @@ -453,7 +392,7 @@ public List GetRooms(Guid callerId, string floorId) try { - databaseRooms = _context.Rooms.Where(room => room.FloorId == floorGuidId); + databaseRooms = _context.Rooms.Include(r=>r.Floor).ThenInclude(f=>f.Building).Where(room => room.FloorId == floorGuidId); } catch (Exception e) when (e is FormatException or ArgumentNullException or OverflowException) { @@ -486,7 +425,7 @@ public List GetAllRooms(Guid userId) try { var companyId = _context.Users.Where(user => user.UserId == userId).Select(user => user.CompanyId).First(); - databaseRooms = _context.Rooms.Where(room => room.Floor.Building.CompanyId == companyId); + databaseRooms = _context.Rooms.Include(r=>r.Floor).ThenInclude(f=>f.Building).Where(room => room.Floor.Building.CompanyId == companyId); } catch (Exception e) when (e is FormatException or ArgumentNullException or OverflowException) { @@ -504,6 +443,9 @@ public List GetAllRooms(Guid userId) { RoomId = r.RoomId.ToString(), RoomName = r.RoomName, + Floor = r.Floor.FloorName, + Building = r.Floor.Building.BuildingName, + Location = r.Floor.Building.Location, FloorId = r.FloorId.ToString(), IsMarkedForDeletion = r.IsMarkedForDeletion }); @@ -513,31 +455,6 @@ public List GetAllRooms(Guid userId) public List GetDesks(Guid callerId, string roomId, DateTime start, DateTime end) { IQueryable mapDesksToCurrentDesks; - if (roomId.Length == 0) - { - var callerDb = _context.Users.First(user => user.UserId == callerId); - try - { - var databaseDesks = _context.Desks.Include(d => d.Room) - .ThenInclude(r => r.Floor) - .ThenInclude(b => b.Building).ThenInclude(c => c.Company) - .Where(desk => desk.Room.Floor.Building.Company.CompanyId == callerDb.CompanyId); - if (databaseDesks.ToList().Count == 0) - { - throw new ArgumentException($"There are no Desks in this Company with id '{callerDb.CompanyId}'"); - } - - mapDesksToCurrentDesks = MapDesksToCurrentDesks(databaseDesks, start, end); - } - catch (Exception e) when (e is FormatException or ArgumentNullException or OverflowException) - { - _logger.LogError(e, e.Message); - throw new ArgumentException($"There are no Desks in this Company with id '{callerDb.CompanyId}'"); - } - - return mapDesksToCurrentDesks.ToList(); - } - Guid roomGuid; try { @@ -551,7 +468,8 @@ public List GetDesks(Guid callerId, string roomId, DateTime start, try { - var databaseDesks = _context.Desks.Where(desk => desk.RoomId == roomGuid); + var databaseDesks = _context.Desks.Include(d => d.Room) + .ThenInclude(r=>r.Floor).ThenInclude(f=>f.Building).Where(desk => desk.RoomId == roomGuid); if (databaseDesks.ToList().Count == 0) { var databaseRoom = _context.Rooms.First(room => room.RoomId == roomGuid); @@ -607,7 +525,9 @@ public List GetAllDesks(Guid userId) try { var companyId = _context.Users.Where(user => user.UserId == userId).Select(user => user.CompanyId).First(); - var databaseDesks = _context.Desks.Where(desk => desk.Room.Floor.Building.CompanyId == companyId); + var databaseDesks = _context.Desks.Include(d => d.Room) + .ThenInclude(r=>r.Floor).ThenInclude(f=>f.Building) + .Where(desk => desk.Room.Floor.Building.CompanyId == companyId); mapDesksToCurrentDesks = databaseDesks.Select(desk => new CurrentDesk { @@ -641,7 +561,8 @@ public CurrentDesk GetDesk(Guid deskId, DateTime startDateTime, DateTime endDate CurrentDesk mapDeskToCurrentDesk; try { - var databaseDesks = _context.Desks.Where(desk => desk.DeskId == deskId); + var databaseDesks = _context.Desks.Include(d => d.Room) + .ThenInclude(r=>r.Floor).ThenInclude(f=>f.Building).Where(desk => desk.DeskId == deskId); mapDeskToCurrentDesk = databaseDesks.Select(desk => new CurrentDesk { @@ -1257,4 +1178,4 @@ public void RestoreBuilding(Guid adminId, string buildingId) buildingDbInstance.IsMarkedForDeletion = false; _context.SaveChanges(); } -} \ No newline at end of file +} diff --git a/src/deskstar-backend/Deskstar/Usecases/UserUsecases.cs b/src/deskstar-backend/Deskstar/Usecases/UserUsecases.cs index 201c25d5..6c9578a1 100644 --- a/src/deskstar-backend/Deskstar/Usecases/UserUsecases.cs +++ b/src/deskstar-backend/Deskstar/Usecases/UserUsecases.cs @@ -7,12 +7,13 @@ * * MIT License */ + +using System.Text.RegularExpressions; using Deskstar.Core.Exceptions; using Deskstar.DataAccess; using Deskstar.Entities; using Deskstar.Helper; using Microsoft.EntityFrameworkCore; -using System.Text.RegularExpressions; namespace Deskstar.Usecases; @@ -30,14 +31,15 @@ public interface IUserUsecases public class UserUsecases : IUserUsecases { + private readonly DataContext _context; private readonly ILogger _logger; - private readonly DataContext _context; public UserUsecases(ILogger logger, DataContext context) { _logger = logger; _context = context; } + public User ReadSpecificUser(Guid userId) { var user = _context.Users.Include(u => u.Company).Include(u => u.Bookings).SingleOrDefault(u => u.UserId == userId); @@ -45,6 +47,7 @@ public User ReadSpecificUser(Guid userId) throw new EntityNotFoundException($"There is no user with Id '{userId}'"); return user; } + public Guid ApproveUser(Guid adminId, string userId) { Guid guid; @@ -69,20 +72,12 @@ public Guid ApproveUser(Guid adminId, string userId) _context.SaveChanges(); var body = $"Hello {user.FirstName},
" + - $"your account has been approved by {ReadSpecificUser(adminId).FirstName}.
" + - "You can now log into the system.
" + - "You can now book your first desk and get to work.
"; + $"your account has been approved by {ReadSpecificUser(adminId).FirstName}.
" + + "You can now log into the system.
" + + "You can now book your first desk and get to work.
"; EmailHelper.SendEmail(_logger, user.MailAddress, "Your Deskstar account has been approved!", body); return guid; - - } - - private void CheckSameCompany(Guid adminId, Guid guid) - { - var accessDenied = _context.Users.Where(u => u.UserId == adminId || u.UserId == guid).Select(u => u.CompanyId).ToHashSet().Count != 1; - if (accessDenied) - throw new InsufficientPermissionException($"'{adminId}' has no access to administrate '{guid}'"); } public Guid DeclineUser(Guid adminId, string userId) @@ -107,8 +102,8 @@ public Guid DeclineUser(Guid adminId, string userId) throw new ArgumentInvalidException($"You cannot rejected an already approved user '{guid}'"); var body = $"Hello {user.FirstName},
" + - $"your account has been rejected.
" + - "Please contact one of your company's admins if you think this was a mistake.
"; + "your account has been rejected.
" + + "Please contact one of your company's admins if you think this was a mistake.
"; EmailHelper.SendEmail(_logger, user.MailAddress, "Your Deskstar account has been rejected!", body); _context.Users.Remove(user); @@ -123,7 +118,7 @@ public List ReadAllUsers(Guid adminId) if (admin == null) throw new EntityNotFoundException($"There is no admin with id '{adminId}'"); return _context.Users.Where(user => user.CompanyId == admin.CompanyId) - .ToList(); + .ToList(); } public Guid UpdateUser(string requestUserId, User user) @@ -140,9 +135,7 @@ public Guid UpdateUser(string requestUserId, User user) } if (!guid.Equals(user.UserId)) - { throw new ArgumentInvalidException($"'{requestUserId}' is not equals with given userObject"); - } return SaveUpdateUser(user); } @@ -154,39 +147,9 @@ public Guid UpdateUser(Guid adminId, User user) throw new EntityNotFoundException($"There is no user with id '{user.UserId}'"); CheckSameCompany(adminId, user.UserId); if (adminId == user.UserId && !user.IsCompanyAdmin) - throw new ArgumentInvalidException($"You cannot delete your own admin rights"); + throw new ArgumentInvalidException("You cannot delete your own admin rights"); return SaveUpdateUser(user); } - private Guid SaveUpdateUser(User user) - { - if (user.UserId == Guid.Empty) - throw new ArgumentInvalidException($"'{nameof(user.UserId)}' is empty"); - if (string.IsNullOrEmpty(user.FirstName)) - throw new ArgumentInvalidException($"'{nameof(user.FirstName)}' is not set"); - if (string.IsNullOrEmpty(user.LastName)) - throw new ArgumentInvalidException($"'{nameof(user.LastName)}' is not set"); - if (string.IsNullOrEmpty(user.MailAddress)) - throw new ArgumentInvalidException($"'{nameof(user.MailAddress)}' is not set"); - var rx = new Regex("(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\\])", - RegexOptions.IgnoreCase); - if (rx.Matches(user.MailAddress).Count != 1) - throw new ArgumentInvalidException("Mailaddress is not valid"); - var userDbInstance = _context.Users.SingleOrDefault(u => u.UserId == user.UserId); - if (userDbInstance == null) - throw new EntityNotFoundException($"There is no user with id '{user.UserId}'"); - userDbInstance.FirstName = user.FirstName; - userDbInstance.LastName = user.LastName; - userDbInstance.MailAddress = user.MailAddress; - userDbInstance.IsCompanyAdmin = user.IsCompanyAdmin; - userDbInstance.IsMarkedForDeletion = user.IsMarkedForDeletion; - _context.SaveChanges(); - var body = $"Hello {user.FirstName},
" + - "your account details have been updated.
" + - "Please check if this was ok.
" + - "If not get in touch with your company admin.
"; - EmailHelper.SendEmail(_logger, user.MailAddress, "Your Deskstar account has been updated!", body); - return user.UserId; - } public Guid DeleteUser(Guid adminId, string userId) { @@ -206,7 +169,7 @@ public Guid DeleteUser(Guid adminId, string userId) throw new EntityNotFoundException($"There is no user with id '{userId}'"); CheckSameCompany(adminId, guid); if (adminId == guid) - throw new ArgumentInvalidException($"You cannot delete yourself"); + throw new ArgumentInvalidException("You cannot delete yourself"); var body = $"Hello {userDbInstance.FirstName},
" + "your account has been deleted by your Company admin.
" + "If you think this was an mistake, get in touch with your company admin.
"; @@ -216,4 +179,44 @@ public Guid DeleteUser(Guid adminId, string userId) return guid; } + + private void CheckSameCompany(Guid adminId, Guid guid) + { + var accessDenied = _context.Users.Where(u => u.UserId == adminId || u.UserId == guid).Select(u => u.CompanyId) + .ToHashSet().Count != 1; + if (accessDenied) + throw new InsufficientPermissionException($"'{adminId}' has no access to administrate '{guid}'"); + } + + private Guid SaveUpdateUser(User user) + { + if (user.UserId == Guid.Empty) + throw new ArgumentInvalidException($"'{nameof(user.UserId)}' is empty"); + if (string.IsNullOrEmpty(user.FirstName)) + throw new ArgumentInvalidException($"'{nameof(user.FirstName)}' is not set"); + if (string.IsNullOrEmpty(user.LastName)) + throw new ArgumentInvalidException($"'{nameof(user.LastName)}' is not set"); + if (string.IsNullOrEmpty(user.MailAddress)) + throw new ArgumentInvalidException($"'{nameof(user.MailAddress)}' is not set"); + var rx = new Regex( + "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\\])", + RegexOptions.IgnoreCase); + if (rx.Matches(user.MailAddress).Count != 1) + throw new ArgumentInvalidException("Mailaddress is not valid"); + var userDbInstance = _context.Users.SingleOrDefault(u => u.UserId == user.UserId); + if (userDbInstance == null) + throw new EntityNotFoundException($"There is no user with id '{user.UserId}'"); + userDbInstance.FirstName = user.FirstName; + userDbInstance.LastName = user.LastName; + userDbInstance.MailAddress = user.MailAddress; + userDbInstance.IsCompanyAdmin = user.IsCompanyAdmin; + userDbInstance.IsMarkedForDeletion = user.IsMarkedForDeletion; + _context.SaveChanges(); + var body = $"Hello {user.FirstName},
" + + "your account details have been updated.
" + + "Please check if this was ok.
" + + "If not get in touch with your company admin.
"; + EmailHelper.SendEmail(_logger, user.MailAddress, "Your Deskstar account has been updated!", body); + return user.UserId; + } } diff --git a/src/deskstar-backend/Teststar.Tests/Tests/AuthUsecasesTests.cs b/src/deskstar-backend/Teststar.Tests/Tests/AuthUsecasesTests.cs index f914357e..59401d2d 100644 --- a/src/deskstar-backend/Teststar.Tests/Tests/AuthUsecasesTests.cs +++ b/src/deskstar-backend/Teststar.Tests/Tests/AuthUsecasesTests.cs @@ -165,11 +165,11 @@ public void CreateToken_ValidMailAndPassword() var logger = new Mock>(); var subject = new AuthUsecases(logger.Object, mogDB); var mogSettings = new Dictionary - { - { "Jwt:Issuer", "https://deskstar.com/" }, - { "Jwt:Audience", "https://deskstar.com/" }, - { "Jwt:Key", "thisIsATopSecretForTesting" } - }; + { + { "Jwt:Issuer", "https://deskstar.com/" }, + { "Jwt:Audience", "https://deskstar.com/" }, + { "Jwt:Key", "thisIsATopSecretForTesting" } + }; var configuration = new ConfigurationBuilder().AddInMemoryCollection(mogSettings).Build(); @@ -284,6 +284,7 @@ public void RegisterUser_NonExistingCompany() //cleanup mogDB.Database.EnsureDeleted(); } + [Test] public void RegisterAdmin_WhenAllValuesValid_ShouldCreateAdminAndCompany() { @@ -320,6 +321,7 @@ public void RegisterAdmin_WhenAllValuesValid_ShouldCreateAdminAndCompany() // cleanup context.Database.EnsureDeleted(); } + [Test] [TestCase("a")] [TestCase("a.de")] @@ -341,7 +343,8 @@ public void RegisterAdmin_WhenMailIsInvalid_ShouldCreateAdminAndCompany(string i var companyName = "company"; // act+assert - var ex = Assert.Throws(() => subject.RegisterAdmin(firstName, lastName, invalidMailAddress, password, companyName)); + var ex = Assert.Throws(() => + subject.RegisterAdmin(firstName, lastName, invalidMailAddress, password, companyName)); Assert.NotNull(ex); Assert.That(ex.Message, Is.EqualTo($"E-Mail '{invalidMailAddress}' is not valid")); @@ -349,6 +352,7 @@ public void RegisterAdmin_WhenMailIsInvalid_ShouldCreateAdminAndCompany(string i // cleanup context.Database.EnsureDeleted(); } + [Test] public void RegisterAdmin_WhenMailIsInvalid_ShouldCreateAdminAndCompany() { @@ -371,7 +375,8 @@ public void RegisterAdmin_WhenMailIsInvalid_ShouldCreateAdminAndCompany() var password = "testpw"; // act+assert - var ex = Assert.Throws(() => subject.RegisterAdmin(firstName, lastName, mailAddress, password, companyName)); + var ex = Assert.Throws(() => + subject.RegisterAdmin(firstName, lastName, mailAddress, password, companyName)); Assert.NotNull(ex); Assert.That(ex.Message, Is.EqualTo($"Company name '{companyName}' already in use")); @@ -379,6 +384,7 @@ public void RegisterAdmin_WhenMailIsInvalid_ShouldCreateAdminAndCompany() // cleanup context.Database.EnsureDeleted(); } + [Test] public void RegisterAdmin_WhenCalledWithEmptyFirstName_ShouldThrowInvalidArgumentException() { @@ -390,15 +396,16 @@ public void RegisterAdmin_WhenCalledWithEmptyFirstName_ShouldThrowInvalidArgumen var logger = new Mock>(); var subject = new AuthUsecases(logger.Object, context); - string firstName = string.Empty; - string lastName = "notEmpty"; - string mailAddress = "notEmpty"; - string password = "notEmpty"; - string companyName = "notEmpty"; + var firstName = string.Empty; + var lastName = "notEmpty"; + var mailAddress = "notEmpty"; + var password = "notEmpty"; + var companyName = "notEmpty"; // act + assert - var ex = Assert.Throws(() => subject.RegisterAdmin(firstName, lastName, mailAddress, password, companyName)); + var ex = Assert.Throws(() => + subject.RegisterAdmin(firstName, lastName, mailAddress, password, companyName)); Assert.NotNull(ex); Assert.That(ex.Message, Is.EqualTo($"'{nameof(firstName)}' is not set")); @@ -406,6 +413,7 @@ public void RegisterAdmin_WhenCalledWithEmptyFirstName_ShouldThrowInvalidArgumen // cleanup context.Database.EnsureDeleted(); } + [Test] public void RegisterAdmin_WhenCalledWithEmptyLastName_ShouldThrowInvalidArgumentException() { @@ -417,15 +425,16 @@ public void RegisterAdmin_WhenCalledWithEmptyLastName_ShouldThrowInvalidArgument var logger = new Mock>(); var subject = new AuthUsecases(logger.Object, context); - string firstName = "notEmpty"; - string lastName = string.Empty; - string mailAddress = "notEmpty"; - string password = "notEmpty"; - string companyName = "notEmpty"; + var firstName = "notEmpty"; + var lastName = string.Empty; + var mailAddress = "notEmpty"; + var password = "notEmpty"; + var companyName = "notEmpty"; // act + assert - var ex = Assert.Throws(() => subject.RegisterAdmin(firstName, lastName, mailAddress, password, companyName)); + var ex = Assert.Throws(() => + subject.RegisterAdmin(firstName, lastName, mailAddress, password, companyName)); Assert.NotNull(ex); Assert.That(ex.Message, Is.EqualTo($"'{nameof(lastName)}' is not set")); @@ -433,6 +442,7 @@ public void RegisterAdmin_WhenCalledWithEmptyLastName_ShouldThrowInvalidArgument // cleanup context.Database.EnsureDeleted(); } + [Test] public void RegisterAdmin_WhenCalledWithEmptyMailAddress_ShouldThrowInvalidArgumentException() { @@ -444,15 +454,16 @@ public void RegisterAdmin_WhenCalledWithEmptyMailAddress_ShouldThrowInvalidArgum var logger = new Mock>(); var subject = new AuthUsecases(logger.Object, context); - string firstName = "notEmpty"; - string lastName = "notEmpty"; - string mailAddress = string.Empty; - string password = "notEmpty"; - string companyName = "notEmpty"; + var firstName = "notEmpty"; + var lastName = "notEmpty"; + var mailAddress = string.Empty; + var password = "notEmpty"; + var companyName = "notEmpty"; // act + assert - var ex = Assert.Throws(() => subject.RegisterAdmin(firstName, lastName, mailAddress, password, companyName)); + var ex = Assert.Throws(() => + subject.RegisterAdmin(firstName, lastName, mailAddress, password, companyName)); Assert.NotNull(ex); Assert.That(ex.Message, Is.EqualTo($"'{nameof(mailAddress)}' is not set")); @@ -460,6 +471,7 @@ public void RegisterAdmin_WhenCalledWithEmptyMailAddress_ShouldThrowInvalidArgum // cleanup context.Database.EnsureDeleted(); } + [Test] public void RegisterAdmin_WhenCalledWithEmptyPassword_ShouldThrowInvalidArgumentException() { @@ -471,15 +483,16 @@ public void RegisterAdmin_WhenCalledWithEmptyPassword_ShouldThrowInvalidArgument var logger = new Mock>(); var subject = new AuthUsecases(logger.Object, context); - string firstName = "notEmpty"; - string lastName = "notEmpty"; - string mailAddress = "notEmpty"; - string password = string.Empty; - string companyName = "notEmpty"; + var firstName = "notEmpty"; + var lastName = "notEmpty"; + var mailAddress = "notEmpty"; + var password = string.Empty; + var companyName = "notEmpty"; // act + assert - var ex = Assert.Throws(() => subject.RegisterAdmin(firstName, lastName, mailAddress, password, companyName)); + var ex = Assert.Throws(() => + subject.RegisterAdmin(firstName, lastName, mailAddress, password, companyName)); Assert.NotNull(ex); Assert.That(ex.Message, Is.EqualTo($"'{nameof(password)}' is not set")); @@ -487,6 +500,7 @@ public void RegisterAdmin_WhenCalledWithEmptyPassword_ShouldThrowInvalidArgument // cleanup context.Database.EnsureDeleted(); } + [Test] public void RegisterAdmin_WhenCalledWithEmptyCompanyName_ShouldThrowInvalidArgumentException() { @@ -498,15 +512,16 @@ public void RegisterAdmin_WhenCalledWithEmptyCompanyName_ShouldThrowInvalidArgum var logger = new Mock>(); var subject = new AuthUsecases(logger.Object, context); - string firstName = "notEmpty"; - string lastName = "notEmpty"; - string mailAddress = "notEmpty"; - string password = "notEmpty"; - string companyName = string.Empty; + var firstName = "notEmpty"; + var lastName = "notEmpty"; + var mailAddress = "notEmpty"; + var password = "notEmpty"; + var companyName = string.Empty; // act + assert - var ex = Assert.Throws(() => subject.RegisterAdmin(firstName, lastName, mailAddress, password, companyName)); + var ex = Assert.Throws(() => + subject.RegisterAdmin(firstName, lastName, mailAddress, password, companyName)); Assert.NotNull(ex); Assert.That(ex.Message, Is.EqualTo($"'{nameof(companyName)}' is not set")); diff --git a/src/deskstar-backend/Teststar.Tests/Tests/BookingUsecasesTest.cs b/src/deskstar-backend/Teststar.Tests/Tests/BookingUsecasesTest.cs index 78645f41..6d830eaf 100644 --- a/src/deskstar-backend/Teststar.Tests/Tests/BookingUsecasesTest.cs +++ b/src/deskstar-backend/Teststar.Tests/Tests/BookingUsecasesTest.cs @@ -10,1021 +10,1022 @@ namespace Teststar.Tests.Tests; public class BookingUsecasesTest { - [Test] - public void CountValidBookings_WhenBookingsAvailable_ShouldReturnNumberOfBookings() + [Test] + public void CountValidBookings_WhenBookingsAvailable_ShouldReturnNumberOfBookings() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + SetupMockData(db, userId: userId); + + //arrange + var direction = "DESC"; + var start = DateTime.Now; + var end = DateTime.Now; + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + //act + var numberOfBookings = usecases.CountValidBookings(userId, direction, start, end); + + //assert + Assert.Zero(numberOfBookings); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void CountValidBookings_WhenNoBookingsAvailable_ShouldReturnZero() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + SetupMockData(db, userId: userId, deskId: deskId); + + //arrange + var direction = "DESC"; + var start = DateTime.Now; + var end = DateTime.Now.Add(TimeSpan.FromDays(3)); + var fbId = Guid.NewGuid(); + var sbId = Guid.NewGuid(); + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + SetupTwoBookings(db, userId, deskId, fbId, sbId); + + //act + var numberOfBookings = usecases.CountValidBookings(userId, direction, start, end); + + //assert + Assert.NotZero(numberOfBookings); + Assert.That(numberOfBookings == 2); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void GetFilteredBookings_WhenDefaultConfigIsUsed_ShouldReturnASingleBooking() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + SetupMockData(db, userId: userId, deskId: deskId); + + var bId = Guid.NewGuid(); + var bStart = DateTime.Now.Add(TimeSpan.FromHours(1)); + var bEnd = DateTime.Now.Add(TimeSpan.FromHours(2)); + var booking = new Booking { - //setup - using var db = new DataContext(); + BookingId = bId, + DeskId = deskId, + UserId = userId, + Timestamp = DateTime.Now, + StartTime = bStart, + EndTime = bEnd + }; + db.Add(booking); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + //act + var result = usecases.GetFilteredBookings(userId, int.MaxValue, 0, "DESC", DateTime.Now, DateTime.MaxValue); + + //assert + Assert.That(result, Has.Count.EqualTo(1)); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + [TestCase(1, 0, 1)] + [TestCase(2, 0, 2)] + [TestCase(1, 1, 1)] + [TestCase(1, 2, 0)] + public void GetFilteredBookings_WhenQueryForNandSkip_ShouldReturnTheExpectedAmountOfBookings(int n, int skip, + int expectedBookings) + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + SetupMockData(db, userId: userId, deskId: deskId); + + var fbId = Guid.NewGuid(); + var sbId = Guid.NewGuid(); + SetupTwoBookings(db, userId, deskId, fbId, sbId); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + //act + var result = usecases.GetFilteredBookings(userId, n, skip, "", DateTime.Now, DateTime.MaxValue); + + //assert + Assert.That(result.Count == expectedBookings); + + //cleanup + db.Database.EnsureDeleted(); + } + + + [Test] + public void GetFilteredBookings_WhenQueryForDirectionASC_ShouldReturnTheBookingsInAscendingOrder() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + SetupMockData(db, userId: userId, deskId: deskId); + + var fbId = Guid.NewGuid(); + var sbId = Guid.NewGuid(); + SetupTwoBookings(db, userId, deskId, fbId, sbId); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + //act + var result = usecases.GetFilteredBookings(userId, 2, 0, "ASC", DateTime.Now, DateTime.MaxValue); + + //assert + Assert.That(result[0].BookingId == fbId); + Assert.That(result[1].BookingId == sbId); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void GetFilteredBookings_WhenQueryForDirectionDESC_ShouldReturnTheBookingsInDescendingOrder() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + SetupMockData(db, userId: userId, deskId: deskId); + + var fbId = Guid.NewGuid(); + var sbId = Guid.NewGuid(); + SetupTwoBookings(db, userId, deskId, fbId, sbId); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + //act + var result = usecases.GetFilteredBookings(userId, 2, 0, "DESC", DateTime.Now, DateTime.MaxValue); + + //assert + Assert.That(result[0].BookingId, Is.EqualTo(sbId)); + Assert.That(result[1].BookingId, Is.EqualTo(fbId)); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void + GetFilteredBookings_WhenStartIsAfterBookingStartTime_ShouldNotReturnTheBookingsWhereStartTimeBeforeStart() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + SetupMockData(db, userId: userId, deskId: deskId); + + var fbId = Guid.NewGuid(); + var sbId = Guid.NewGuid(); + var (firstBooking, secondBooking) = SetupTwoBookings(db, userId, deskId, fbId, sbId); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + var start = firstBooking.StartTime.Add(TimeSpan.FromTicks(1)); + + //act + var result = usecases.GetFilteredBookings(userId, 2, 0, "DESC", start, DateTime.MaxValue); - var userId = Guid.NewGuid(); - SetupMockData(db, userId: userId); + //assert + Assert.That(result, Has.Count.EqualTo(1)); + Assert.That(result, Does.Not.Contain(firstBooking)); + Assert.That(result, Does.Contain(secondBooking)); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void GetFilteredBookings_WhenEndIsBeforeBookingStartTime_ShouldNotReturnTheBookingsWhereStartTimeAfterEnd() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + SetupMockData(db, userId: userId, deskId: deskId); + + var fbId = Guid.NewGuid(); + var sbId = Guid.NewGuid(); + var (firstBooking, secondBooking) = SetupTwoBookings(db, userId, deskId, fbId, sbId); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + var end = secondBooking.StartTime.Subtract(TimeSpan.FromTicks(1)); + + //act + var result = usecases.GetFilteredBookings(userId, 2, 0, "DESC", DateTime.Now, end); + + //assert + Assert.That(result, Has.Count.EqualTo(1)); + Assert.That(result, Does.Contain(firstBooking)); + Assert.That(result, Does.Not.Contain(secondBooking)); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void CreateBooking_WhenDesksNotExists_ShouldThrowAnArgumentException() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + SetupMockData(db, userId: userId); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + var bookingRequest = new BookingRequest + { + DeskId = Guid.NewGuid(), + StartTime = DateTime.Now, + EndTime = DateTime.Now + }; + //act + try + { + var result = usecases.CreateBooking(Guid.NewGuid(), bookingRequest); - //arrange - var direction = "DESC"; - var start = DateTime.Now; - var end = DateTime.Now; - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); + //assert + Assert.Fail(); + } + catch (ArgumentException e) + { + Assert.That(e.Message, Is.EqualTo("Desk not found")); + } - //act - var numberOfBookings = usecases.CountValidBookings(userId, direction, start, end); + //cleanup + db.Database.EnsureDeleted(); + } - //assert - Assert.Zero(numberOfBookings); + [Test] + public void CreateBooking_WhenUserNotExists_ShouldThrowAnArgumentException() + { + //setup + using var db = new DataContext(); - //cleanup - db.Database.EnsureDeleted(); - } + var deskId = Guid.NewGuid(); + SetupMockData(db, deskId: deskId); - [Test] - public void CountValidBookings_WhenNoBookingsAvailable_ShouldReturnZero() + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + var bookingRequest = new BookingRequest + { + DeskId = deskId, + StartTime = DateTime.Now, + EndTime = DateTime.Now + }; + //act + try { - //setup - using var db = new DataContext(); - - var userId = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - SetupMockData(db, userId: userId, deskId: deskId); - - //arrange - var direction = "DESC"; - var start = DateTime.Now; - var end = DateTime.Now.Add(TimeSpan.FromDays(3)); - var fbId = Guid.NewGuid(); - var sbId = Guid.NewGuid(); - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - SetupTwoBookings(db, userId, deskId, fbId, sbId); - - //act - var numberOfBookings = usecases.CountValidBookings(userId, direction, start, end); - - //assert - Assert.NotZero(numberOfBookings); - Assert.That(numberOfBookings == 2); - - //cleanup - db.Database.EnsureDeleted(); + var result = usecases.CreateBooking(Guid.NewGuid(), bookingRequest); + + //assert + Assert.Fail(); } - [Test] - public void GetFilteredBookings_WhenDefaultConfigIsUsed_ShouldReturnASingleBooking() + catch (ArgumentException e) { - //setup - using var db = new DataContext(); - - var userId = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - SetupMockData(db, userId: userId, deskId: deskId); - - var bId = Guid.NewGuid(); - var bStart = DateTime.Now.Add(TimeSpan.FromHours(1)); - var bEnd = DateTime.Now.Add(TimeSpan.FromHours(2)); - var booking = new Booking - { - BookingId = bId, - DeskId = deskId, - UserId = userId, - Timestamp = DateTime.Now, - StartTime = bStart, - EndTime = bEnd - }; - db.Add(booking); - db.SaveChanges(); - - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - - //act - var result = usecases.GetFilteredBookings(userId, int.MaxValue, 0, "DESC", DateTime.Now, DateTime.MaxValue); - - //assert - Assert.That(result, Has.Count.EqualTo(1)); - - //cleanup - db.Database.EnsureDeleted(); + Assert.That(e.Message, Is.EqualTo("User not found")); } - [Test] - [TestCase(1, 0, 1)] - [TestCase(2, 0, 2)] - [TestCase(1, 1, 1)] - [TestCase(1, 2, 0)] - public void GetFilteredBookings_WhenQueryForNandSkip_ShouldReturnTheExpectedAmountOfBookings(int n, int skip, - int expectedBookings) - { - //setup - using var db = new DataContext(); + //cleanup + db.Database.EnsureDeleted(); + } - var userId = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - SetupMockData(db, userId: userId, deskId: deskId); + [Test] + public void CreateBooking_WhenTimeslotBooked_ShouldThrowAnArgumentException() + { + //setup + using var db = new DataContext(); - var fbId = Guid.NewGuid(); - var sbId = Guid.NewGuid(); - SetupTwoBookings(db, userId, deskId, fbId, sbId); + var userId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + var bookingId = Guid.NewGuid(); - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); + SetupMockData(db, userId: userId, deskId: deskId); + var fbStart = DateTime.Now.Add(TimeSpan.FromHours(1)); + var fbEnd = DateTime.Now.Add(TimeSpan.FromHours(2)); + var firstBooking = new Booking + { + BookingId = bookingId, + DeskId = deskId, + UserId = userId, + Timestamp = DateTime.Now, + StartTime = fbStart, + EndTime = fbEnd + }; + db.Add(firstBooking); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + var bookingRequest = new BookingRequest + { + DeskId = deskId, + StartTime = fbStart, + EndTime = fbEnd + }; + //act + try + { + var result = usecases.CreateBooking(userId, bookingRequest); - //act - var result = usecases.GetFilteredBookings(userId, n, skip, "", DateTime.Now, DateTime.MaxValue); + //assert + Assert.Fail(); + } + catch (ArgumentException e) + { + Assert.That(e.Message, Is.EqualTo("Time slot not available")); + } - //assert - Assert.That(result.Count == expectedBookings); + //cleanup + db.Database.EnsureDeleted(); + } - //cleanup - db.Database.EnsureDeleted(); - } + [Test] + public void CreateBooking_WhenAvailable_ShouldReturnABooking() + { + //setup + using var db = new DataContext(); + var userId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + var bookingId = Guid.NewGuid(); - [Test] - public void GetFilteredBookings_WhenQueryForDirectionASC_ShouldReturnTheBookingsInAscendingOrder() + SetupMockData(db, userId: userId, deskId: deskId); + var firstBooking = new Booking + { + BookingId = bookingId, + DeskId = deskId, + UserId = userId, + Timestamp = DateTime.Now, + StartTime = DateTime.Now, + EndTime = DateTime.Now + }; + db.Add(firstBooking); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + var fbStart = DateTime.Now.Add(TimeSpan.FromHours(1)); + var fbEnd = DateTime.Now.Add(TimeSpan.FromHours(2)); + + var bookingRequest = new BookingRequest { - //setup - using var db = new DataContext(); + DeskId = deskId, + StartTime = fbStart, + EndTime = fbEnd + }; + //act + var result = usecases.CreateBooking(userId, bookingRequest); + + //assert + Assert.That(result, Is.Not.Null); + Assert.That(result.DeskId, Is.EqualTo(deskId)); + Assert.That(result.StartTime, Is.EqualTo(fbStart)); + Assert.That(result.EndTime, Is.EqualTo(fbEnd)); + + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void UpdateBooking_WhenUserNotExists_ShouldThrowAnArgumentException() + { + //setup + using var db = new DataContext(); + + var deskId = Guid.NewGuid(); + SetupMockData(db, deskId: deskId); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + var updateBookingRequest = new UpdateBookingRequest + { + StartTime = DateTime.Now, + EndTime = DateTime.Now + }; + //act + try + { + var result = usecases.UpdateBooking(Guid.NewGuid(), Guid.NewGuid(), updateBookingRequest); - var userId = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - SetupMockData(db, userId: userId, deskId: deskId); + //assert + Assert.Fail(); + } + catch (ArgumentException e) + { + Assert.That(e.Message, Is.EqualTo("User not found")); + } - var fbId = Guid.NewGuid(); - var sbId = Guid.NewGuid(); - SetupTwoBookings(db, userId, deskId, fbId, sbId); + //cleanup + db.Database.EnsureDeleted(); + } - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); + [Test] + public void UpdateBooking_WhenBookingNotExists_ShouldThrowAnArgumentException() + { + //setup + using var db = new DataContext(); - //act - var result = usecases.GetFilteredBookings(userId, 2, 0, "ASC", DateTime.Now, DateTime.MaxValue); + var userId = Guid.NewGuid(); + SetupMockData(db, userId: userId); - //assert - Assert.That(result[0].BookingId == fbId); - Assert.That(result[1].BookingId == sbId); + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); - //cleanup - db.Database.EnsureDeleted(); - } + var updateBookingRequest = new UpdateBookingRequest + { + StartTime = DateTime.Now, + EndTime = DateTime.Now + }; + //act + try + { + var result = usecases.UpdateBooking(userId, Guid.NewGuid(), updateBookingRequest); - [Test] - public void GetFilteredBookings_WhenQueryForDirectionDESC_ShouldReturnTheBookingsInDescendingOrder() + //assert + Assert.Fail(); + } + catch (ArgumentException e) { - //setup - using var db = new DataContext(); + Assert.That(e.Message, Is.EqualTo("Booking not found")); + } + + //cleanup + db.Database.EnsureDeleted(); + } - var userId = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - SetupMockData(db, userId: userId, deskId: deskId); + [Test] + public void UpdateBooking_WhenBookingNotFromUser_ShouldThrowAnArgumentException() + { + //setup + using var db = new DataContext(); - var fbId = Guid.NewGuid(); - var sbId = Guid.NewGuid(); - SetupTwoBookings(db, userId, deskId, fbId, sbId); + var userId1 = Guid.NewGuid(); + var userId2 = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + var bookingId = Guid.NewGuid(); - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); + SetupMockData(db, userId: userId1, deskId: deskId); + SetupMockData(db, userId: userId2); - //act - var result = usecases.GetFilteredBookings(userId, 2, 0, "DESC", DateTime.Now, DateTime.MaxValue); + var firstBooking = new Booking + { + BookingId = bookingId, + DeskId = deskId, + UserId = userId1, + Timestamp = DateTime.Now, + StartTime = DateTime.Now, + EndTime = DateTime.Now + }; + db.Add(firstBooking); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + var updateBookingRequest = new UpdateBookingRequest + { + StartTime = DateTime.Now, + EndTime = DateTime.Now + }; - //assert - Assert.That(result[0].BookingId, Is.EqualTo(sbId)); - Assert.That(result[1].BookingId, Is.EqualTo(fbId)); + //act + try + { + var result = usecases.UpdateBooking(userId2, bookingId, updateBookingRequest); - //cleanup - db.Database.EnsureDeleted(); + //assert + Assert.Fail(); } - - [Test] - public void - GetFilteredBookings_WhenStartIsAfterBookingStartTime_ShouldNotReturnTheBookingsWhereStartTimeBeforeStart() + catch (ArgumentException e) { - //setup - using var db = new DataContext(); + Assert.That(e.Message, Is.EqualTo("You are not allowed to update this booking")); + } - var userId = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - SetupMockData(db, userId: userId, deskId: deskId); + //cleanup + db.Database.EnsureDeleted(); + } - var fbId = Guid.NewGuid(); - var sbId = Guid.NewGuid(); - var (firstBooking, secondBooking) = SetupTwoBookings(db, userId, deskId, fbId, sbId); + [Test] + public void UpdateBooking_WhenTimeslotBooked_ShouldThrowAnArgumentException() + { + //setup + using var db = new DataContext(); - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - var start = firstBooking.StartTime.Add(TimeSpan.FromTicks(1)); + var userId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + var bookingId = Guid.NewGuid(); - //act - var result = usecases.GetFilteredBookings(userId, 2, 0, "DESC", start, DateTime.MaxValue); + SetupMockData(db, userId: userId, deskId: deskId); + var fbStart = DateTime.Now.Add(TimeSpan.FromHours(1)); + var fbEnd = DateTime.Now.Add(TimeSpan.FromHours(2)); - //assert - Assert.That(result, Has.Count.EqualTo(1)); - Assert.That(result, Does.Not.Contain(firstBooking)); - Assert.That(result, Does.Contain(secondBooking)); + var firstBooking = new Booking + { + BookingId = bookingId, + DeskId = deskId, + UserId = userId, + Timestamp = DateTime.Now, + StartTime = DateTime.Now, + EndTime = DateTime.Now + }; + var secondBooking = new Booking + { + BookingId = Guid.NewGuid(), + DeskId = deskId, + UserId = userId, + Timestamp = DateTime.Now, + StartTime = fbStart, + EndTime = fbEnd + }; + db.Add(firstBooking); + db.Add(secondBooking); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + var updateBookingRequest = new UpdateBookingRequest + { + StartTime = fbStart, + EndTime = fbEnd + }; + //act + try + { + var result = usecases.UpdateBooking(userId, bookingId, updateBookingRequest); - //cleanup - db.Database.EnsureDeleted(); + //assert + Assert.Fail(); } - - [Test] - public void GetFilteredBookings_WhenEndIsBeforeBookingStartTime_ShouldNotReturnTheBookingsWhereStartTimeAfterEnd() + catch (ArgumentException e) { - //setup - using var db = new DataContext(); + Assert.That(e.Message, Is.EqualTo("Time slot not available")); + } - var userId = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - SetupMockData(db, userId: userId, deskId: deskId); + //cleanup + db.Database.EnsureDeleted(); + } - var fbId = Guid.NewGuid(); - var sbId = Guid.NewGuid(); - var (firstBooking, secondBooking) = SetupTwoBookings(db, userId, deskId, fbId, sbId); + [Test] + public void UpdateBooking_WhenAvailable_ShouldReturnABooking() + { + //setup + using var db = new DataContext(); - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - var end = secondBooking.StartTime.Subtract(TimeSpan.FromTicks(1)); + var userId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + var bookingId = Guid.NewGuid(); - //act - var result = usecases.GetFilteredBookings(userId, 2, 0, "DESC", DateTime.Now, end); + SetupMockData(db, userId: userId, deskId: deskId); + var fbStart = DateTime.Now.Add(TimeSpan.FromHours(1)); + var fbEnd = DateTime.Now.Add(TimeSpan.FromHours(2)); - //assert - Assert.That(result, Has.Count.EqualTo(1)); - Assert.That(result, Does.Contain(firstBooking)); - Assert.That(result, Does.Not.Contain(secondBooking)); + var firstBooking = new Booking + { + BookingId = bookingId, + DeskId = deskId, + UserId = userId, + Timestamp = DateTime.Now, + StartTime = fbStart, + EndTime = fbEnd + }; + db.Add(firstBooking); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + var updateBookingRequest = new UpdateBookingRequest + { + StartTime = DateTime.Now, + EndTime = DateTime.Now + }; + //act + var result = usecases.UpdateBooking(userId, bookingId, updateBookingRequest); + + //assert + Assert.That(result, Is.Not.Null); + Assert.That(result.BookingId, Is.EqualTo(bookingId)); + Assert.That(result.UserId, Is.EqualTo(userId)); + Assert.That(result.DeskId, Is.EqualTo(deskId)); + Assert.That(result.StartTime, Is.EqualTo(updateBookingRequest.StartTime)); + Assert.That(result.EndTime, Is.EqualTo(updateBookingRequest.EndTime)); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void DeleteBooking_WhenUserNotExists_ShouldThrowAnArgumentException() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + var bookingId = Guid.NewGuid(); + + SetupMockData(db, userId: userId, deskId: deskId); + var firstBooking = new Booking + { + BookingId = bookingId, + DeskId = deskId, + UserId = userId, + Timestamp = DateTime.Now, + StartTime = DateTime.Now, + EndTime = DateTime.Now + }; + db.Add(firstBooking); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + //act + try + { + var result = usecases.DeleteBooking(Guid.NewGuid(), bookingId); - //cleanup - db.Database.EnsureDeleted(); + //assert + Assert.Fail(); } - - [Test] - public void CreateBooking_WhenDesksNotExists_ShouldThrowAnArgumentException() + catch (ArgumentException e) { - //setup - using var db = new DataContext(); - - var userId = Guid.NewGuid(); - SetupMockData(db, userId: userId); - - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - - var bookingRequest = new BookingRequest - { - DeskId = Guid.NewGuid(), - StartTime = DateTime.Now, - EndTime = DateTime.Now - }; - //act - try - { - var result = usecases.CreateBooking(Guid.NewGuid(), bookingRequest); - - //assert - Assert.Fail(); - } - catch (ArgumentException e) - { - Assert.That(e.Message, Is.EqualTo("Desk not found")); - } - - //cleanup - db.Database.EnsureDeleted(); + Assert.That(e.Message, Is.EqualTo("User not found")); } - [Test] - public void CreateBooking_WhenUserNotExists_ShouldThrowAnArgumentException() - { - //setup - using var db = new DataContext(); - - var deskId = Guid.NewGuid(); - SetupMockData(db, deskId: deskId); - - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - - var bookingRequest = new BookingRequest - { - DeskId = deskId, - StartTime = DateTime.Now, - EndTime = DateTime.Now - }; - //act - try - { - var result = usecases.CreateBooking(Guid.NewGuid(), bookingRequest); - - //assert - Assert.Fail(); - } - catch (ArgumentException e) - { - Assert.That(e.Message, Is.EqualTo("User not found")); - } - - //cleanup - db.Database.EnsureDeleted(); - } + //cleanup + db.Database.EnsureDeleted(); + } - [Test] - public void CreateBooking_WhenTimeslotBooked_ShouldThrowAnArgumentException() - { - //setup - using var db = new DataContext(); - - var userId = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - var bookingId = Guid.NewGuid(); - - SetupMockData(db, userId: userId, deskId: deskId); - var fbStart = DateTime.Now.Add(TimeSpan.FromHours(1)); - var fbEnd = DateTime.Now.Add(TimeSpan.FromHours(2)); - var firstBooking = new Booking - { - BookingId = bookingId, - DeskId = deskId, - UserId = userId, - Timestamp = DateTime.Now, - StartTime = fbStart, - EndTime = fbEnd - }; - db.Add(firstBooking); - db.SaveChanges(); - - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - - var bookingRequest = new BookingRequest - { - DeskId = deskId, - StartTime = fbStart, - EndTime = fbEnd - }; - //act - try - { - var result = usecases.CreateBooking(userId, bookingRequest); - - //assert - Assert.Fail(); - } - catch (ArgumentException e) - { - Assert.That(e.Message, Is.EqualTo("Time slot not available")); - } - - //cleanup - db.Database.EnsureDeleted(); - } + [Test] + public void DeleteBooking_WhenBookingNotExists_ShouldThrowAnArgumentException() + { + //setup + using var db = new DataContext(); - [Test] - public void CreateBooking_WhenAvailable_ShouldReturnABooking() - { - //setup - using var db = new DataContext(); - - var userId = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - var bookingId = Guid.NewGuid(); - - SetupMockData(db, userId: userId, deskId: deskId); - var firstBooking = new Booking - { - BookingId = bookingId, - DeskId = deskId, - UserId = userId, - Timestamp = DateTime.Now, - StartTime = DateTime.Now, - EndTime = DateTime.Now - }; - db.Add(firstBooking); - db.SaveChanges(); - - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - - var fbStart = DateTime.Now.Add(TimeSpan.FromHours(1)); - var fbEnd = DateTime.Now.Add(TimeSpan.FromHours(2)); - - var bookingRequest = new BookingRequest - { - DeskId = deskId, - StartTime = fbStart, - EndTime = fbEnd - }; - //act - var result = usecases.CreateBooking(userId, bookingRequest); - - //assert - Assert.That(result, Is.Not.Null); - Assert.That(result.DeskId, Is.EqualTo(deskId)); - Assert.That(result.StartTime, Is.EqualTo(fbStart)); - Assert.That(result.EndTime, Is.EqualTo(fbEnd)); - - - //cleanup - db.Database.EnsureDeleted(); - } + var userId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + var bookingId = Guid.NewGuid(); - [Test] - public void UpdateBooking_WhenUserNotExists_ShouldThrowAnArgumentException() - { - //setup - using var db = new DataContext(); - - var deskId = Guid.NewGuid(); - SetupMockData(db, deskId: deskId); - - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - - var updateBookingRequest = new UpdateBookingRequest - { - StartTime = DateTime.Now, - EndTime = DateTime.Now - }; - //act - try - { - var result = usecases.UpdateBooking(Guid.NewGuid(), Guid.NewGuid(), updateBookingRequest); - - //assert - Assert.Fail(); - } - catch (ArgumentException e) - { - Assert.That(e.Message, Is.EqualTo("User not found")); - } - - //cleanup - db.Database.EnsureDeleted(); - } + SetupMockData(db, userId: userId, deskId: deskId); - [Test] - public void UpdateBooking_WhenBookingNotExists_ShouldThrowAnArgumentException() - { - //setup - using var db = new DataContext(); - - var userId = Guid.NewGuid(); - SetupMockData(db, userId: userId); - - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - - var updateBookingRequest = new UpdateBookingRequest - { - StartTime = DateTime.Now, - EndTime = DateTime.Now - }; - //act - try - { - var result = usecases.UpdateBooking(userId, Guid.NewGuid(), updateBookingRequest); - - //assert - Assert.Fail(); - } - catch (ArgumentException e) - { - Assert.That(e.Message, Is.EqualTo("Booking not found")); - } - - //cleanup - db.Database.EnsureDeleted(); - } + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); - [Test] - public void UpdateBooking_WhenBookingNotFromUser_ShouldThrowAnArgumentException() + //act + try { - //setup - using var db = new DataContext(); - - var userId1 = Guid.NewGuid(); - var userId2 = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - var bookingId = Guid.NewGuid(); - - SetupMockData(db, userId: userId1, deskId: deskId); - SetupMockData(db, userId: userId2); - - var firstBooking = new Booking - { - BookingId = bookingId, - DeskId = deskId, - UserId = userId1, - Timestamp = DateTime.Now, - StartTime = DateTime.Now, - EndTime = DateTime.Now - }; - db.Add(firstBooking); - db.SaveChanges(); - - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - - var updateBookingRequest = new UpdateBookingRequest - { - StartTime = DateTime.Now, - EndTime = DateTime.Now - }; - - //act - try - { - var result = usecases.UpdateBooking(userId2, bookingId, updateBookingRequest); - - //assert - Assert.Fail(); - } - catch (ArgumentException e) - { - Assert.That(e.Message, Is.EqualTo("You are not allowed to update this booking")); - } - - //cleanup - db.Database.EnsureDeleted(); - } + var result = usecases.DeleteBooking(userId, bookingId); - [Test] - public void UpdateBooking_WhenTimeslotBooked_ShouldThrowAnArgumentException() - { - //setup - using var db = new DataContext(); - - var userId = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - var bookingId = Guid.NewGuid(); - - SetupMockData(db, userId: userId, deskId: deskId); - var fbStart = DateTime.Now.Add(TimeSpan.FromHours(1)); - var fbEnd = DateTime.Now.Add(TimeSpan.FromHours(2)); - - var firstBooking = new Booking - { - BookingId = bookingId, - DeskId = deskId, - UserId = userId, - Timestamp = DateTime.Now, - StartTime = DateTime.Now, - EndTime = DateTime.Now - }; - var secondBooking = new Booking - { - BookingId = Guid.NewGuid(), - DeskId = deskId, - UserId = userId, - Timestamp = DateTime.Now, - StartTime = fbStart, - EndTime = fbEnd - }; - db.Add(firstBooking); - db.Add(secondBooking); - db.SaveChanges(); - - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - - var updateBookingRequest = new UpdateBookingRequest - { - StartTime = fbStart, - EndTime = fbEnd - }; - //act - try - { - var result = usecases.UpdateBooking(userId, bookingId, updateBookingRequest); - - //assert - Assert.Fail(); - } - catch (ArgumentException e) - { - Assert.That(e.Message, Is.EqualTo("Time slot not available")); - } - - //cleanup - db.Database.EnsureDeleted(); + //assert + Assert.Fail(); } - - [Test] - public void UpdateBooking_WhenAvailable_ShouldReturnABooking() + catch (ArgumentException e) { - //setup - using var db = new DataContext(); - - var userId = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - var bookingId = Guid.NewGuid(); - - SetupMockData(db, userId: userId, deskId: deskId); - var fbStart = DateTime.Now.Add(TimeSpan.FromHours(1)); - var fbEnd = DateTime.Now.Add(TimeSpan.FromHours(2)); - - var firstBooking = new Booking - { - BookingId = bookingId, - DeskId = deskId, - UserId = userId, - Timestamp = DateTime.Now, - StartTime = fbStart, - EndTime = fbEnd - }; - db.Add(firstBooking); - db.SaveChanges(); - - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - - var updateBookingRequest = new UpdateBookingRequest - { - StartTime = DateTime.Now, - EndTime = DateTime.Now - }; - //act - var result = usecases.UpdateBooking(userId, bookingId, updateBookingRequest); - - //assert - Assert.That(result, Is.Not.Null); - Assert.That(result.BookingId, Is.EqualTo(bookingId)); - Assert.That(result.UserId, Is.EqualTo(userId)); - Assert.That(result.DeskId, Is.EqualTo(deskId)); - Assert.That(result.StartTime, Is.EqualTo(updateBookingRequest.StartTime)); - Assert.That(result.EndTime, Is.EqualTo(updateBookingRequest.EndTime)); - - //cleanup - db.Database.EnsureDeleted(); + Assert.That(e.Message, Is.EqualTo("Booking not found")); } - [Test] - public void DeleteBooking_WhenUserNotExists_ShouldThrowAnArgumentException() - { - //setup - using var db = new DataContext(); - - var userId = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - var bookingId = Guid.NewGuid(); - - SetupMockData(db, userId: userId, deskId: deskId); - var firstBooking = new Booking - { - BookingId = bookingId, - DeskId = deskId, - UserId = userId, - Timestamp = DateTime.Now, - StartTime = DateTime.Now, - EndTime = DateTime.Now - }; - db.Add(firstBooking); - db.SaveChanges(); - - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - - //act - try - { - var result = usecases.DeleteBooking(Guid.NewGuid(), bookingId); - - //assert - Assert.Fail(); - } - catch (ArgumentException e) - { - Assert.That(e.Message, Is.EqualTo("User not found")); - } - - //cleanup - db.Database.EnsureDeleted(); - } + //cleanup + db.Database.EnsureDeleted(); + } - [Test] - public void DeleteBooking_WhenBookingNotExists_ShouldThrowAnArgumentException() - { - //setup - using var db = new DataContext(); - - var userId = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - var bookingId = Guid.NewGuid(); - - SetupMockData(db, userId: userId, deskId: deskId); - - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - - //act - try - { - var result = usecases.DeleteBooking(userId, bookingId); - - //assert - Assert.Fail(); - } - catch (ArgumentException e) - { - Assert.That(e.Message, Is.EqualTo("Booking not found")); - } - - //cleanup - db.Database.EnsureDeleted(); - } + [Test] + public void DeleteBooking_WhenBookingNotFromUser_ShouldThrowAnArgumentException() + { + //setup + using var db = new DataContext(); - [Test] - public void DeleteBooking_WhenBookingNotFromUser_ShouldThrowAnArgumentException() - { - //setup - using var db = new DataContext(); - - var userId1 = Guid.NewGuid(); - var userId2 = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - var bookingId = Guid.NewGuid(); - - SetupMockData(db, userId: userId1, deskId: deskId); - SetupMockData(db, userId: userId2); - - var firstBooking = new Booking - { - BookingId = bookingId, - DeskId = deskId, - UserId = userId1, - Timestamp = DateTime.Now, - StartTime = DateTime.Now, - EndTime = DateTime.Now - }; - db.Add(firstBooking); - db.SaveChanges(); - - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - - //act - try - { - var result = usecases.DeleteBooking(userId2, bookingId); - - //assert - Assert.Fail(); - } - catch (ArgumentException e) - { - Assert.That(e.Message, Is.EqualTo("You are not allowed to delete this booking")); - } - - //cleanup - db.Database.EnsureDeleted(); - } + var userId1 = Guid.NewGuid(); + var userId2 = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + var bookingId = Guid.NewGuid(); - [Test] - public void DeleteBooking_WhenBookingExists_ShouldReturnABooking() - { - //setup - using var db = new DataContext(); - - var userId = Guid.NewGuid(); - var deskId = Guid.NewGuid(); - var bookingId = Guid.NewGuid(); - - SetupMockData(db, userId: userId, deskId: deskId); - var firstBooking = new Booking - { - BookingId = bookingId, - DeskId = deskId, - UserId = userId, - Timestamp = DateTime.Now, - StartTime = DateTime.Now, - EndTime = DateTime.Now - }; - db.Add(firstBooking); - db.SaveChanges(); - - //arrange - var logger = new Mock>(); - var usecases = new BookingUsecases(logger.Object, db); - - //act - var result = usecases.DeleteBooking(userId, bookingId); - - //assert - Assert.That(result, Is.Not.Null); - Assert.That(result.DeskId, Is.EqualTo(deskId)); - Assert.That(result.StartTime, Is.EqualTo(firstBooking.StartTime)); - Assert.That(result.EndTime, Is.EqualTo(firstBooking.EndTime)); - - //cleanup - db.Database.EnsureDeleted(); - } + SetupMockData(db, userId: userId1, deskId: deskId); + SetupMockData(db, userId: userId2); - private void SetupMockData(DataContext moqDb, Guid companyId = new(), Guid userId = new(), Guid buildingId = new(), - Guid floorId = new(), Guid roomId = new(), Guid deskTypeId = new(), Guid deskId = new()) + var firstBooking = new Booking { - if (companyId.ToString() == "00000000-0000-0000-0000-000000000000") companyId = Guid.NewGuid(); - if (userId.ToString() == "00000000-0000-0000-0000-000000000000") userId = Guid.NewGuid(); - if (buildingId.ToString() == "00000000-0000-0000-0000-000000000000") buildingId = Guid.NewGuid(); - if (floorId.ToString() == "00000000-0000-0000-0000-000000000000") floorId = Guid.NewGuid(); - if (roomId.ToString() == "00000000-0000-0000-0000-000000000000") roomId = Guid.NewGuid(); - if (deskTypeId.ToString() == "00000000-0000-0000-0000-000000000000") deskTypeId = Guid.NewGuid(); - if (deskId.ToString() == "00000000-0000-0000-0000-000000000000") deskId = Guid.NewGuid(); - - var hasher = new PasswordHasher(); - var company = new Company - { - CompanyId = companyId, - CompanyName = "gehmalbierholn" - }; - var user = new User - { - UserId = userId, - MailAddress = "test@example.de", - FirstName = "testF", - LastName = "testL", - CompanyId = company.CompanyId, - IsApproved = true - }; - user.Password = hasher.HashPassword(user, "testpw"); - var building = new Building - { - BuildingId = buildingId, - BuildingName = "Gebäude1", - Location = "Location1", - CompanyId = company.CompanyId - }; - var floor = new Floor - { - FloorId = floorId, - FloorName = "Stockwerk1", - BuildingId = building.BuildingId - }; - var room = new Room - { - RoomId = roomId, - FloorId = floor.FloorId, - RoomName = "Raum1" - }; - var deskTyp = new DeskType - { - DeskTypeId = deskTypeId, - CompanyId = company.CompanyId, - DeskTypeName = "Typ1" - }; - var desk = new Desk - { - DeskId = deskId, - DeskName = "Desk1", - DeskTypeId = deskTyp.DeskTypeId, - RoomId = room.RoomId - }; - moqDb.Companies.Add(company); - moqDb.Users.Add(user); - moqDb.Buildings.Add(building); - moqDb.Floors.Add(floor); - moqDb.Rooms.Add(room); - moqDb.DeskTypes.Add(deskTyp); - moqDb.Desks.Add(desk); - - moqDb.SaveChanges(); - } - - private (Booking, Booking) SetupTwoBookings(DataContext db, Guid userId, Guid deskId, Guid fbId, Guid sbId) + BookingId = bookingId, + DeskId = deskId, + UserId = userId1, + Timestamp = DateTime.Now, + StartTime = DateTime.Now, + EndTime = DateTime.Now + }; + db.Add(firstBooking); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + //act + try { - var fbStart = DateTime.Now.Add(TimeSpan.FromHours(1)); - var fbEnd = DateTime.Now.Add(TimeSpan.FromHours(2)); - var firstBooking = new Booking - { - BookingId = fbId, - DeskId = deskId, - UserId = userId, - Timestamp = DateTime.Now, - StartTime = fbStart, - EndTime = fbEnd - }; - - var sbStart = DateTime.Now.Add(TimeSpan.FromDays(1)); - var sbEnd = DateTime.Now.Add(TimeSpan.FromDays(1)); - var secondBooking = new Booking - { - BookingId = sbId, - DeskId = deskId, - UserId = userId, - Timestamp = DateTime.Now, - StartTime = sbStart, - EndTime = sbEnd - }; - db.Add(firstBooking); - db.Add(secondBooking); - db.SaveChanges(); - return (firstBooking, secondBooking); - } + var result = usecases.DeleteBooking(userId2, bookingId); - private void AddOneCompany_AddOneUser(DataContext mogDb, PasswordHasher hasher) + //assert + Assert.Fail(); + } + catch (ArgumentException e) { - var company = new Company - { - CompanyId = new Guid(), - CompanyName = "gehmalbierholn" - }; - var user = new User - { - UserId = new Guid(), - MailAddress = "test@mail.de", - FirstName = "testF", - LastName = "testL", - Company = company, - IsApproved = true - }; - user.Password = hasher.HashPassword(user, "testpw"); - mogDb.Companies.Add(company); - mogDb.Users.Add(user); - mogDb.SaveChanges(); - mogDb.Companies.Add(company); - mogDb.Users.Add(user); - mogDb.SaveChanges(); + Assert.That(e.Message, Is.EqualTo("You are not allowed to delete this booking")); } - private void FillDatabaseWithEverything(DataContext mogDb, PasswordHasher hasher) + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void DeleteBooking_WhenBookingExists_ShouldReturnABooking() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + var bookingId = Guid.NewGuid(); + + SetupMockData(db, userId: userId, deskId: deskId); + var firstBooking = new Booking { - var company = new Company - { - CompanyId = Guid.NewGuid(), - CompanyName = "gehmalbierholn" - }; - var user = new User - { - UserId = Guid.NewGuid(), - MailAddress = "test@example.de", - FirstName = "testF", - LastName = "testL", - CompanyId = company.CompanyId, - IsApproved = true - }; - user.Password = hasher.HashPassword(user, "testpw"); - var building = new Building - { - BuildingId = Guid.NewGuid(), - BuildingName = "Gebäude1", - Location = "Location1", - CompanyId = company.CompanyId - }; - var floor = new Floor - { - FloorId = Guid.NewGuid(), - FloorName = "Stockwerk1", - BuildingId = building.BuildingId - }; - var room = new Room - { - RoomId = Guid.NewGuid(), - FloorId = floor.FloorId, - RoomName = "Raum1" - }; - var deskTyp = new DeskType - { - DeskTypeId = Guid.NewGuid(), - CompanyId = company.CompanyId, - DeskTypeName = "Typ1" - }; - var desk = new Desk - { - DeskId = Guid.NewGuid(), - DeskName = "Desk1", - DeskTypeId = deskTyp.DeskTypeId, - RoomId = room.RoomId - }; - var booking = new Booking - { - UserId = user.UserId, - DeskId = desk.DeskId, - Timestamp = DateTime.Now, - StartTime = DateTime.Now.Add(TimeSpan.FromHours(1)), - EndTime = DateTime.Now.Add(TimeSpan.FromHours(2)) - }; - mogDb.Companies.Add(company); - mogDb.Users.Add(user); - mogDb.Buildings.Add(building); - mogDb.Floors.Add(floor); - mogDb.Rooms.Add(room); - mogDb.DeskTypes.Add(deskTyp); - mogDb.Desks.Add(desk); - mogDb.Bookings.Add(booking); - - mogDb.SaveChanges(); - } -} \ No newline at end of file + BookingId = bookingId, + DeskId = deskId, + UserId = userId, + Timestamp = DateTime.Now, + StartTime = DateTime.Now, + EndTime = DateTime.Now + }; + db.Add(firstBooking); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new BookingUsecases(logger.Object, db); + + //act + var result = usecases.DeleteBooking(userId, bookingId); + + //assert + Assert.That(result, Is.Not.Null); + Assert.That(result.DeskId, Is.EqualTo(deskId)); + Assert.That(result.StartTime, Is.EqualTo(firstBooking.StartTime)); + Assert.That(result.EndTime, Is.EqualTo(firstBooking.EndTime)); + + //cleanup + db.Database.EnsureDeleted(); + } + + private void SetupMockData(DataContext moqDb, Guid companyId = new(), Guid userId = new(), Guid buildingId = new(), + Guid floorId = new(), Guid roomId = new(), Guid deskTypeId = new(), Guid deskId = new()) + { + if (companyId.ToString() == "00000000-0000-0000-0000-000000000000") companyId = Guid.NewGuid(); + if (userId.ToString() == "00000000-0000-0000-0000-000000000000") userId = Guid.NewGuid(); + if (buildingId.ToString() == "00000000-0000-0000-0000-000000000000") buildingId = Guid.NewGuid(); + if (floorId.ToString() == "00000000-0000-0000-0000-000000000000") floorId = Guid.NewGuid(); + if (roomId.ToString() == "00000000-0000-0000-0000-000000000000") roomId = Guid.NewGuid(); + if (deskTypeId.ToString() == "00000000-0000-0000-0000-000000000000") deskTypeId = Guid.NewGuid(); + if (deskId.ToString() == "00000000-0000-0000-0000-000000000000") deskId = Guid.NewGuid(); + + var hasher = new PasswordHasher(); + var company = new Company + { + CompanyId = companyId, + CompanyName = "gehmalbierholn" + }; + var user = new User + { + UserId = userId, + MailAddress = "test@example.de", + FirstName = "testF", + LastName = "testL", + CompanyId = company.CompanyId, + IsApproved = true + }; + user.Password = hasher.HashPassword(user, "testpw"); + var building = new Building + { + BuildingId = buildingId, + BuildingName = "Gebäude1", + Location = "Location1", + CompanyId = company.CompanyId + }; + var floor = new Floor + { + FloorId = floorId, + FloorName = "Stockwerk1", + BuildingId = building.BuildingId + }; + var room = new Room + { + RoomId = roomId, + FloorId = floor.FloorId, + RoomName = "Raum1" + }; + var deskTyp = new DeskType + { + DeskTypeId = deskTypeId, + CompanyId = company.CompanyId, + DeskTypeName = "Typ1" + }; + var desk = new Desk + { + DeskId = deskId, + DeskName = "Desk1", + DeskTypeId = deskTyp.DeskTypeId, + RoomId = room.RoomId + }; + moqDb.Companies.Add(company); + moqDb.Users.Add(user); + moqDb.Buildings.Add(building); + moqDb.Floors.Add(floor); + moqDb.Rooms.Add(room); + moqDb.DeskTypes.Add(deskTyp); + moqDb.Desks.Add(desk); + + moqDb.SaveChanges(); + } + + private (Booking, Booking) SetupTwoBookings(DataContext db, Guid userId, Guid deskId, Guid fbId, Guid sbId) + { + var fbStart = DateTime.Now.Add(TimeSpan.FromHours(1)); + var fbEnd = DateTime.Now.Add(TimeSpan.FromHours(2)); + var firstBooking = new Booking + { + BookingId = fbId, + DeskId = deskId, + UserId = userId, + Timestamp = DateTime.Now, + StartTime = fbStart, + EndTime = fbEnd + }; + + var sbStart = DateTime.Now.Add(TimeSpan.FromDays(1)); + var sbEnd = DateTime.Now.Add(TimeSpan.FromDays(1)); + var secondBooking = new Booking + { + BookingId = sbId, + DeskId = deskId, + UserId = userId, + Timestamp = DateTime.Now, + StartTime = sbStart, + EndTime = sbEnd + }; + db.Add(firstBooking); + db.Add(secondBooking); + db.SaveChanges(); + return (firstBooking, secondBooking); + } + + private void AddOneCompany_AddOneUser(DataContext mogDb, PasswordHasher hasher) + { + var company = new Company + { + CompanyId = new Guid(), + CompanyName = "gehmalbierholn" + }; + var user = new User + { + UserId = new Guid(), + MailAddress = "test@mail.de", + FirstName = "testF", + LastName = "testL", + Company = company, + IsApproved = true + }; + user.Password = hasher.HashPassword(user, "testpw"); + mogDb.Companies.Add(company); + mogDb.Users.Add(user); + mogDb.SaveChanges(); + mogDb.Companies.Add(company); + mogDb.Users.Add(user); + mogDb.SaveChanges(); + } + + private void FillDatabaseWithEverything(DataContext mogDb, PasswordHasher hasher) + { + var company = new Company + { + CompanyId = Guid.NewGuid(), + CompanyName = "gehmalbierholn" + }; + var user = new User + { + UserId = Guid.NewGuid(), + MailAddress = "test@example.de", + FirstName = "testF", + LastName = "testL", + CompanyId = company.CompanyId, + IsApproved = true + }; + user.Password = hasher.HashPassword(user, "testpw"); + var building = new Building + { + BuildingId = Guid.NewGuid(), + BuildingName = "Gebäude1", + Location = "Location1", + CompanyId = company.CompanyId + }; + var floor = new Floor + { + FloorId = Guid.NewGuid(), + FloorName = "Stockwerk1", + BuildingId = building.BuildingId + }; + var room = new Room + { + RoomId = Guid.NewGuid(), + FloorId = floor.FloorId, + RoomName = "Raum1" + }; + var deskTyp = new DeskType + { + DeskTypeId = Guid.NewGuid(), + CompanyId = company.CompanyId, + DeskTypeName = "Typ1" + }; + var desk = new Desk + { + DeskId = Guid.NewGuid(), + DeskName = "Desk1", + DeskTypeId = deskTyp.DeskTypeId, + RoomId = room.RoomId + }; + var booking = new Booking + { + UserId = user.UserId, + DeskId = desk.DeskId, + Timestamp = DateTime.Now, + StartTime = DateTime.Now.Add(TimeSpan.FromHours(1)), + EndTime = DateTime.Now.Add(TimeSpan.FromHours(2)) + }; + mogDb.Companies.Add(company); + mogDb.Users.Add(user); + mogDb.Buildings.Add(building); + mogDb.Floors.Add(floor); + mogDb.Rooms.Add(room); + mogDb.DeskTypes.Add(deskTyp); + mogDb.Desks.Add(desk); + mogDb.Bookings.Add(booking); + + mogDb.SaveChanges(); + } +} diff --git a/src/deskstar-backend/Teststar.Tests/Tests/CompanyUsecasesTests.cs b/src/deskstar-backend/Teststar.Tests/Tests/CompanyUsecasesTests.cs index ddfd2fdf..4a4b4908 100644 --- a/src/deskstar-backend/Teststar.Tests/Tests/CompanyUsecasesTests.cs +++ b/src/deskstar-backend/Teststar.Tests/Tests/CompanyUsecasesTests.cs @@ -1,8 +1,6 @@ -using Deskstar.Core.Exceptions; using Deskstar.DataAccess; using Deskstar.Entities; using Deskstar.Usecases; -using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Moq; @@ -10,7 +8,6 @@ namespace Teststar.Tests.Tests; public class CompanyUsecasesTests { - [Test] public void GetCompanies_ShouldReturnAllCompanies() { @@ -37,7 +34,7 @@ public void GetCompanies_ShouldReturnAllCompanies() db.Database.EnsureDeleted(); } - private void setupMockData(DataContext db, Guid companyID, String companyName) + private void setupMockData(DataContext db, Guid companyID, string companyName) { var company = new Company { diff --git a/src/deskstar-backend/Teststar.Tests/Tests/ResourceUsecasesTests.cs b/src/deskstar-backend/Teststar.Tests/Tests/ResourceUsecasesTests.cs index 44646089..9efe1272 100644 --- a/src/deskstar-backend/Teststar.Tests/Tests/ResourceUsecasesTests.cs +++ b/src/deskstar-backend/Teststar.Tests/Tests/ResourceUsecasesTests.cs @@ -17,7 +17,8 @@ public void UpdateBuilding_WhenBuildingIdDoesNotExist_ShouldThrowEntityNotFoundE var companyId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = Guid.NewGuid(), CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = Guid.NewGuid(), CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; context.Buildings.Add(building); context.SaveChanges(); @@ -25,16 +26,18 @@ public void UpdateBuilding_WhenBuildingIdDoesNotExist_ShouldThrowEntityNotFoundE var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, "Building Name", "Location")); + var ex = Assert.Throws(() => + resourceUsecases.UpdateBuilding(companyId, buildingId, "Building Name", "Location")); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"There is no building with id '{buildingId}'")); + Assert.That(ex?.Message, Is.EqualTo($"There is no building with id '{buildingId}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateBuilding_WhenBuildingNameDoesAlreadyExist_ShouldThrowArgumentInvalidException() { @@ -46,7 +49,8 @@ public void UpdateBuilding_WhenBuildingNameDoesAlreadyExist_ShouldThrowArgumentI var buildingName = "testbuilding"; var company = new Company { CompanyId = companyId, CompanyName = "testcompany" }; - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = buildingName, Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = buildingName, Location = "testlocation" }; context.Companies.Add(company); context.Buildings.Add(building); @@ -56,16 +60,18 @@ public void UpdateBuilding_WhenBuildingNameDoesAlreadyExist_ShouldThrowArgumentI var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, buildingName, null)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateBuilding(companyId, buildingId, buildingName, null)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"There is already a building named '{buildingName}' in your company")); + Assert.That(ex?.Message, Is.EqualTo($"There is already a building named '{buildingName}' in your company")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateBuilding_WhenCompanyIdDoesNotMatchBuilding_ShouldThrowInsufficientPermissionException() { @@ -76,7 +82,8 @@ public void UpdateBuilding_WhenCompanyIdDoesNotMatchBuilding_ShouldThrowInsuffic var buildingId = Guid.NewGuid(); var context = new DataContext(); var buildingName = "testname"; - var building = new Building { BuildingId = buildingId, CompanyId = company2Id, BuildingName = buildingName, Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = company2Id, BuildingName = buildingName, Location = "testlocation" }; context.Companies.Add(company2); context.Buildings.Add(building); context.SaveChanges(); @@ -85,16 +92,18 @@ public void UpdateBuilding_WhenCompanyIdDoesNotMatchBuilding_ShouldThrowInsuffic var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, "Building Name", "Location")); + var ex = Assert.Throws(() => + resourceUsecases.UpdateBuilding(companyId, buildingId, "Building Name", "Location")); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"Your company has no access to administrate building '{buildingName}'")); + Assert.That(ex?.Message, Is.EqualTo($"Your company has no access to administrate building '{buildingName}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateBuilding_WhenAllInputIsValid_ShouldUpdateBuilding() { @@ -106,7 +115,8 @@ public void UpdateBuilding_WhenAllInputIsValid_ShouldUpdateBuilding() var buildingName = "testbuilding"; var company = new Company { CompanyId = companyId, CompanyName = "testcompany" }; - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = buildingName, Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = buildingName, Location = "testlocation" }; context.Companies.Add(company); context.Buildings.Add(building); @@ -116,7 +126,7 @@ public void UpdateBuilding_WhenAllInputIsValid_ShouldUpdateBuilding() var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); var updatedBuildingName = "New Building Name"; var updatedLocation = "New York"; // act @@ -130,6 +140,7 @@ public void UpdateBuilding_WhenAllInputIsValid_ShouldUpdateBuilding() // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateBuilding_WhenOnlyLocationIsProvided_ShouldUpdateBuildingLocation() { @@ -138,7 +149,8 @@ public void UpdateBuilding_WhenOnlyLocationIsProvided_ShouldUpdateBuildingLocati var company = new Company { CompanyId = companyId, CompanyName = "testcompany" }; var buildingId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; context.Companies.Add(company); context.Buildings.Add(building); context.SaveChanges(); @@ -147,7 +159,7 @@ public void UpdateBuilding_WhenOnlyLocationIsProvided_ShouldUpdateBuildingLocati var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); var newLocation = "newlocation"; // act @@ -161,6 +173,7 @@ public void UpdateBuilding_WhenOnlyLocationIsProvided_ShouldUpdateBuildingLocati // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateBuilding_WhenOnlyBuildingNameIsProvided_ShouldUpdateBuildingName() { @@ -172,7 +185,8 @@ public void UpdateBuilding_WhenOnlyBuildingNameIsProvided_ShouldUpdateBuildingNa var location = "testlocation"; var buildingName = "testbuilding"; var company = new Company { CompanyId = companyId, CompanyName = "testcompany" }; - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = buildingName, Location = location }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = buildingName, Location = location }; context.Companies.Add(company); context.Buildings.Add(building); @@ -182,7 +196,7 @@ public void UpdateBuilding_WhenOnlyBuildingNameIsProvided_ShouldUpdateBuildingNa var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); var updatedBuildingName = "updatedBuildingName"; // act @@ -197,6 +211,7 @@ public void UpdateBuilding_WhenOnlyBuildingNameIsProvided_ShouldUpdateBuildingNa // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateBuilding_WhenNeitherLocationNorBuildingNameIsProvided_ShouldReturnBuildingId() { @@ -205,7 +220,8 @@ public void UpdateBuilding_WhenNeitherLocationNorBuildingNameIsProvided_ShouldRe var company = new Company { CompanyId = companyId, CompanyName = "testcompany" }; var buildingId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; context.Companies.Add(company); context.Buildings.Add(building); context.SaveChanges(); @@ -214,7 +230,7 @@ public void UpdateBuilding_WhenNeitherLocationNorBuildingNameIsProvided_ShouldRe var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act var updatedBuilding = resourceUsecases.UpdateBuilding(companyId, buildingId, null, null); @@ -225,6 +241,7 @@ public void UpdateBuilding_WhenNeitherLocationNorBuildingNameIsProvided_ShouldRe // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateBuilding_WhenLocationIsEmpty_ShouldThrowArgumentInvalidException() { @@ -233,7 +250,8 @@ public void UpdateBuilding_WhenLocationIsEmpty_ShouldThrowArgumentInvalidExcepti var company = new Company { CompanyId = companyId, CompanyName = "testcompany" }; var buildingId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; context.Companies.Add(company); context.Buildings.Add(building); context.SaveChanges(); @@ -242,16 +260,18 @@ public void UpdateBuilding_WhenLocationIsEmpty_ShouldThrowArgumentInvalidExcepti var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, "Building Name", "")); + var ex = Assert.Throws(() => + resourceUsecases.UpdateBuilding(companyId, buildingId, "Building Name", "")); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo("Location must not be empty")); + Assert.That(ex?.Message, Is.EqualTo("Location must not be empty")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateBuilding_WhenBuildingNameIsEmpty_ShouldThrowArgumentInvalidException() { @@ -260,7 +280,8 @@ public void UpdateBuilding_WhenBuildingNameIsEmpty_ShouldThrowArgumentInvalidExc var company = new Company { CompanyId = companyId, CompanyName = "testcompany" }; var buildingId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; context.Companies.Add(company); context.Buildings.Add(building); context.SaveChanges(); @@ -269,12 +290,13 @@ public void UpdateBuilding_WhenBuildingNameIsEmpty_ShouldThrowArgumentInvalidExc var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, "", "New York")); + var ex = Assert.Throws(() => + resourceUsecases.UpdateBuilding(companyId, buildingId, "", "New York")); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo("Building name must not be empty")); + Assert.That(ex?.Message, Is.EqualTo("Building name must not be empty")); // cleanup context.Database.EnsureDeleted(); @@ -288,7 +310,8 @@ public void UpdateFloor_WhenFloorDoesNotExist_ShouldThrowEntitiesNotFoundExcepti var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; context.Buildings.Add(building); context.SaveChanges(); @@ -296,12 +319,13 @@ public void UpdateFloor_WhenFloorDoesNotExist_ShouldThrowEntitiesNotFoundExcepti var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, "Floor Name", buildingId)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateFloor(companyId, floorId, "Floor Name", buildingId)); Assert.NotNull(ex); - Assert.That($"There is no floor with id '{floorId}'" == ex.Message); + Assert.That($"There is no floor with id '{floorId}'" == ex?.Message); // cleanup context.Database.EnsureDeleted(); @@ -315,7 +339,8 @@ public void UpdateFloor_WhenCompanyIdDoesNotMatchFloor_ShouldThrowInsufficientPe var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = Guid.NewGuid(), BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = Guid.NewGuid(), BuildingName = "testname", Location = "testlocation" }; context.Buildings.Add(building); var floorName = "testfloor"; var floor = new Floor { FloorId = floorId, FloorName = floorName, BuildingId = buildingId, Building = building }; @@ -326,12 +351,13 @@ public void UpdateFloor_WhenCompanyIdDoesNotMatchFloor_ShouldThrowInsufficientPe var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, "Floor Name", null)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateFloor(companyId, floorId, "Floor Name", null)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"Your company has no access to administrate floor '{floorName}'")); + Assert.That(ex?.Message, Is.EqualTo($"Your company has no access to administrate floor '{floorName}'")); // cleanup context.Database.EnsureDeleted(); @@ -345,7 +371,8 @@ public void UpdateFloor_WhenFloorNameIsEmpty_ShouldThrowArgumentInvalidException var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; context.Buildings.Add(building); var floor = new Floor { FloorId = floorId, FloorName = "testfloor", BuildingId = buildingId, Building = building }; context.Floors.Add(floor); @@ -355,12 +382,12 @@ public void UpdateFloor_WhenFloorNameIsEmpty_ShouldThrowArgumentInvalidException var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, "", null)); Assert.NotNull(ex); - Assert.That($"Floor name must not be empty" == ex.Message); + Assert.That("Floor name must not be empty" == ex?.Message); // cleanup context.Database.EnsureDeleted(); @@ -374,7 +401,8 @@ public void UpdateFloor_WhenBuildingIdDoesNotExist_ShouldThrowEntityNotFoundExce var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; context.Buildings.Add(building); var floor = new Floor { FloorId = floorId, FloorName = "testfloor", BuildingId = buildingId, Building = building }; context.Floors.Add(floor); @@ -385,12 +413,13 @@ public void UpdateFloor_WhenBuildingIdDoesNotExist_ShouldThrowEntityNotFoundExce var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, "testname", buildingIdNotExisting)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateFloor(companyId, floorId, "testname", buildingIdNotExisting)); Assert.NotNull(ex); - Assert.That($"Building does not exist with id '{buildingIdNotExisting}'" == ex.Message); + Assert.That($"Building does not exist with id '{buildingIdNotExisting}'" == ex?.Message); // cleanup context.Database.EnsureDeleted(); @@ -404,7 +433,8 @@ public void UpdateFloor_WhenCompanyIdDoesNotMatchBuilding_ShouldThrowInsufficien var buildingId = Guid.NewGuid(); var floorId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = Guid.NewGuid(), BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = Guid.NewGuid(), BuildingName = "testname", Location = "testlocation" }; var floorName = "testname"; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = floorName }; context.Buildings.Add(building); @@ -415,12 +445,13 @@ public void UpdateFloor_WhenCompanyIdDoesNotMatchBuilding_ShouldThrowInsufficien var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, "new name", null)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateFloor(companyId, floorId, "new name", null)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"Your company has no access to administrate floor '{floorName}'")); + Assert.That(ex?.Message, Is.EqualTo($"Your company has no access to administrate floor '{floorName}'")); // cleanup context.Database.EnsureDeleted(); @@ -436,7 +467,8 @@ public void UpdateFloor_WhenUpdatedBuildingBelongsToDifferentCompany_ShouldThrow var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, FloorName = "testfloor", BuildingId = buildingId, Building = building }; context.Buildings.Add(building); context.Floors.Add(floor); @@ -444,7 +476,10 @@ public void UpdateFloor_WhenUpdatedBuildingBelongsToDifferentCompany_ShouldThrow var anotherCompanyId = Guid.NewGuid(); var building2Id = Guid.NewGuid(); var building2Name = "testbuilding2"; - var building2 = new Building { BuildingId = building2Id, CompanyId = anotherCompanyId, BuildingName = building2Name, Location = "testlocation" }; + var building2 = new Building + { + BuildingId = building2Id, CompanyId = anotherCompanyId, BuildingName = building2Name, Location = "testlocation" + }; context.Buildings.Add(building2); context.SaveChanges(); @@ -452,12 +487,13 @@ public void UpdateFloor_WhenUpdatedBuildingBelongsToDifferentCompany_ShouldThrow var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, null, building2Id)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateFloor(companyId, floorId, null, building2Id)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"Your company has no access to move a floor to building '{building2Name}'")); + Assert.That(ex?.Message, Is.EqualTo($"Your company has no access to move a floor to building '{building2Name}'")); // cleanup context.Database.EnsureDeleted(); @@ -474,14 +510,18 @@ public void UpdateFloor_WhenUpdatedBuildingNameAlreadyExists_ShouldThrowArgument var buildingId = Guid.NewGuid(); var floorName = "testfloor"; var buildingName = "testname"; - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = buildingName, Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = buildingName, Location = "testlocation" }; var floor = new Floor { FloorId = floorId, FloorName = floorName, BuildingId = buildingId, Building = building }; context.Buildings.Add(building); context.Floors.Add(floor); var anotherCompanyId = Guid.NewGuid(); var building2Id = Guid.NewGuid(); - var building2 = new Building { BuildingId = building2Id, CompanyId = anotherCompanyId, BuildingName = "testbuilding2", Location = "testlocation" }; + var building2 = new Building + { + BuildingId = building2Id, CompanyId = anotherCompanyId, BuildingName = "testbuilding2", Location = "testlocation" + }; context.Buildings.Add(building2); context.SaveChanges(); @@ -489,12 +529,13 @@ public void UpdateFloor_WhenUpdatedBuildingNameAlreadyExists_ShouldThrowArgument var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, floorName, null)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateFloor(companyId, floorId, floorName, null)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"There is already a floor named '{floorName}' in building '{buildingName}'")); + Assert.That(ex?.Message, Is.EqualTo($"There is already a floor named '{floorName}' in building '{buildingName}'")); // cleanup context.Database.EnsureDeleted(); @@ -508,10 +549,12 @@ public void UpdateFloor_WhenAllInputIsValid_ShouldUpdateFloorAndReturnFloorId() var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; context.Buildings.Add(building); var building2Id = Guid.NewGuid(); - var building2 = new Building { BuildingId = building2Id, CompanyId = companyId, BuildingName = "testbuilding2", Location = "testlocation" }; + var building2 = new Building + { BuildingId = building2Id, CompanyId = companyId, BuildingName = "testbuilding2", Location = "testlocation" }; context.Buildings.Add(building2); var floor = new Floor { FloorId = floorId, FloorName = "testfloor", BuildingId = buildingId, Building = building }; context.Floors.Add(floor); @@ -521,7 +564,7 @@ public void UpdateFloor_WhenAllInputIsValid_ShouldUpdateFloorAndReturnFloorId() var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); var newFloorName = "new name"; // act @@ -548,17 +591,18 @@ public void UpdateFloor_WhenFloorNameAlreadyExistsInUpdatedBuilding_ShouldThrowA var floorId = Guid.NewGuid(); var floorName = "testfloor"; - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, FloorName = floorName, BuildingId = buildingId }; context.Buildings.Add(building); context.Floors.Add(floor); - var company2Id = Guid.NewGuid(); var building2Id = Guid.NewGuid(); var floor2Id = Guid.NewGuid(); var building2Name = "testbuilding2"; - var building2 = new Building { BuildingId = building2Id, CompanyId = companyId, BuildingName = building2Name, Location = "testlocation" }; + var building2 = new Building + { BuildingId = building2Id, CompanyId = companyId, BuildingName = building2Name, Location = "testlocation" }; var floor2 = new Floor { FloorId = floor2Id, FloorName = floorName, BuildingId = building2Id }; context.Buildings.Add(building2); @@ -570,12 +614,15 @@ public void UpdateFloor_WhenFloorNameAlreadyExistsInUpdatedBuilding_ShouldThrowA var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, floorName, building2Id)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateFloor(companyId, floorId, floorName, building2Id)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"You cant move floor '{floorName}' to building '{building2Name}'. In building '{building2Name}' already exists a floor called '{floorName}'")); + Assert.That(ex?.Message, + Is.EqualTo( + $"You cant move floor '{floorName}' to building '{building2Name}'. In building '{building2Name}' already exists a floor called '{floorName}'")); // cleanup context.Database.EnsureDeleted(); @@ -589,7 +636,8 @@ public void UpdateFloor_WhenOnlyFloorNameIsProvided_ShouldUpdateFloorNameAndRetu var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; context.Buildings.Add(building); var floorName = "testfloor"; var floor = new Floor { FloorId = floorId, FloorName = floorName, BuildingId = buildingId, Building = building }; @@ -600,7 +648,7 @@ public void UpdateFloor_WhenOnlyFloorNameIsProvided_ShouldUpdateFloorNameAndRetu var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); var newFloorName = "newFloorName"; // act @@ -624,10 +672,12 @@ public void UpdateFloor_WhenOnlyBuildingIdIsProvided_ShouldUpdateFloorBuildingAn var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; context.Buildings.Add(building); var building2Id = Guid.NewGuid(); - var building2 = new Building { BuildingId = building2Id, CompanyId = companyId, BuildingName = "testbuilding2", Location = "testlocation" }; + var building2 = new Building + { BuildingId = building2Id, CompanyId = companyId, BuildingName = "testbuilding2", Location = "testlocation" }; context.Buildings.Add(building2); var floorName = "testfloor"; var floor = new Floor { FloorId = floorId, FloorName = floorName, BuildingId = buildingId, Building = building }; @@ -638,7 +688,7 @@ public void UpdateFloor_WhenOnlyBuildingIdIsProvided_ShouldUpdateFloorBuildingAn var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act var updatedFloor = resourceUsecases.UpdateFloor(companyId, floorId, null, building2Id); @@ -661,7 +711,8 @@ public void UpdateFloor_WhenNeitherFloorNameNorBuildingIdIsProvided_ShouldReturn var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; context.Buildings.Add(building); var floorName = "testfloor"; var floor = new Floor { FloorId = floorId, FloorName = floorName, BuildingId = buildingId, Building = building }; @@ -672,7 +723,7 @@ public void UpdateFloor_WhenNeitherFloorNameNorBuildingIdIsProvided_ShouldReturn var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act var updatedFloor = resourceUsecases.UpdateFloor(companyId, floorId, null, null); @@ -697,7 +748,8 @@ public void UpdateRoom_WhenRoomDoesNotExist_ShouldThrowEntityNotFoundException() var buildingId = Guid.NewGuid(); var floorId = Guid.NewGuid(); var roomId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var roomName = "testroom"; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = roomName }; @@ -708,9 +760,11 @@ public void UpdateRoom_WhenRoomDoesNotExist_ShouldThrowEntityNotFoundException() var anotherBuildingId = Guid.NewGuid(); var anotherFloorId = Guid.NewGuid(); var anotherRoomId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" + }; var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "testfloor" }; - var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = roomName }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); context.SaveChanges(); @@ -719,12 +773,13 @@ public void UpdateRoom_WhenRoomDoesNotExist_ShouldThrowEntityNotFoundException() var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateRoom(companyId, anotherRoomId, "Room Name", floorId)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateRoom(companyId, anotherRoomId, "Room Name", floorId)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"There is no room with id '{anotherRoomId}'")); + Assert.That(ex?.Message, Is.EqualTo($"There is no room with id '{anotherRoomId}'")); // cleanup context.Database.EnsureDeleted(); @@ -740,7 +795,8 @@ public void UpdateRoom_WhenCompanyHasInsufficientPermission_ShouldThrowInsuffici var buildingId = Guid.NewGuid(); var roomId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var roomName = "testroom"; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = roomName }; @@ -753,12 +809,13 @@ public void UpdateRoom_WhenCompanyHasInsufficientPermission_ShouldThrowInsuffici var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateRoom(anotherCompanyId, roomId, "Room Name", floorId)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateRoom(anotherCompanyId, roomId, "Room Name", floorId)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"Your company has no access to administrate room '{roomName}'")); + Assert.That(ex?.Message, Is.EqualTo($"Your company has no access to administrate room '{roomName}'")); // cleanup context.Database.EnsureDeleted(); @@ -769,12 +826,12 @@ public void UpdateRoom_WhenRoomNameIsEmpty_ShouldThrowArgumentInvalidException() { // setup var companyId = Guid.NewGuid(); - var anotherCompanyId = Guid.NewGuid(); var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var roomId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; context.Buildings.Add(building); @@ -786,12 +843,12 @@ public void UpdateRoom_WhenRoomNameIsEmpty_ShouldThrowArgumentInvalidException() var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act and assert var ex = Assert.Throws(() => resourceUsecases.UpdateRoom(companyId, roomId, "", floorId)); Assert.NotNull(ex); - Assert.That($"Room name must not be empty" == ex.Message); + Assert.That("Room name must not be empty" == ex?.Message); // cleanup context.Database.EnsureDeleted(); @@ -802,13 +859,13 @@ public void UpdateRoom_WhenUpdatedFloorDoesNotExist_ShouldThrowEntityNotFoundExc { // setup var companyId = Guid.NewGuid(); - var anotherCompanyId = Guid.NewGuid(); var floorId = Guid.NewGuid(); var anotherFloorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var roomId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var roomName = "testroom"; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = roomName }; @@ -820,16 +877,18 @@ public void UpdateRoom_WhenUpdatedFloorDoesNotExist_ShouldThrowEntityNotFoundExc // arrange var logger = new Mock>(); var userUsecases = new Mock(); - var resourceUsecases = new ResourceUsecases(logger.Object, context, userUsecases.Object); + var resourceUsecases = new ResourceUsecases(logger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateRoom(companyId, roomId, roomName, anotherFloorId)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateRoom(companyId, roomId, roomName, anotherFloorId)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"Floor does not exist with id '{anotherFloorId}'")); + Assert.That(ex?.Message, Is.EqualTo($"Floor does not exist with id '{anotherFloorId}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateRoom_WhenCompanyHasInsufficientPermissionToChangeFloor_ShouldThrowInsufficientPermissionException() { @@ -842,11 +901,17 @@ public void UpdateRoom_WhenCompanyHasInsufficientPermissionToChangeFloor_ShouldT var anotherBuildingId = Guid.NewGuid(); var roomId = Guid.NewGuid(); var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", + Location = "testlocation" + }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var anotherFloorName = "anotherTestFloor"; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = anotherFloorName }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = anotherFloorName }; var roomName = "testroom"; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = roomName }; context.Buildings.Add(building); @@ -859,12 +924,13 @@ public void UpdateRoom_WhenCompanyHasInsufficientPermissionToChangeFloor_ShouldT //arrange var logger = new Mock>(); var userUsecases = new Mock(); - var usecases = new ResourceUsecases(logger.Object, context, userUsecases.Object); + var usecases = new ResourceUsecases(logger.Object, context); // act+assert - var ex = Assert.Throws(() => usecases.UpdateRoom(companyId, roomId, "New Room", anotherFloorId)); + var ex = Assert.Throws(() => + usecases.UpdateRoom(companyId, roomId, "New Room", anotherFloorId)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"Your company has no access to move a room to floor '{anotherFloorName}'")); + Assert.That(ex?.Message, Is.EqualTo($"Your company has no access to move a room to floor '{anotherFloorName}'")); // cleanup context.Database.EnsureDeleted(); @@ -880,7 +946,8 @@ public void UpdateRoom_WhenProvidedRoomNameAndFloor_ShouldUpdateBothNameAndFloor var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var roomId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var roomName = "testroom"; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = roomName }; @@ -890,7 +957,10 @@ public void UpdateRoom_WhenProvidedRoomNameAndFloor_ShouldUpdateBothNameAndFloor var anotherFloorId = Guid.NewGuid(); var anotherBuildingId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" + }; var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "testfloor" }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -899,7 +969,7 @@ public void UpdateRoom_WhenProvidedRoomNameAndFloor_ShouldUpdateBothNameAndFloor // arrange var logger = new Mock>(); var userUsecases = new Mock(); - var usecases = new ResourceUsecases(logger.Object, context, userUsecases.Object); + var usecases = new ResourceUsecases(logger.Object, context); var updatedRoomName = "updatedRoomName"; // act @@ -924,7 +994,8 @@ public void UpdateRoom_WhenUpdatingOnlyRoomName_ShouldUpdateNameOnly() var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var roomId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var roomName = "testroom"; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = roomName }; @@ -936,7 +1007,7 @@ public void UpdateRoom_WhenUpdatingOnlyRoomName_ShouldUpdateNameOnly() // arrange var logger = new Mock>(); var userUsecases = new Mock(); - var usecases = new ResourceUsecases(logger.Object, context, userUsecases.Object); + var usecases = new ResourceUsecases(logger.Object, context); var updatedRoomName = "updatedRoomName"; // act @@ -950,6 +1021,7 @@ public void UpdateRoom_WhenUpdatingOnlyRoomName_ShouldUpdateNameOnly() // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateRoom_WhenUpdatingOnlyRoomNameAndRoomNameAlreadyExists_ShouldThrowArgumentInvalidException() { @@ -960,7 +1032,8 @@ public void UpdateRoom_WhenUpdatingOnlyRoomNameAndRoomNameAlreadyExists_ShouldTh var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var roomId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floorName = "testfloor"; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = floorName }; var roomName = "testroom"; @@ -973,12 +1046,12 @@ public void UpdateRoom_WhenUpdatingOnlyRoomNameAndRoomNameAlreadyExists_ShouldTh // arrange var logger = new Mock>(); var userUsecases = new Mock(); - var usecases = new ResourceUsecases(logger.Object, context, userUsecases.Object); + var usecases = new ResourceUsecases(logger.Object, context); // act+assert var ex = Assert.Throws(() => usecases.UpdateRoom(companyId, roomId, roomName, null)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"There is already a room named '{roomName}' in floor '{floorName}'")); + Assert.That(ex?.Message, Is.EqualTo($"There is already a room named '{roomName}' in floor '{floorName}'")); // cleanup context.Database.EnsureDeleted(); @@ -995,7 +1068,8 @@ public void UpdateRoom_WhenUpdatingRoomNameAndFloorAndRoomNameAlreadyExists_Shou var buildingId = Guid.NewGuid(); var roomId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var roomName = "testroom"; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = roomName }; @@ -1008,9 +1082,13 @@ public void UpdateRoom_WhenUpdatingRoomNameAndFloorAndRoomNameAlreadyExists_Shou var anotherBuildingId = Guid.NewGuid(); var anotherRoomId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" + }; var anotherFloorName = "testfloor"; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = anotherFloorName }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = anotherFloorName }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = roomName }; context.Buildings.Add(anotherBuilding); @@ -1022,16 +1100,20 @@ public void UpdateRoom_WhenUpdatingRoomNameAndFloorAndRoomNameAlreadyExists_Shou // arrange var logger = new Mock>(); var userUsecases = new Mock(); - var usecases = new ResourceUsecases(logger.Object, context, userUsecases.Object); + var usecases = new ResourceUsecases(logger.Object, context); // act+assert - var ex = Assert.Throws(() => usecases.UpdateRoom(companyId, roomId, roomName, anotherFloorId)); + var ex = Assert.Throws(() => + usecases.UpdateRoom(companyId, roomId, roomName, anotherFloorId)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"You cant move room '{roomName}' to floor '{anotherFloorName}'. In floor '{anotherFloorName}' already exists a room called '{roomName}'")); + Assert.That(ex?.Message, + Is.EqualTo( + $"You cant move room '{roomName}' to floor '{anotherFloorName}'. In floor '{anotherFloorName}' already exists a room called '{roomName}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateRoom_WhenUpdatingOnlyFloor_ShouldUpdateFloorOnly() { @@ -1042,7 +1124,8 @@ public void UpdateRoom_WhenUpdatingOnlyFloor_ShouldUpdateFloorOnly() var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var roomId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var roomName = "testroom"; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = roomName }; @@ -1052,7 +1135,10 @@ public void UpdateRoom_WhenUpdatingOnlyFloor_ShouldUpdateFloorOnly() var anotherFloorId = Guid.NewGuid(); var anotherBuildingId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" + }; var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "testfloor" }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -1061,7 +1147,7 @@ public void UpdateRoom_WhenUpdatingOnlyFloor_ShouldUpdateFloorOnly() // arrange var logger = new Mock>(); var userUsecases = new Mock(); - var usecases = new ResourceUsecases(logger.Object, context, userUsecases.Object); + var usecases = new ResourceUsecases(logger.Object, context); // act var updatedRoom = usecases.UpdateRoom(companyId, roomId, null, anotherFloorId); @@ -1085,7 +1171,8 @@ public void UpdateRoom_WhenUpdatingNothing_ShouldUpdateNothing() var floorId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); var roomId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var roomName = "testroom"; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = roomName }; @@ -1098,7 +1185,7 @@ public void UpdateRoom_WhenUpdatingNothing_ShouldUpdateNothing() // arrange var logger = new Mock>(); var userUsecases = new Mock(); - var usecases = new ResourceUsecases(logger.Object, context, userUsecases.Object); + var usecases = new ResourceUsecases(logger.Object, context); // act var updatedRoom = usecases.UpdateRoom(companyId, roomId, null, null); @@ -1118,8 +1205,6 @@ public void UpdateDesk_WhenDeskDoesNotExist_ShouldThrowEntityNotFoundException() // setup var companyId = Guid.NewGuid(); var floorId = Guid.NewGuid(); - var bui = Guid.NewGuid(); - var roomId = Guid.NewGuid(); var floor = new Floor { FloorId = floorId, FloorName = "testfloor", BuildingId = Guid.NewGuid() }; var context = new DataContext(); context.Floors.Add(floor); @@ -1129,17 +1214,19 @@ public void UpdateDesk_WhenDeskDoesNotExist_ShouldThrowEntityNotFoundException() var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); var unknownDeskId = Guid.NewGuid(); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateDesk(companyId, unknownDeskId, null, null, null)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateDesk(companyId, unknownDeskId, null, null, null)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"There is no desk with id '{unknownDeskId}'")); + Assert.That(ex?.Message, Is.EqualTo($"There is no desk with id '{unknownDeskId}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDesk_WhenCompanyHasInsufficientPermission_ShouldThrowInsufficientPermissionException() { @@ -1153,7 +1240,8 @@ public void UpdateDesk_WhenCompanyHasInsufficientPermission_ShouldThrowInsuffici var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -1174,11 +1262,18 @@ public void UpdateDesk_WhenCompanyHasInsufficientPermission_ShouldThrowInsuffici var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", + Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; - var anotherDeskType = new DeskType { CompanyId = anotherCompanyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = anotherCompanyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -1192,16 +1287,18 @@ public void UpdateDesk_WhenCompanyHasInsufficientPermission_ShouldThrowInsuffici var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateDesk(companyId, anotherDeskId, null, null, null)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateDesk(companyId, anotherDeskId, null, null, null)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"Your company has no access to administrate desk '{deskName}'")); + Assert.That(ex?.Message, Is.EqualTo($"Your company has no access to administrate desk '{deskName}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDesk_WhenDeskNameIsEmpty_ShouldThrowArgumentInvalidException() { @@ -1215,7 +1312,8 @@ public void UpdateDesk_WhenDeskNameIsEmpty_ShouldThrowArgumentInvalidException() var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -1236,11 +1334,18 @@ public void UpdateDesk_WhenDeskNameIsEmpty_ShouldThrowArgumentInvalidException() var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", + Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; - var anotherDeskType = new DeskType { CompanyId = anotherCompanyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = anotherCompanyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -1254,16 +1359,18 @@ public void UpdateDesk_WhenDeskNameIsEmpty_ShouldThrowArgumentInvalidException() var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateDesk(companyId, deskId, "", null, null)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateDesk(companyId, deskId, "", null, null)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"Desk name must not be empty")); + Assert.That(ex?.Message, Is.EqualTo("Desk name must not be empty")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDesk_WhenRoomDoesNotExist_ShouldThrowEntityNotFoundException() { @@ -1277,7 +1384,8 @@ public void UpdateDesk_WhenRoomDoesNotExist_ShouldThrowEntityNotFoundException() var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -1298,11 +1406,18 @@ public void UpdateDesk_WhenRoomDoesNotExist_ShouldThrowEntityNotFoundException() var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", + Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; - var anotherDeskType = new DeskType { CompanyId = anotherCompanyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = anotherCompanyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -1316,17 +1431,19 @@ public void UpdateDesk_WhenRoomDoesNotExist_ShouldThrowEntityNotFoundException() var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); var unknownRoomId = Guid.NewGuid(); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateDesk(companyId, deskId, null, unknownRoomId, null)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateDesk(companyId, deskId, null, unknownRoomId, null)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"Room does not exist with id '{unknownRoomId}'")); + Assert.That(ex?.Message, Is.EqualTo($"Room does not exist with id '{unknownRoomId}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDesk_WhenCompanyHasInsufficientPermissionToChangeRoom_ShouldThrowInsufficientPermissionException() { @@ -1340,7 +1457,8 @@ public void UpdateDesk_WhenCompanyHasInsufficientPermissionToChangeRoom_ShouldTh var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -1361,12 +1479,19 @@ public void UpdateDesk_WhenCompanyHasInsufficientPermissionToChangeRoom_ShouldTh var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", + Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoomName = "anothertestroom"; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = anotherRoomName }; - var anotherDeskType = new DeskType { CompanyId = anotherCompanyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = anotherCompanyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -1380,17 +1505,18 @@ public void UpdateDesk_WhenCompanyHasInsufficientPermissionToChangeRoom_ShouldTh var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - var unknownRoomId = Guid.NewGuid(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateDesk(companyId, deskId, null, anotherRoomId, null)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateDesk(companyId, deskId, null, anotherRoomId, null)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"Your company has no access to add a desk to room '{anotherRoomName}'")); + Assert.That(ex?.Message, Is.EqualTo($"Your company has no access to add a desk to room '{anotherRoomName}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDesk_WhenDeskTypeDoesNotExist_ShouldThrowEntityNotFoundException() { @@ -1404,7 +1530,8 @@ public void UpdateDesk_WhenDeskTypeDoesNotExist_ShouldThrowEntityNotFoundExcepti var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -1425,11 +1552,18 @@ public void UpdateDesk_WhenDeskTypeDoesNotExist_ShouldThrowEntityNotFoundExcepti var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", + Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; - var anotherDeskType = new DeskType { CompanyId = anotherCompanyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = anotherCompanyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -1443,19 +1577,22 @@ public void UpdateDesk_WhenDeskTypeDoesNotExist_ShouldThrowEntityNotFoundExcepti var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); var unknownDeskTypeId = Guid.NewGuid(); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateDesk(companyId, deskId, null, null, unknownDeskTypeId)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateDesk(companyId, deskId, null, null, unknownDeskTypeId)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"DeskType does not exist with id '{unknownDeskTypeId}'")); + Assert.That(ex?.Message, Is.EqualTo($"DeskType does not exist with id '{unknownDeskTypeId}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] - public void UpdateDesk_WhenCompanyHasInsufficientPermissionToChangeDeskType_ShouldThrowInsufficientPermissionException() + public void + UpdateDesk_WhenCompanyHasInsufficientPermissionToChangeDeskType_ShouldThrowInsufficientPermissionException() { // setup var context = new DataContext(); @@ -1467,7 +1604,8 @@ public void UpdateDesk_WhenCompanyHasInsufficientPermissionToChangeDeskType_Shou var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -1488,12 +1626,19 @@ public void UpdateDesk_WhenCompanyHasInsufficientPermissionToChangeDeskType_Shou var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", + Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; var anotherDeskTypeName = "anotherdesktype"; - var anotherDeskType = new DeskType { CompanyId = anotherCompanyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = anotherDeskTypeName }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = anotherCompanyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = anotherDeskTypeName }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -1507,16 +1652,18 @@ public void UpdateDesk_WhenCompanyHasInsufficientPermissionToChangeDeskType_Shou var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateDesk(companyId, deskId, null, null, anotherDeskTypeId)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateDesk(companyId, deskId, null, null, anotherDeskTypeId)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"Your company has no access to desk type '{anotherDeskTypeName}'")); + Assert.That(ex?.Message, Is.EqualTo($"Your company has no access to desk type '{anotherDeskTypeName}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDesk_WhenUpdatingDeskNameAndRoomAndDeskType_ShouldUpdateDeskNameAndRoomAndDeskType() { @@ -1530,7 +1677,8 @@ public void UpdateDesk_WhenUpdatingDeskNameAndRoomAndDeskType_ShouldUpdateDeskNa var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -1543,19 +1691,23 @@ public void UpdateDesk_WhenUpdatingDeskNameAndRoomAndDeskType_ShouldUpdateDeskNa context.DeskTypes.Add(deskType); context.Desks.Add(desk); - - var anotherCompanyId = Guid.NewGuid(); var anotherBuildingId = Guid.NewGuid(); var anotherFloorId = Guid.NewGuid(); var anotherRoomId = Guid.NewGuid(); var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; - var anotherDeskType = new DeskType { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -1569,7 +1721,7 @@ public void UpdateDesk_WhenUpdatingDeskNameAndRoomAndDeskType_ShouldUpdateDeskNa var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); var updatedDeskName = "updatedDeskName"; // act @@ -1584,6 +1736,7 @@ public void UpdateDesk_WhenUpdatingDeskNameAndRoomAndDeskType_ShouldUpdateDeskNa // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDesk_WhenUpdatingOnlyDeskNameAndNameDoesNotExists_ShouldOnlyUpdateName() { @@ -1597,7 +1750,8 @@ public void UpdateDesk_WhenUpdatingOnlyDeskNameAndNameDoesNotExists_ShouldOnlyUp var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -1610,19 +1764,23 @@ public void UpdateDesk_WhenUpdatingOnlyDeskNameAndNameDoesNotExists_ShouldOnlyUp context.DeskTypes.Add(deskType); context.Desks.Add(desk); - - var anotherCompanyId = Guid.NewGuid(); var anotherBuildingId = Guid.NewGuid(); var anotherFloorId = Guid.NewGuid(); var anotherRoomId = Guid.NewGuid(); var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; - var anotherDeskType = new DeskType { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -1636,7 +1794,7 @@ public void UpdateDesk_WhenUpdatingOnlyDeskNameAndNameDoesNotExists_ShouldOnlyUp var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); var updatedDeskName = "updatedDeskName"; // act @@ -1651,6 +1809,7 @@ public void UpdateDesk_WhenUpdatingOnlyDeskNameAndNameDoesNotExists_ShouldOnlyUp // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDesk_WhenUpdatingOnlyDeskNameAndNameDoesAlreadyExists_ShouldThrowArgumentInvalidException() { @@ -1664,7 +1823,8 @@ public void UpdateDesk_WhenUpdatingOnlyDeskNameAndNameDoesAlreadyExists_ShouldTh var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var roomName = "testroom"; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = roomName }; @@ -1679,19 +1839,24 @@ public void UpdateDesk_WhenUpdatingOnlyDeskNameAndNameDoesAlreadyExists_ShouldTh context.Desks.Add(desk); - var anotherCompanyId = Guid.NewGuid(); var anotherBuildingId = Guid.NewGuid(); var anotherFloorId = Guid.NewGuid(); var anotherRoomId = Guid.NewGuid(); var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; - var anotherDeskType = new DeskType { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; + var anotherDeskType = new DeskType + { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; var updatedDeskName = "updatedDeskName"; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = updatedDeskName, DeskTypeId = anotherDeskTypeId, RoomId = roomId }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = updatedDeskName, DeskTypeId = anotherDeskTypeId, RoomId = roomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -1705,16 +1870,18 @@ public void UpdateDesk_WhenUpdatingOnlyDeskNameAndNameDoesAlreadyExists_ShouldTh var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateDesk(companyId, deskId, updatedDeskName, null, null)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateDesk(companyId, deskId, updatedDeskName, null, null)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"There is already a desk named '{updatedDeskName}' in room '{roomName}'")); + Assert.That(ex?.Message, Is.EqualTo($"There is already a desk named '{updatedDeskName}' in room '{roomName}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDesk_WhenUpdatingOnlyRoomAndDeskNameInOtherRoomAlreadyExists_ShouldThrowArgumentInvalidException() { @@ -1728,7 +1895,8 @@ public void UpdateDesk_WhenUpdatingOnlyRoomAndDeskNameInOtherRoomAlreadyExists_S var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -1741,20 +1909,24 @@ public void UpdateDesk_WhenUpdatingOnlyRoomAndDeskNameInOtherRoomAlreadyExists_S context.DeskTypes.Add(deskType); context.Desks.Add(desk); - - var anotherCompanyId = Guid.NewGuid(); var anotherBuildingId = Guid.NewGuid(); var anotherFloorId = Guid.NewGuid(); var anotherRoomId = Guid.NewGuid(); var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoomName = "anothertestroom"; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = anotherRoomName }; - var anotherDeskType = new DeskType { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -1768,16 +1940,20 @@ public void UpdateDesk_WhenUpdatingOnlyRoomAndDeskNameInOtherRoomAlreadyExists_S var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateDesk(companyId, deskId, null, anotherRoomId, null)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateDesk(companyId, deskId, null, anotherRoomId, null)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"You cant move desk '{deskName}' to room '{anotherRoomName}'. In room '{anotherRoomName}' already exists a desk called '{deskName}'")); + Assert.That(ex?.Message, + Is.EqualTo( + $"You cant move desk '{deskName}' to room '{anotherRoomName}'. In room '{anotherRoomName}' already exists a desk called '{deskName}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDesk_WhenUpdatingOnlyRoomAndDeskNameInOtherRoomDoesNotExists_ShouldUpdateRoomName() { @@ -1791,7 +1967,8 @@ public void UpdateDesk_WhenUpdatingOnlyRoomAndDeskNameInOtherRoomDoesNotExists_S var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -1804,19 +1981,23 @@ public void UpdateDesk_WhenUpdatingOnlyRoomAndDeskNameInOtherRoomDoesNotExists_S context.DeskTypes.Add(deskType); context.Desks.Add(desk); - - var anotherCompanyId = Guid.NewGuid(); var anotherBuildingId = Guid.NewGuid(); var anotherFloorId = Guid.NewGuid(); var anotherRoomId = Guid.NewGuid(); var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; - var anotherDeskType = new DeskType { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = "anotherDeskName", DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = "anotherDeskName", DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -1830,7 +2011,7 @@ public void UpdateDesk_WhenUpdatingOnlyRoomAndDeskNameInOtherRoomDoesNotExists_S var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act var updatedDesk = resourceUsecases.UpdateDesk(companyId, deskId, null, anotherRoomId, null); @@ -1844,6 +2025,7 @@ public void UpdateDesk_WhenUpdatingOnlyRoomAndDeskNameInOtherRoomDoesNotExists_S // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDesk_WhenUpdatingOnlyDeskType_ShouldOnlyUpdateDeskType() { @@ -1857,7 +2039,8 @@ public void UpdateDesk_WhenUpdatingOnlyDeskType_ShouldOnlyUpdateDeskType() var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -1870,19 +2053,23 @@ public void UpdateDesk_WhenUpdatingOnlyDeskType_ShouldOnlyUpdateDeskType() context.DeskTypes.Add(deskType); context.Desks.Add(desk); - - var anotherCompanyId = Guid.NewGuid(); var anotherBuildingId = Guid.NewGuid(); var anotherFloorId = Guid.NewGuid(); var anotherRoomId = Guid.NewGuid(); var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; - var anotherDeskType = new DeskType { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -1896,7 +2083,7 @@ public void UpdateDesk_WhenUpdatingOnlyDeskType_ShouldOnlyUpdateDeskType() var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act var updatedDesk = resourceUsecases.UpdateDesk(companyId, deskId, null, null, anotherDeskTypeId); @@ -1910,6 +2097,7 @@ public void UpdateDesk_WhenUpdatingOnlyDeskType_ShouldOnlyUpdateDeskType() // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDesk_WhenUpdatingNothing_ShouldThrowArgumentInvalidException() { @@ -1923,7 +2111,8 @@ public void UpdateDesk_WhenUpdatingNothing_ShouldThrowArgumentInvalidException() var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -1936,19 +2125,23 @@ public void UpdateDesk_WhenUpdatingNothing_ShouldThrowArgumentInvalidException() context.DeskTypes.Add(deskType); context.Desks.Add(desk); - - var anotherCompanyId = Guid.NewGuid(); var anotherBuildingId = Guid.NewGuid(); var anotherFloorId = Guid.NewGuid(); var anotherRoomId = Guid.NewGuid(); var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = companyId, BuildingName = "anothertestname", Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; - var anotherDeskType = new DeskType { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -1962,7 +2155,7 @@ public void UpdateDesk_WhenUpdatingNothing_ShouldThrowArgumentInvalidException() var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act var updatedDesk = resourceUsecases.UpdateDesk(companyId, deskId, null, null, null); @@ -1976,14 +2169,13 @@ public void UpdateDesk_WhenUpdatingNothing_ShouldThrowArgumentInvalidException() // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDeskType_WhenDeskTypeDoesNotExist_ShouldThrowEntityNotFoundException() { // setup var companyId = Guid.NewGuid(); var floorId = Guid.NewGuid(); - var bui = Guid.NewGuid(); - var roomId = Guid.NewGuid(); var floor = new Floor { FloorId = floorId, FloorName = "testfloor", BuildingId = Guid.NewGuid() }; var context = new DataContext(); context.Floors.Add(floor); @@ -1993,17 +2185,19 @@ public void UpdateDeskType_WhenDeskTypeDoesNotExist_ShouldThrowEntityNotFoundExc var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); var unknownDeskTypeId = Guid.NewGuid(); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateDeskType(companyId, unknownDeskTypeId, null)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateDeskType(companyId, unknownDeskTypeId, null)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"There is no desk type with id '{unknownDeskTypeId}'")); + Assert.That(ex?.Message, Is.EqualTo($"There is no desk type with id '{unknownDeskTypeId}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDeskType_WhenDeskTypeDoesBelongToDifferentCompany_ShouldThrowInsufficientPermissionException() { @@ -2022,17 +2216,19 @@ public void UpdateDeskType_WhenDeskTypeDoesBelongToDifferentCompany_ShouldThrowI var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); var noPermissionCompanyId = Guid.NewGuid(); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateDeskType(noPermissionCompanyId, deskTypeId, null)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateDeskType(noPermissionCompanyId, deskTypeId, null)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"Your company has no access to administrate desk type '{deskTypeName}'")); + Assert.That(ex?.Message, Is.EqualTo($"Your company has no access to administrate desk type '{deskTypeName}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDeskType_WhenDeskTypeNameIsEmpty_ShouldThrowArgumentInvalidException() { @@ -2046,7 +2242,8 @@ public void UpdateDeskType_WhenDeskTypeNameIsEmpty_ShouldThrowArgumentInvalidExc var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -2067,11 +2264,18 @@ public void UpdateDeskType_WhenDeskTypeNameIsEmpty_ShouldThrowArgumentInvalidExc var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", + Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; - var anotherDeskType = new DeskType { CompanyId = anotherCompanyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = anotherCompanyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = "anotherdesktype" }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -2085,16 +2289,17 @@ public void UpdateDeskType_WhenDeskTypeNameIsEmpty_ShouldThrowArgumentInvalidExc var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert var ex = Assert.Throws(() => resourceUsecases.UpdateDeskType(companyId, deskTypeId, "")); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo("Desk type name must not be empty")); + Assert.That(ex?.Message, Is.EqualTo("Desk type name must not be empty")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDeskType_WhenDeskTypeNameIsTaken_ShouldThrowArgumentInvalidException() { @@ -2108,7 +2313,8 @@ public void UpdateDeskType_WhenDeskTypeNameIsTaken_ShouldThrowArgumentInvalidExc var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -2129,12 +2335,19 @@ public void UpdateDeskType_WhenDeskTypeNameIsTaken_ShouldThrowArgumentInvalidExc var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", + Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; var anotherDeskTypeName = "anotherdesktype"; - var anotherDeskType = new DeskType { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = anotherDeskTypeName }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = anotherDeskTypeName }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -2148,16 +2361,18 @@ public void UpdateDeskType_WhenDeskTypeNameIsTaken_ShouldThrowArgumentInvalidExc var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateDeskType(companyId, deskTypeId, anotherDeskTypeName)); + var ex = Assert.Throws(() => + resourceUsecases.UpdateDeskType(companyId, deskTypeId, anotherDeskTypeName)); Assert.NotNull(ex); - Assert.That(ex.Message, Is.EqualTo($"There is already a desktype named '{anotherDeskTypeName}'")); + Assert.That(ex?.Message, Is.EqualTo($"There is already a desktype named '{anotherDeskTypeName}'")); // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDeskType_WhenUpdatingDeskTypeName_ShouldUpdateName() { @@ -2171,7 +2386,8 @@ public void UpdateDeskType_WhenUpdatingDeskTypeName_ShouldUpdateName() var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -2192,12 +2408,19 @@ public void UpdateDeskType_WhenUpdatingDeskTypeName_ShouldUpdateName() var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", + Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; var anotherDeskTypeName = "anotherdesktype"; - var anotherDeskType = new DeskType { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = anotherDeskTypeName }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = anotherDeskTypeName }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -2211,7 +2434,7 @@ public void UpdateDeskType_WhenUpdatingDeskTypeName_ShouldUpdateName() var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); var deskTypeNameThatDoesNotExistYet = "deskNameThatDoesNotExistYet"; // act @@ -2224,6 +2447,7 @@ public void UpdateDeskType_WhenUpdatingDeskTypeName_ShouldUpdateName() // cleanup context.Database.EnsureDeleted(); } + [Test] public void UpdateDeskType_WhenUpdatingNothing_ShouldUpdateNothing() { @@ -2237,7 +2461,8 @@ public void UpdateDeskType_WhenUpdatingNothing_ShouldUpdateNothing() var deskId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var building = new Building + { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; var floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testfloor" }; var room = new Room { RoomId = roomId, FloorId = floorId, RoomName = "testroom" }; var deskType = new DeskType { CompanyId = companyId, DeskTypeId = deskTypeId, DeskTypeName = "testdesktype" }; @@ -2258,12 +2483,19 @@ public void UpdateDeskType_WhenUpdatingNothing_ShouldUpdateNothing() var anotherDeskId = Guid.NewGuid(); var anotherDeskTypeId = Guid.NewGuid(); - var anotherBuilding = new Building { BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", Location = "testlocation" }; - var anotherFloor = new Floor { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; + var anotherBuilding = new Building + { + BuildingId = anotherBuildingId, CompanyId = anotherCompanyId, BuildingName = "anothertestname", + Location = "testlocation" + }; + var anotherFloor = new Floor + { FloorId = anotherFloorId, BuildingId = anotherBuildingId, FloorName = "anothertestfloor" }; var anotherRoom = new Room { RoomId = anotherRoomId, FloorId = anotherFloorId, RoomName = "anothertestroom" }; var anotherDeskTypeName = "anotherdesktype"; - var anotherDeskType = new DeskType { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = anotherDeskTypeName }; - var anotherDesk = new Desk { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; + var anotherDeskType = new DeskType + { CompanyId = companyId, DeskTypeId = anotherDeskTypeId, DeskTypeName = anotherDeskTypeName }; + var anotherDesk = new Desk + { DeskId = anotherDeskId, DeskName = deskName, DeskTypeId = anotherDeskTypeId, RoomId = anotherRoomId }; context.Buildings.Add(anotherBuilding); context.Floors.Add(anotherFloor); @@ -2277,7 +2509,7 @@ public void UpdateDeskType_WhenUpdatingNothing_ShouldUpdateNothing() var userLogger = new Mock>(); var userUsecases = new UserUsecases(userLogger.Object, context); var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context); // act var updatedDeskType = resourceUsecases.UpdateDeskType(companyId, anotherDeskTypeId, null); @@ -2289,6 +2521,7 @@ public void UpdateDeskType_WhenUpdatingNothing_ShouldUpdateNothing() // cleanup context.Database.EnsureDeleted(); } + [Test] public void GetBuildings_WhenNoBuildingFound_ShouldReturnAEmptyList() { @@ -2319,7 +2552,7 @@ public void GetBuildings_WhenNoBuildingFound_ShouldReturnAEmptyList() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act @@ -2332,6 +2565,40 @@ public void GetBuildings_WhenNoBuildingFound_ShouldReturnAEmptyList() db.Database.EnsureDeleted(); } + [Test] + public void GetBuildings_WhenTwoBuildingsFound_ShouldReturnAList() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + var companyId = Guid.NewGuid(); + SetupMockData(db, userId: userId, companyId: companyId); + var building2 = new Building + { + BuildingName = "testBuilding2", + Location = "testLocation2", + CompanyId = companyId + }; + db.Buildings.Add(building2); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new ResourceUsecases(logger.Object, db); + + + //act + var result = usecases.GetBuildings(userId); + + //assert + Assert.That(result, Is.Not.Empty); + Assert.That(result.Count, Is.EqualTo(2)); + + //cleanup + db.Database.EnsureDeleted(); + } + [Test] public void GetBuildings_WhenOneBuildingFound_ShouldReturnAException() { @@ -2345,7 +2612,7 @@ public void GetBuildings_WhenOneBuildingFound_ShouldReturnAException() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var callId = Guid.NewGuid(); //act @@ -2395,7 +2662,7 @@ public void GetAllFloors_WhenNoFloorFound_ShouldReturnAEmptyList() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act var result = usecases.GetAllFloors(userId); @@ -2438,7 +2705,7 @@ public void GetFloors_WhenNoFloorFound_ShouldReturnAEmptyList() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act @@ -2452,7 +2719,7 @@ public void GetFloors_WhenNoFloorFound_ShouldReturnAEmptyList() } [Test] - public void GetFloors_WhenNoFloorIdProvided_ShouldReturnList() + public void GetAllFloors_WhenNoFloorIdProvided_ShouldReturnList() { //setup using var db = new DataContext(); @@ -2464,11 +2731,11 @@ public void GetFloors_WhenNoFloorIdProvided_ShouldReturnList() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act - var result = usecases.GetFloors(userId,""); + var result = usecases.GetAllFloors(userId); //assert Assert.That(result, Is.Not.Empty); @@ -2478,6 +2745,29 @@ public void GetFloors_WhenNoFloorIdProvided_ShouldReturnList() db.Database.EnsureDeleted(); } + [Test] + public void GetFloors_WhenInvaildFloorIdProvided_ShouldThrowAnExecption() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + SetupMockData(db, userId: userId); + + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new ResourceUsecases(logger.Object, db); + + + //act+ assert + Assert.Throws(() => usecases.GetFloors(userId, Guid.NewGuid().ToString())); + + //cleanup + db.Database.EnsureDeleted(); + } + [Test] public void GetFloors_WhenBuildingNotExists_ShouldReturnAException() { @@ -2492,7 +2782,7 @@ public void GetFloors_WhenBuildingNotExists_ShouldReturnAException() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var callId = Guid.NewGuid(); //act @@ -2519,12 +2809,12 @@ public void GetRooms_WhenRoomFound_ShouldReturnAList() using var db = new DataContext(); var userId = Guid.NewGuid(); var floorId = Guid.NewGuid(); - var roomId= Guid.NewGuid(); - SetupMockData(db, userId: userId, floorId: floorId, roomId:roomId); + var roomId = Guid.NewGuid(); + SetupMockData(db, userId: userId, floorId: floorId, roomId: roomId); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); usecases.DeleteRoom(userId, roomId.ToString()); @@ -2546,12 +2836,12 @@ public void GetRooms_WhenNoRoomFound_ShouldReturnAEmptyList() using var db = new DataContext(); var userId = Guid.NewGuid(); var floorId = Guid.NewGuid(); - var roomId= Guid.NewGuid(); - SetupMockData(db, userId: userId, floorId: floorId, roomId:roomId); + var roomId = Guid.NewGuid(); + SetupMockData(db, userId: userId, floorId: floorId, roomId: roomId); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); usecases.DeleteRoom(userId, roomId.ToString()); @@ -2572,40 +2862,63 @@ public void GetRooms_WhenNoValidRoomId_ShouldReturnAnException() using var db = new DataContext(); var userId = Guid.NewGuid(); var floorId = Guid.NewGuid(); - SetupMockData(db, userId: userId, floorId: floorId ); + SetupMockData(db, userId: userId, floorId: floorId); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //assert + act - Assert.Throws(()=>usecases.GetRooms(userId, "abs")); + Assert.Throws(() => usecases.GetRooms(userId, "abs")); //cleanup db.Database.EnsureDeleted(); } [Test] - public void GetRooms_WhenNoRoomIdProvided_ShouldReturnAnList() + public void GetRooms_WhenInvalidRoomIdProvided_ShouldThrowAnException() { //setup using var db = new DataContext(); var userId = Guid.NewGuid(); - SetupMockData(db, userId: userId ); + SetupMockData(db, userId: userId); db.SaveChanges(); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); + + + //act+ assert + Assert.Throws(() => usecases.GetFloors(userId, Guid.NewGuid().ToString())); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void GetAllRooms_WhenNoRoomIdProvided_ShouldReturnAnList() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + SetupMockData(db, userId: userId); + + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new ResourceUsecases(logger.Object, db); //act - var result=usecases.GetRooms(userId, ""); + var result = usecases.GetAllRooms(userId); - //assert - Assert.That(result, Is.Not.Empty); - Assert.That(result.Count, Is.EqualTo(1)); + //assert + Assert.That(result, Is.Not.Empty); + Assert.That(result.Count, Is.EqualTo(1)); //cleanup db.Database.EnsureDeleted(); @@ -2641,7 +2954,7 @@ public void GetAllRooms_WhenNoRoomIsFound_ShouldReturnEmptyList() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act var result = usecases.GetAllRooms(userId); @@ -2683,7 +2996,7 @@ public void GetAllDesks_WhenNoDeskIsFound_ShouldReturnEmptyList() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act var result = usecases.GetAllDesks(userId); @@ -2751,7 +3064,7 @@ public void GetDesks_WhenNoDeskFound_ShouldReturnAEmptyList() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act @@ -2780,7 +3093,7 @@ public void GetDesks_WhenOneDeskFound_ShouldReturnAException() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var callId = Guid.NewGuid(); //act @@ -2801,7 +3114,100 @@ public void GetDesks_WhenOneDeskFound_ShouldReturnAException() } [Test] - public void GetDesks_WhenNoRoomIdProvided_ShouldListOfAllDesks() + public void GetDesks_WhenInvalidDeskIdProvided_ShouldThrowAnException() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + SetupMockData(db, userId: userId); + + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new ResourceUsecases(logger.Object, db); + + + //act+ assert + Assert.Throws(() => usecases.GetDesk(Guid.NewGuid(), DateTime.Now, DateTime.MaxValue)); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void GetDesks_WhenInvalidDeskIdProvided2_ShouldThrowAnException() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + SetupMockData(db, userId: userId); + + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new ResourceUsecases(logger.Object, db); + + + //act+ assert + Assert.Throws(() => usecases.GetDesks(userId, "abc", DateTime.Now, DateTime.MaxValue)); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void GetDesks_WhenInvalidDeskIdProvided3_ShouldThrowAnException() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + SetupMockData(db, userId: userId); + + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new ResourceUsecases(logger.Object, db); + + + //act+ assert + Assert.Throws(() => + usecases.GetDesks(userId, Guid.NewGuid().ToString(), DateTime.Now, DateTime.MaxValue)); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void GetRooms_WhenInvalidDeskIdProvided_ShouldThrowAnException() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + SetupMockData(db, userId: userId); + + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new ResourceUsecases(logger.Object, db); + + + //act+ assert + Assert.Throws(() => usecases.GetRooms(userId, "abc")); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void GetAllDesks_WhenNoRoomIdProvided_ShouldListOfAllDesks() { //setup using var db = new DataContext(); @@ -2816,11 +3222,11 @@ public void GetDesks_WhenNoRoomIdProvided_ShouldListOfAllDesks() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act - var result = usecases.GetDesks(userId, "", start, end); + var result = usecases.GetAllDesks(userId); //assert Assert.That(result, Is.Not.Empty); @@ -2857,7 +3263,7 @@ public void GetDesks_WhenDeskIsFound_StartBeforeEndIn_ShouldReturnACurrentsDeskL //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act @@ -2917,7 +3323,7 @@ public void GetDesks_WhenDeskIsFound_StartInEndBevore_ShouldReturnACurrentsDeskL //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act @@ -2977,7 +3383,7 @@ public void GetDesks_WhenDeskIsFound_SameStartAndEndTime_ShouldReturnACurrentsDe //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act @@ -3026,7 +3432,7 @@ public void GetDesk_WhenDeskNotFound_ShouldThrowAnException() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var callId = Guid.NewGuid(); //act @@ -3072,7 +3478,7 @@ public void GetDesk_WhenDeskIsFound_ShouldReturnCurrentDeskObject() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act @@ -3100,6 +3506,26 @@ public void GetDesk_WhenDeskIsFound_ShouldReturnCurrentDeskObject() db.Database.EnsureDeleted(); } + [Test] + public void GetDesks_WhenNonVaildID_ShouldThrowAnError() + { + //setup + using var db = new DataContext(); + SetupMockData(db); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new ResourceUsecases(logger.Object, db); + + + //act + assert + Assert.Throws(() => usecases.GetDesk(new Guid(), DateTime.Now, DateTime.Now)); + + //cleanup + db.Database.EnsureDeleted(); + } + [Test] public void GetDeskTypes_WhenDeskTypeIsFound_ShouldReturnDeskTypes() { @@ -3114,7 +3540,7 @@ public void GetDeskTypes_WhenDeskTypeIsFound_ShouldReturnDeskTypes() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act @@ -3143,7 +3569,7 @@ public void GetDeskTypes_WhenCompanyHasNoDeskTypes_ShouldReturnEmptyList() //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act @@ -3172,7 +3598,7 @@ public void CreateDesk_WhenValidDeskTypeAndRoomId_ShouldAddDeskAndReturnItsGuid( //arrange var deskName = "validDeskName"; var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act @@ -3201,7 +3627,7 @@ public void CreateDesk_WhenDuplicatedNameIsProvided_ShouldThrowArgumentInvalidEx //arrange var duplicated = "Desk1"; var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act+assert Assert.Throws(() => usecases.CreateDesk(duplicated, deskTypeId, roomId)); @@ -3227,7 +3653,7 @@ public void CreateDesk_WhenNoNameIsProvided_ShouldThrowArgumentInvalidException( //arrange var noDeskName = ""; var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act+assert Assert.Throws(() => usecases.CreateDesk(noDeskName, deskTypeId, roomId)); @@ -3246,14 +3672,14 @@ public void CreateDesk_WhenInvalidDeskType_ShouldThrowEntityNotFoundException() var companyId = Guid.NewGuid(); var invalidDeskTypeId = Guid.NewGuid(); var roomId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId, roomId: roomId); + SetupMockData(db, companyId, roomId: roomId); db.SaveChanges(); //arrange var deskName = "validDeskName"; var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act+assert Assert.Throws(() => usecases.CreateDesk(deskName, invalidDeskTypeId, roomId)); @@ -3271,14 +3697,14 @@ public void CreateDesk_WhenInvalidRoomId_ShouldThrowEntityNotFoundException() var companyId = Guid.NewGuid(); var deskTypeId = Guid.NewGuid(); var invalidRoomId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId, deskTypeId: deskTypeId); + SetupMockData(db, companyId, deskTypeId: deskTypeId); db.SaveChanges(); //arrange var deskName = "validDeskName"; var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); //act+assert Assert.Throws(() => usecases.CreateDesk(deskName, deskTypeId, invalidRoomId)); @@ -3298,7 +3724,7 @@ public void CreateDeskType_WhenInvalidCompanyIdIsProvided_ShouldThrowEntitiyNotF //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var deskTypeName = "validDeskName"; var invalidCompanyId = Guid.NewGuid(); @@ -3315,13 +3741,13 @@ public void CreateDeskType_WhenNoDeskTypeNameIsProvided_ShouldThrowArgumentInval //setup using var db = new DataContext(); var companyId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId); + SetupMockData(db, companyId); db.SaveChanges(); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var noDeskTypeName = ""; //act+assert @@ -3337,13 +3763,13 @@ public void CreateDeskType_WhenDeskTypeAlreadyExists_ShouldThrowArgumentInvalidE //setup using var db = new DataContext(); var companyId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId); + SetupMockData(db, companyId); db.SaveChanges(); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var duplicateName = "Typ1"; //act+assert @@ -3359,13 +3785,13 @@ public void CreateDeskType_WhenValidArgumentsProvided_ShouldCreateDeskType() //setup using var db = new DataContext(); var companyId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId); + SetupMockData(db, companyId); db.SaveChanges(); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var deskTypeName = "ValidName"; //act+assert @@ -3386,7 +3812,7 @@ public void CreateRoom_WhenInvalidFloorIdIsProvided_ShouldThrowEntitiyNotFoundEx //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var roomName = "validRoomName"; var invalidFloorId = Guid.NewGuid(); @@ -3404,13 +3830,13 @@ public void CreateRoom_WhenNoRoomNameIsProvided_ShouldThrowArgumentInvalidExcept using var db = new DataContext(); var companyId = Guid.NewGuid(); var floorId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId, floorId: floorId); + SetupMockData(db, companyId, floorId: floorId); db.SaveChanges(); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var noRoomName = ""; //act+assert @@ -3427,13 +3853,13 @@ public void CreateRoom_WhenRoomNameAlreadyExists_ShouldThrowArgumentInvalidExcep using var db = new DataContext(); var companyId = Guid.NewGuid(); var floorId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId, floorId: floorId); + SetupMockData(db, companyId, floorId: floorId); db.SaveChanges(); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var duplicateName = "Raum1"; //act+assert @@ -3450,13 +3876,13 @@ public void CreateRoom_WhenValidArgumentsProvided_ShouldCreateRoom() using var db = new DataContext(); var companyId = Guid.NewGuid(); var floorId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId, floorId: floorId); + SetupMockData(db, companyId, floorId: floorId); db.SaveChanges(); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var roomName = "ValidName"; //act+assert @@ -3477,7 +3903,7 @@ public void CreateFloor_WhenInvalidBuildingIdIsProvided_ShouldThrowEntitiyNotFou //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var floorName = "validName"; var invalidBuildingId = Guid.NewGuid(); @@ -3495,13 +3921,13 @@ public void CreateFloor_WhenNoFloorNameIsProvided_ShouldThrowArgumentInvalidExce using var db = new DataContext(); var companyId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId, buildingId: buildingId); + SetupMockData(db, companyId, buildingId: buildingId); db.SaveChanges(); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var noFloorName = ""; //act+assert @@ -3518,13 +3944,13 @@ public void CreateFloor_WhenFloorNameAlreadyExists_ShouldThrowArgumentInvalidExc using var db = new DataContext(); var companyId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId, buildingId: buildingId); + SetupMockData(db, companyId, buildingId: buildingId); db.SaveChanges(); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var duplicateName = "Stockwerk1"; //act+assert @@ -3541,13 +3967,13 @@ public void CreateFloor_WhenValidArgumentsProvided_ShouldCreateFloor() using var db = new DataContext(); var companyId = Guid.NewGuid(); var buildingId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId, buildingId: buildingId); + SetupMockData(db, companyId, buildingId: buildingId); db.SaveChanges(); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var floorName = "ValidName"; //act+assert @@ -3568,7 +3994,7 @@ public void CreateBuilding_WhenInvalidCompanyIdIsProvided_ShouldThrowEntitiyNotF //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var buildingName = "validName"; var location = "validLocation"; var invalidCompanyId = Guid.NewGuid(); @@ -3586,13 +4012,13 @@ public void CreateBuilding_WhenNoLocationIsProvided_ShouldThrowArgumentInvalidEx //setup using var db = new DataContext(); var companyId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId); + SetupMockData(db, companyId); db.SaveChanges(); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var buildingName = "validName"; var noLocation = ""; @@ -3609,13 +4035,13 @@ public void CreateBuilding_WhenNoBuildingNameIsProvided_ShouldThrowArgumentInval //setup using var db = new DataContext(); var companyId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId); + SetupMockData(db, companyId); db.SaveChanges(); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var noBuildingName = ""; var location = "validLocation"; @@ -3632,13 +4058,13 @@ public void CreateBuilding_WhenBuildingNameAlreadyExists_ShouldThrowArgumentInva //setup using var db = new DataContext(); var companyId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId); + SetupMockData(db, companyId); db.SaveChanges(); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var duplicateName = "Gebäude1"; var location = "validLocation"; @@ -3655,13 +4081,13 @@ public void CreateBuilding_WhenValidArgumentsProvided_ShouldCreateBuilding() //setup using var db = new DataContext(); var companyId = Guid.NewGuid(); - SetupMockData(db, companyId: companyId); + SetupMockData(db, companyId); db.SaveChanges(); //arrange var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var usecases = new ResourceUsecases(logger.Object, db); var buildingName = "validName"; var location = "validLocation"; @@ -3684,7 +4110,7 @@ public void DeleteBuilding_WhenValidBuildingIsProvided_ShouldUpdateBuilding() //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); //act resourceUsecases.DeleteBuilding(adminId, buildingId.ToString()); @@ -3694,6 +4120,176 @@ public void DeleteBuilding_WhenValidBuildingIsProvided_ShouldUpdateBuilding() db.Floors.Where(f => f.BuildingId == buildingId).ToList().ForEach(f => Assert.That(f.IsMarkedForDeletion)); } + [Test] + public void DeleteBuilding_WhenNonValidAdminIsProvided_ShouldThrowAnException() + { + //setup + using var db = new DataContext(); + var buildingId = Guid.NewGuid(); + var adminId = Guid.NewGuid(); + + SetupMockData(db, buildingId: buildingId, userId: adminId); + + //arrange + var logger = new Mock>(); + var resourceUsecases = new ResourceUsecases(logger.Object, db); + + //act + Assert.Throws( + () => resourceUsecases.DeleteBuilding(Guid.NewGuid(), buildingId.ToString())); + } + + [Test] + public void GetFloors_WhenNonValidFloorIdIsProvided_ShouldThrowAnException() + { + //setup + using var db = new DataContext(); + var buildingId = Guid.NewGuid(); + var adminId = Guid.NewGuid(); + + SetupMockData(db, buildingId: buildingId, userId: adminId); + + //arrange + var logger = new Mock>(); + var resourceUsecases = new ResourceUsecases(logger.Object, db); + + //act + Assert.Throws(() => resourceUsecases.GetFloors(adminId, Guid.NewGuid().ToString())); + } + + [Test] + public void GetFloors_WhenNonValidFloorIdIsProvided2_ShouldThrowAnException() + { + //setup + using var db = new DataContext(); + var buildingId = Guid.NewGuid(); + var adminId = Guid.NewGuid(); + + SetupMockData(db, buildingId: buildingId, userId: adminId); + + //arrange + var logger = new Mock>(); + var resourceUsecases = new ResourceUsecases(logger.Object, db); + + //act + Assert.Throws(() => resourceUsecases.GetFloors(adminId, "abc")); + } + + [Test] + public void GetFloors_WhenNoFloorFound_ShouldReturnAnEmptyList() + { + //setup + using var db = new DataContext(); + var buildingId = Guid.NewGuid(); + var adminId = Guid.NewGuid(); + var floorId = Guid.NewGuid(); + var roomId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + var deskTypeId = Guid.NewGuid(); + + SetupMockData(db, buildingId: buildingId, userId: adminId, floorId: floorId, roomId: roomId, deskId: deskId, + deskTypeId: deskTypeId); + var desk = db.Desks.First(d => d.DeskId == deskId); + db.Desks.Remove(desk); + var deskType = db.DeskTypes.First(d => d.DeskTypeId == deskTypeId); + db.DeskTypes.Remove(deskType); + var room = db.Rooms.First(r => r.RoomId == roomId); + db.Rooms.Remove(room); + var floor = db.Floors.First(f => f.FloorId == floorId); + db.Floors.Remove(floor); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var resourceUsecases = new ResourceUsecases(logger.Object, db); + //act + var result = resourceUsecases.GetFloors(adminId, buildingId.ToString()); + //Assert + Assert.That(result.Count == 0); + } + + [Test] + public void GetRoom_WhenNoRoomFound_ShouldReturnAnEmptyList() + { + //setup + using var db = new DataContext(); + var adminId = Guid.NewGuid(); + var floorId = Guid.NewGuid(); + var roomId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + var deskTypeId = Guid.NewGuid(); + + SetupMockData(db, userId: adminId, floorId: floorId, roomId: roomId, deskId: deskId, + deskTypeId: deskTypeId); + var desk = db.Desks.First(d => d.DeskId == deskId); + db.Desks.Remove(desk); + var deskType = db.DeskTypes.First(d => d.DeskTypeId == deskTypeId); + db.DeskTypes.Remove(deskType); + var room = db.Rooms.First(r => r.RoomId == roomId); + db.Rooms.Remove(room); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var resourceUsecases = new ResourceUsecases(logger.Object, db); + //act + var result = resourceUsecases.GetRooms(adminId, floorId.ToString()); + //Assert + Assert.That(result.Count == 0); + } + + [Test] + public void GetDesk_WhenNoDeskFound_ShouldReturnAnEmptyList() + { + //setup + using var db = new DataContext(); + var adminId = Guid.NewGuid(); + var roomId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + var deskTypeId = Guid.NewGuid(); + + SetupMockData(db, userId: adminId, roomId: roomId, deskId: deskId, + deskTypeId: deskTypeId); + var desk = db.Desks.First(d => d.DeskId == deskId); + db.Desks.Remove(desk); + var deskType = db.DeskTypes.First(d => d.DeskTypeId == deskTypeId); + db.DeskTypes.Remove(deskType); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var resourceUsecases = new ResourceUsecases(logger.Object, db); + //act + var result = resourceUsecases.GetDesks(adminId, roomId.ToString(), DateTime.MinValue, DateTime.MaxValue); + //Assert + Assert.That(result.Count == 0); + } + + [Test] + public void GetDeskType_WhenNoDeskTypeFound_ShouldReturnAnEmptyList() + { + //setup + using var db = new DataContext(); + var adminId = Guid.NewGuid(); + var deskId = Guid.NewGuid(); + var deskTypeId = Guid.NewGuid(); + + SetupMockData(db, userId: adminId, deskTypeId: deskTypeId, deskId: deskId); + var desk = db.Desks.First(d => d.DeskId == deskId); + db.Desks.Remove(desk); + var deskType = db.DeskTypes.First(d => d.DeskTypeId == deskTypeId); + db.DeskTypes.Remove(deskType); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var resourceUsecases = new ResourceUsecases(logger.Object, db); + //act + var result = resourceUsecases.GetDeskTypes(adminId); + //Assert + Assert.That(result.Count == 0); + } + [Test] public void DeleteBuilding_WhenNonValidBuildingIsProvided_ShouldThrowEntityNotFoundException() { @@ -3705,8 +4301,7 @@ public void DeleteBuilding_WhenNonValidBuildingIsProvided_ShouldThrowEntityNotFo //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); - + var resourceUsecases = new ResourceUsecases(logger.Object, db); //act & assert Assert.Throws(() => resourceUsecases.DeleteBuilding(adminId, new Guid().ToString())); @@ -3724,7 +4319,7 @@ public void DeleteFloor_WhenValidFloorIsProvided_ShouldUpdateFloor() //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); //act resourceUsecases.DeleteFloor(adminId, floorId.ToString()); @@ -3745,7 +4340,7 @@ public void DeleteFloor_WhenNonValidFloorIsProvided_ShouldThrowEntityNotFoundExc //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); //act & assert @@ -3764,7 +4359,7 @@ public void DeleteRoom_WhenValidRoomIsProvided_ShouldUpdateRoom() //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); //act resourceUsecases.DeleteRoom(adminId, roomId.ToString()); @@ -3785,7 +4380,7 @@ public void DeleteRoom_WhenNonValidRoomIsProvided_ShouldThrowEntityNotFoundExcep //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); //act & assert @@ -3804,7 +4399,7 @@ public void DeleteDesk_WhenValidDeskIsProvided_ShouldUpdateDesk() //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); //act resourceUsecases.DeleteDesk(adminId, deskId.ToString()); @@ -3824,7 +4419,7 @@ public void DeleteDesk_WhenNonValidDeskIsProvided_ShouldThrowEntityNotFoundExcep //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); //act & assert @@ -3844,7 +4439,7 @@ public void DeleteDeskType_WhenValidDeskTypeIsProvided_ShouldUpdateDeskType() //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); resourceUsecases.DeleteDesk(adminId, deskId.ToString()); //act resourceUsecases.DeleteDeskType(adminId, deskTypeId.ToString()); @@ -3864,7 +4459,7 @@ public void DeleteDeskType_WhenNonValidDeskTypeIsProvided_ShouldThrowEntityNotFo //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); //act & assert @@ -3883,7 +4478,7 @@ public void RestoreBuilding_WhenValidBuildingIsProvided_ShouldUpdateBuilding() //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); resourceUsecases.DeleteBuilding(adminId, buildingId.ToString()); //act @@ -3904,7 +4499,7 @@ public void RestoreBuilding_WhenNonValidBuildingIsProvided_ShouldThrowEntityNotF //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); //act & assert @@ -3923,7 +4518,7 @@ public void RestoreFloor_WhenValidFloorIsProvided_ShouldUpdateFloor() //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); resourceUsecases.DeleteFloor(adminId, floorId.ToString()); //act @@ -3944,7 +4539,7 @@ public void RestoreFloor_WhenNonValidFloorIsProvided_ShouldThrowEntityNotFoundEx //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); //act & assert @@ -3963,7 +4558,7 @@ public void RestoreRoom_WhenValidRoomIsProvided_ShouldUpdateRoom() //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); resourceUsecases.DeleteRoom(adminId, roomId.ToString()); //act @@ -3984,7 +4579,7 @@ public void RestoreRoom_WhenNonValidRoomIsProvided_ShouldThrowEntityNotFoundExce //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); //act & assert @@ -4003,7 +4598,7 @@ public void RestoreDesk_WhenValidDeskIsProvided_ShouldUpdateDesk() //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); resourceUsecases.DeleteDesk(adminId, deskId.ToString()); //act @@ -4024,7 +4619,7 @@ public void RestoreDesk_WhenNonValidDeskIsProvided_ShouldThrowEntityNotFoundExce //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); //act & assert @@ -4044,7 +4639,7 @@ public void RestoreDeskType_WhenValidDeskTypeIsProvided_ShouldUpdateDeskType() //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); resourceUsecases.DeleteDesk(adminId, deskId.ToString()); resourceUsecases.DeleteDeskType(adminId, deskTypeId.ToString()); @@ -4066,7 +4661,7 @@ public void RestoreDeskType_WhenNonValidDeskTypeIsProvided_ShouldThrowEntityNotF //arrange var logger = new Mock>(); - var resourceUsecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + var resourceUsecases = new ResourceUsecases(logger.Object, db); //act & assert diff --git a/src/deskstar-backend/Teststar.Tests/Tests/UserUsecasesTests.cs b/src/deskstar-backend/Teststar.Tests/Tests/UserUsecasesTests.cs index ac29c36f..2e4c8d34 100644 --- a/src/deskstar-backend/Teststar.Tests/Tests/UserUsecasesTests.cs +++ b/src/deskstar-backend/Teststar.Tests/Tests/UserUsecasesTests.cs @@ -1,4 +1,3 @@ -using Castle.Components.DictionaryAdapter; using Deskstar.Core.Exceptions; using Deskstar.DataAccess; using Deskstar.Entities; @@ -11,598 +10,577 @@ namespace Teststar.Tests.Tests; public class UserUsecasesTests { - [Test] - public void ReadSpecificUser_WhenInvalidUserIdIsGiven_ShouldThrowEntityNotFoundException() - { - //setup - using var db = new DataContext(); - - var userId = Guid.NewGuid(); - setupMockData(db, userID: userId); - - //arrange - var invalidId = Guid.NewGuid(); - var logger = new Mock>(); - var usecases = new UserUsecases(logger.Object, db); - - //act + assert - Assert.Throws(() => usecases.ReadSpecificUser(invalidId)); - - //cleanup - db.Database.EnsureDeleted(); - } - - [Test] - public void ReadSpecificUser_WhenValidUserIdIsGiven_ShouldReturnUser() - { - //setup - using var db = new DataContext(); - - var userId = Guid.NewGuid(); - setupMockData(db, userID: userId); - - //arrange - var logger = new Mock>(); - var usecases = new UserUsecases(logger.Object, db); - - //act - var result = usecases.ReadSpecificUser(userId); - - //assert - Assert.That(result.UserId == userId); - - //cleanup - db.Database.EnsureDeleted(); - } - - [Test] - public void ApproveUser_WhenValidUserIdIsGiven_ShouldApproveUser() - { - //setup - using var db = new DataContext(); - bool isUserApproved = false; - User user, admin; - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - //act - var result = userUsecases.ApproveUser(admin.UserId, user.UserId.ToString()); - - //assert - Assert.That(result == user.UserId); - - //cleanup - db.Database.EnsureDeleted(); - } - - [Test] - public void ApproveUser_WhenInvalidUserIdIsGiven_ShouldThrowArgumentInvalidException() - { - //setup - using var db = new DataContext(); - bool isUserApproved = false; - User user, admin; - SetupSingleUser(db, isUserApproved, out user, out admin); + [Test] + public void ReadSpecificUser_WhenInvalidUserIdIsGiven_ShouldThrowEntityNotFoundException() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + setupMockData(db, userID: userId); + + //arrange + var invalidId = Guid.NewGuid(); + var logger = new Mock>(); + var usecases = new UserUsecases(logger.Object, db); + + //act + assert + Assert.Throws(() => usecases.ReadSpecificUser(invalidId)); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void ReadSpecificUser_WhenValidUserIdIsGiven_ShouldReturnUser() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + setupMockData(db, userID: userId); + + //arrange + var logger = new Mock>(); + var usecases = new UserUsecases(logger.Object, db); + + //act + var result = usecases.ReadSpecificUser(userId); + + //assert + Assert.That(result.UserId == userId); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void ApproveUser_WhenValidUserIdIsGiven_ShouldApproveUser() + { + //setup + using var db = new DataContext(); + var isUserApproved = false; + User user, admin; + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //act + var result = userUsecases.ApproveUser(admin.UserId, user.UserId.ToString()); + + //assert + Assert.That(result == user.UserId); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void ApproveUser_WhenInvalidUserIdIsGiven_ShouldThrowArgumentInvalidException() + { + //setup + using var db = new DataContext(); + var isUserApproved = false; + User user, admin; + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //act + assert + Assert.Throws(() => userUsecases.ApproveUser(admin.UserId, "invalidguid")); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void ApproveUser_WhenThereIsNoUserWithGivenId_ShouldThrowEntityNotFoundException() + { + //setup + using var db = new DataContext(); + var isUserApproved = false; + User user, admin; + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //act + assert + Assert.Throws(() => userUsecases.ApproveUser(admin.UserId, new Guid().ToString())); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void + ApproveUser_WhenValidUserIsGivenButAdminIsFromDifferentCompany_ShouldThrowInsufficientPermissionException() + { + //setup + using var db = new DataContext(); + var isUserApproved = false; + User user, admin; + SetupSingleUserInDifferentCompany(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //act + assert + Assert.Throws(() => + userUsecases.ApproveUser(admin.UserId, user.UserId.ToString())); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void + DeclineUser_WhenValidUserIsGivenButAdminIsFromDifferentCompany_ShouldThrowInsufficientPermissionException() + { + //setup + using var db = new DataContext(); + var isUserApproved = false; + User user, admin; + SetupSingleUserInDifferentCompany(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //act + assert + Assert.Throws(() => + userUsecases.DeclineUser(admin.UserId, user.UserId.ToString())); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void DeclineUser_WhenUserIsAlreadyApproved_ShouldThrowArgumentInvalidException() + { + //setup + using var db = new DataContext(); + var isUserApproved = true; + User user, admin; + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //act + assert + Assert.Throws(() => userUsecases.DeclineUser(admin.UserId, user.UserId.ToString())); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void DeclineUser_WhenNoUserExistsWithGivenId_ShouldThrowEntityNotFoundException() + { + //setup + using var db = new DataContext(); + var isUserApproved = false; + User user, admin; + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //act + assert + Assert.Throws(() => userUsecases.DeclineUser(admin.UserId, new Guid().ToString())); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void DeclineUser_WhenValidUserIdIsGiven_ShouldRemoveUser() + { + //setup + using var db = new DataContext(); + User user, admin; + var isUserApproved = false; + + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //act + var result = userUsecases.DeclineUser(admin.UserId, user.UserId.ToString()); + + //assert + var userWasRemoved = !db.Users.Contains(user); + Assert.That(userWasRemoved); + Assert.That(result == user.UserId); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void UpdateUser_WhenValidUserIsProvided_ButLastAdmin_ShouldThrowException() + { + //setup + using var db = new DataContext(); + User user, admin; + var isUserApproved = true; + + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //assert+ act + Assert.Throws(() => userUsecases.UpdateUser(user.UserId, user)); + } + + [Test] + public void UpdateUser_WhenValidUserIsProvided_ShouldUpdateUser() + { + //setup + using var db = new DataContext(); + User user, admin; + var isUserApproved = true; + + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + user.FirstName = "test"; + //act + var result = userUsecases.UpdateUser(admin.UserId, user); + //assert + Assert.That(result == user.UserId); + Assert.That(db.Users.First(u => u.UserId == result).FirstName == "test"); + } + + [Test] + public void UpdateUser_nothingChanged_WhenValidUserIsProvided_ShouldUpdateUser() + { + //setup + using var db = new DataContext(); + User user, admin; + var isUserApproved = true; + + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //act + var result = userUsecases.UpdateUser(admin.UserId, user); + //assert + Assert.That(result == user.UserId); + } + + [Test] + public void UpdateUser_WhenInvalidUserIsProvided_ShouldThrowEntityNotFoundException() + { + //setup + using var db = new DataContext(); + User user, admin; + var isUserApproved = true; + + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //act + assert + Assert.Throws(() => userUsecases.UpdateUser(new Guid(), new User())); + } + + [Test] + public void UpdateUser_AsAdmin_WhenValidUserIsProvided_ShouldUpdateUser() + { + //setup + using var db = new DataContext(); + User user, admin; + var isUserApproved = true; + + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //act + var result = userUsecases.UpdateUser(admin.UserId, user); + + //assert + Assert.That(result == user.UserId); + } + + [Test] + public void ReadAllUsers_WhenValidUserIdIsProvided_ShouldReturnListOfAllUsersInTheSameCompany() + { + //setup + using var db = new DataContext(); + User user, admin; + var isUserApproved = true; + + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //act + var result = userUsecases.ReadAllUsers(admin.UserId); + + //assert + Assert.That(result.Count != 0); + Assert.That(result.Contains(user)); + } + + [Test] + public void ReadAllUsers_WhenInvalidUserIdIsProvided_ShouldThrowEntityNotFoundException() + { + //setup + using var db = new DataContext(); + User user, admin; + var isUserApproved = true; + + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //act + assert + Assert.Throws(() => userUsecases.ReadAllUsers(new Guid())); + } + + [Test] + public void DeleteUser_WhenValidUserIsProvided_ShouldUpdateUser() + { + //setup + using var db = new DataContext(); + User user, admin; + const bool isUserApproved = true; + + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + //act + var result = userUsecases.DeleteUser(admin.UserId, user.UserId.ToString()); + + //assert + Assert.That(result, Is.EqualTo(user.UserId)); + Assert.That(db.Users.First(u => u.UserId == user.UserId).IsMarkedForDeletion); + } + + [Test] + public void DeleteUser_WhenNonValidUserIsProvided_ShouldThrowEntityNotFoundException() + { + //setup + using var db = new DataContext(); + User user, admin; + const bool isUserApproved = true; + + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); + + + //act & assert + Assert.Throws(() => userUsecases.DeleteUser(admin.UserId, new Guid().ToString())); + } + + [Test] + public void DeleteUser_WhenDeleteSelf_ShouldThrowArgumentInvalidException() + { + //setup + using var db = new DataContext(); + User user, admin; + const bool isUserApproved = true; + + SetupSingleUser(db, isUserApproved, out user, out admin); + + //arrange + var logger = new Mock>(); + var userUsecases = new UserUsecases(logger.Object, db); - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - //act + assert - Assert.Throws(() => userUsecases.ApproveUser(admin.UserId, "invalidguid")); + //act & assert + Assert.Throws(() => userUsecases.DeleteUser(admin.UserId, admin.UserId.ToString())); + } - //cleanup - db.Database.EnsureDeleted(); - } + private void SetupSingleUser(DataContext db, bool userApproved, out User user, out User admin) + { + var hasher = new PasswordHasher(); - [Test] - public void ApproveUser_WhenThereIsNoUserWithGivenId_ShouldThrowEntityNotFoundException() + var companyId = Guid.NewGuid(); + var company = new Company { - //setup - using var db = new DataContext(); - bool isUserApproved = false; - User user, admin; - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - //act + assert - Assert.Throws(() => userUsecases.ApproveUser(admin.UserId, (new Guid()).ToString())); - - //cleanup - db.Database.EnsureDeleted(); - } - - [Test] - public void - ApproveUser_WhenValidUserIsGivenButAdminIsFromDifferentCompany_ShouldThrowInsufficientPermissionException() + CompanyId = companyId, + CompanyName = "testLLC" + }; + user = new User { - //setup - using var db = new DataContext(); - bool isUserApproved = false; - User user, admin; - SetupSingleUserInDifferentCompany(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - //act + assert - Assert.Throws(() => - userUsecases.ApproveUser(admin.UserId, user.UserId.ToString())); - - //cleanup - db.Database.EnsureDeleted(); - } - - [Test] - public void - DeclineUser_WhenValidUserIsGivenButAdminIsFromDifferentCompany_ShouldThrowInsufficientPermissionException() - { - //setup - using var db = new DataContext(); - bool isUserApproved = false; - User user, admin; - SetupSingleUserInDifferentCompany(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - //act + assert - Assert.Throws(() => - userUsecases.DeclineUser(admin.UserId, user.UserId.ToString())); - - //cleanup - db.Database.EnsureDeleted(); - } - - [Test] - public void DeclineUser_WhenUserIsAlreadyApproved_ShouldThrowArgumentInvalidException() - { - //setup - using var db = new DataContext(); - bool isUserApproved = true; - User user, admin; - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - //act + assert - Assert.Throws(() => userUsecases.DeclineUser(admin.UserId, user.UserId.ToString())); - - //cleanup - db.Database.EnsureDeleted(); - } - - [Test] - public void DeclineUser_WhenNoUserExistsWithGivenId_ShouldThrowEntityNotFoundException() - { - //setup - using var db = new DataContext(); - bool isUserApproved = false; - User user, admin; - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - //act + assert - Assert.Throws(() => userUsecases.DeclineUser(admin.UserId, (new Guid()).ToString())); - - //cleanup - db.Database.EnsureDeleted(); - } - - [Test] - public void DeclineUser_WhenValidUserIdIsGiven_ShouldRemoveUser() - { - //setup - using var db = new DataContext(); - User user, admin; - bool isUserApproved = false; - - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - //act - var result = userUsecases.DeclineUser(admin.UserId, user.UserId.ToString()); - - //assert - var userWasRemoved = !db.Users.Contains(user); - Assert.That(userWasRemoved); - Assert.That(result == user.UserId); - - //cleanup - db.Database.EnsureDeleted(); - } - - [Test] - public void UpdateUser_WhenValidUserIsProvided_ButLastAdmin_ShouldThrowException() - { - //setup - using var db = new DataContext(); - User user, admin; - bool isUserApproved = true; - - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - //assert+ act - Assert.Throws(() => userUsecases.UpdateUser(user.UserId, user)); - } - - [Test] - public void UpdateUser_WhenValidUserIsProvided_ShouldUpdateUser() + UserId = Guid.NewGuid(), + MailAddress = "test@example.de", + FirstName = "testF", + LastName = "testL", + CompanyId = companyId, + IsApproved = userApproved + }; + user.Password = hasher.HashPassword(user, "testpw"); + admin = new User { - //setup - using var db = new DataContext(); - User user, admin; - bool isUserApproved = true; - - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - user.FirstName="test"; - //act - var result = userUsecases.UpdateUser(admin.UserId, user); - //assert - Assert.That(result == user.UserId); - Assert.That(db.Users.First(u=>u.UserId==result).FirstName == "test"); - } - - [Test] - public void UpdateUser_nothingChanged_WhenValidUserIsProvided_ShouldUpdateUser() + UserId = Guid.NewGuid(), + MailAddress = "test@example.de", + FirstName = "testF", + LastName = "testL", + CompanyId = companyId, + IsApproved = false, + IsCompanyAdmin = true + }; + admin.Password = hasher.HashPassword(admin, "testpw"); + db.Companies.Add(company); + db.Users.Add(user); + db.Users.Add(admin); + db.SaveChanges(); + } + + private void SetupSingleUserInDifferentCompany(DataContext db, bool isApproved, out User user, out User admin) + { + var hasher = new PasswordHasher(); + + var companyId = Guid.NewGuid(); + var company = new Company { - //setup - using var db = new DataContext(); - User user, admin; - bool isUserApproved = true; - - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - //act - var result = userUsecases.UpdateUser(admin.UserId, user); - //assert - Assert.That(result == user.UserId); - } - - [Test] - public void UpdateUser_WhenInvalidUserIsProvided_ShouldThrowEntityNotFoundException() + CompanyId = companyId, + CompanyName = "testLLC" + }; + var companyId2 = Guid.NewGuid(); + var company2 = new Company { - //setup - using var db = new DataContext(); - User user, admin; - bool isUserApproved = true; - - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - //act + assert - Assert.Throws(() => userUsecases.UpdateUser(new Guid(), new User())); - } - - [Test] - public void UpdateUser_AsAdmin_WhenValidUserIsProvided_ShouldUpdateUser() + CompanyId = companyId2, + CompanyName = "testLLC2" + }; + user = new User { - //setup - using var db = new DataContext(); - User user, admin; - bool isUserApproved = true; - - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - //act - var result = userUsecases.UpdateUser(admin.UserId, user); - - //assert - Assert.That(result == user.UserId); - } - - [Test] - public void ReadAllUsers_WhenValidUserIdIsProvided_ShouldReturnListOfAllUsersInTheSameCompany() + UserId = Guid.NewGuid(), + MailAddress = "test@example.de", + FirstName = "testF", + LastName = "testL", + CompanyId = companyId2, + IsApproved = isApproved + }; + user.Password = hasher.HashPassword(user, "testpw"); + admin = new User { - //setup - using var db = new DataContext(); - User user, admin; - bool isUserApproved = true; - - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - //act - var result = userUsecases.ReadAllUsers(admin.UserId); - - //assert - Assert.That(result.Count != 0); - Assert.That(result.Contains(user)); - } - - [Test] - public void ReadAllUsers_WhenInvalidUserIdIsProvided_ShouldThrowEntityNotFoundException() + UserId = Guid.NewGuid(), + MailAddress = "test@example.de", + FirstName = "testF", + LastName = "testL", + CompanyId = companyId, + IsApproved = false, + IsCompanyAdmin = true + }; + admin.Password = hasher.HashPassword(admin, "testpw"); + db.Companies.Add(company); + db.Companies.Add(company2); + db.Users.Add(user); + db.Users.Add(admin); + db.SaveChanges(); + } + + private void setupMockData(DataContext moqDb, Guid companyID = new(), Guid userID = new(), + Guid buildingID = new(), Guid floorID = new(), Guid roomID = new(), Guid deskTypeID = new(), + Guid deskID = new()) + { + if (companyID.ToString() == "00000000-0000-0000-0000-000000000000") companyID = Guid.NewGuid(); + + if (userID.ToString() == "00000000-0000-0000-0000-000000000000") userID = Guid.NewGuid(); + + if (buildingID.ToString() == "00000000-0000-0000-0000-000000000000") buildingID = Guid.NewGuid(); + + if (floorID.ToString() == "00000000-0000-0000-0000-000000000000") floorID = Guid.NewGuid(); + + if (roomID.ToString() == "00000000-0000-0000-0000-000000000000") roomID = Guid.NewGuid(); + + if (deskTypeID.ToString() == "00000000-0000-0000-0000-000000000000") deskTypeID = Guid.NewGuid(); + + if (deskID.ToString() == "00000000-0000-0000-0000-000000000000") deskID = Guid.NewGuid(); + + var hasher = new PasswordHasher(); + var company = new Company { - //setup - using var db = new DataContext(); - User user, admin; - bool isUserApproved = true; - - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - //act + assert - Assert.Throws(() => userUsecases.ReadAllUsers(new Guid())); - } - - [Test] - public void DeleteUser_WhenValidUserIsProvided_ShouldUpdateUser() + CompanyId = companyID, + CompanyName = "gehmalbierholn" + }; + var user = new User { - //setup - using var db = new DataContext(); - User user, admin; - const bool isUserApproved = true; - - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - //act - var result = userUsecases.DeleteUser(admin.UserId, user.UserId.ToString()); - - //assert - Assert.That(result, Is.EqualTo(user.UserId)); - Assert.That(db.Users.First(u => u.UserId == user.UserId).IsMarkedForDeletion); - } - - [Test] - public void DeleteUser_WhenNonValidUserIsProvided_ShouldThrowEntityNotFoundException() + UserId = userID, + MailAddress = "test@example.de", + FirstName = "testF", + LastName = "testL", + CompanyId = company.CompanyId, + IsApproved = true + }; + user.Password = hasher.HashPassword(user, "testpw"); + var building = new Building { - //setup - using var db = new DataContext(); - User user, admin; - const bool isUserApproved = true; - - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - - //act & assert - Assert.Throws(() => userUsecases.DeleteUser(admin.UserId, new Guid().ToString())); - } - - [Test] - public void DeleteUser_WhenDeleteSelf_ShouldThrowArgumentInvalidException() + BuildingId = buildingID, + BuildingName = "Gebäude1", + Location = "Location1", + CompanyId = company.CompanyId + }; + var floor = new Floor { - //setup - using var db = new DataContext(); - User user, admin; - const bool isUserApproved = true; - - SetupSingleUser(db, isUserApproved, out user, out admin); - - //arrange - var logger = new Mock>(); - var userUsecases = new UserUsecases(logger.Object, db); - - - //act & assert - Assert.Throws(() => userUsecases.DeleteUser(admin.UserId, admin.UserId.ToString())); - } - - private void SetupSingleUser(DataContext db, bool userApproved, out User user, out User admin) + FloorId = floorID, + FloorName = "Stockwerk1", + BuildingId = building.BuildingId + }; + var room = new Room { - var hasher = new PasswordHasher(); - - var companyId = Guid.NewGuid(); - var company = new Company - { - CompanyId = companyId, - CompanyName = "testLLC" - }; - user = new User - { - UserId = Guid.NewGuid(), - MailAddress = "test@example.de", - FirstName = "testF", - LastName = "testL", - CompanyId = companyId, - IsApproved = userApproved - }; - user.Password = hasher.HashPassword(user, "testpw"); - admin = new User - { - UserId = Guid.NewGuid(), - MailAddress = "test@example.de", - FirstName = "testF", - LastName = "testL", - CompanyId = companyId, - IsApproved = false, - IsCompanyAdmin = true - }; - admin.Password = hasher.HashPassword(admin, "testpw"); - db.Companies.Add(company); - db.Users.Add(user); - db.Users.Add(admin); - db.SaveChanges(); - } - - private void SetupSingleUserInDifferentCompany(DataContext db, bool isApproved, out User user, out User admin) + RoomId = roomID, + FloorId = floor.FloorId, + RoomName = "Raum1" + }; + var deskTyp = new DeskType { - var hasher = new PasswordHasher(); - - var companyId = Guid.NewGuid(); - var company = new Company - { - CompanyId = companyId, - CompanyName = "testLLC" - }; - var companyId2 = Guid.NewGuid(); - var company2 = new Company - { - CompanyId = companyId2, - CompanyName = "testLLC2" - }; - user = new User - { - UserId = Guid.NewGuid(), - MailAddress = "test@example.de", - FirstName = "testF", - LastName = "testL", - CompanyId = companyId2, - IsApproved = isApproved - }; - user.Password = hasher.HashPassword(user, "testpw"); - admin = new User - { - UserId = Guid.NewGuid(), - MailAddress = "test@example.de", - FirstName = "testF", - LastName = "testL", - CompanyId = companyId, - IsApproved = false, - IsCompanyAdmin = true - }; - admin.Password = hasher.HashPassword(admin, "testpw"); - db.Companies.Add(company); - db.Companies.Add(company2); - db.Users.Add(user); - db.Users.Add(admin); - db.SaveChanges(); - } - - private void setupMockData(DataContext moqDb, Guid companyID = new Guid(), Guid userID = new Guid(), - Guid buildingID = new Guid(), Guid floorID = new Guid(), Guid roomID = new Guid(), Guid deskTypeID = new Guid(), - Guid deskID = new Guid()) + DeskTypeId = deskTypeID, + CompanyId = company.CompanyId, + DeskTypeName = "Typ1" + }; + var desk = new Desk { - if (companyID.ToString() == "00000000-0000-0000-0000-000000000000") - { - companyID = Guid.NewGuid(); - } - - if (userID.ToString() == "00000000-0000-0000-0000-000000000000") - { - userID = Guid.NewGuid(); - } - - if (buildingID.ToString() == "00000000-0000-0000-0000-000000000000") - { - buildingID = Guid.NewGuid(); - } - - if (floorID.ToString() == "00000000-0000-0000-0000-000000000000") - { - floorID = Guid.NewGuid(); - } - - if (roomID.ToString() == "00000000-0000-0000-0000-000000000000") - { - roomID = Guid.NewGuid(); - } - - if (deskTypeID.ToString() == "00000000-0000-0000-0000-000000000000") - { - deskTypeID = Guid.NewGuid(); - } - - if (deskID.ToString() == "00000000-0000-0000-0000-000000000000") - { - deskID = Guid.NewGuid(); - } - - var hasher = new PasswordHasher(); - var company = new Company - { - CompanyId = companyID, - CompanyName = "gehmalbierholn" - }; - var user = new User - { - UserId = userID, - MailAddress = "test@example.de", - FirstName = "testF", - LastName = "testL", - CompanyId = company.CompanyId, - IsApproved = true - }; - user.Password = hasher.HashPassword(user, "testpw"); - var building = new Building - { - BuildingId = buildingID, - BuildingName = "Gebäude1", - Location = "Location1", - CompanyId = company.CompanyId - }; - var floor = new Floor - { - FloorId = floorID, - FloorName = "Stockwerk1", - BuildingId = building.BuildingId - }; - var room = new Room - { - RoomId = roomID, - FloorId = floor.FloorId, - RoomName = "Raum1" - }; - var deskTyp = new DeskType - { - DeskTypeId = deskTypeID, - CompanyId = company.CompanyId, - DeskTypeName = "Typ1" - }; - var desk = new Desk - { - DeskId = deskID, - DeskName = "Desk1", - DeskTypeId = deskTyp.DeskTypeId, - RoomId = room.RoomId - }; - moqDb.Companies.Add(company); - moqDb.Users.Add(user); - moqDb.Buildings.Add(building); - moqDb.Floors.Add(floor); - moqDb.Rooms.Add(room); - moqDb.DeskTypes.Add(deskTyp); - moqDb.Desks.Add(desk); - - moqDb.SaveChanges(); - } + DeskId = deskID, + DeskName = "Desk1", + DeskTypeId = deskTyp.DeskTypeId, + RoomId = room.RoomId + }; + moqDb.Companies.Add(company); + moqDb.Users.Add(user); + moqDb.Buildings.Add(building); + moqDb.Floors.Add(floor); + moqDb.Rooms.Add(room); + moqDb.DeskTypes.Add(deskTyp); + moqDb.Desks.Add(desk); + + moqDb.SaveChanges(); + } } diff --git a/src/deskstar-backend/Teststar.Tests/Usings.cs b/src/deskstar-backend/Teststar.Tests/Usings.cs index cefced49..32445676 100644 --- a/src/deskstar-backend/Teststar.Tests/Usings.cs +++ b/src/deskstar-backend/Teststar.Tests/Usings.cs @@ -1 +1 @@ -global using NUnit.Framework; \ No newline at end of file +global using NUnit.Framework; diff --git a/src/deskstar-frontend/pages/resources/index.tsx b/src/deskstar-frontend/pages/resources/index.tsx index f7504f56..897361c8 100644 --- a/src/deskstar-frontend/pages/resources/index.tsx +++ b/src/deskstar-frontend/pages/resources/index.tsx @@ -364,7 +364,7 @@ const ResourceOverview = ({ let result = await deleteBuilding(session, building.buildingId); if (result.response == ResourceResponse.Success) { - toast.success(result.message); + toast.success(`Building ${building.buildingName} deleted!`); // Remove the building from buildingList setBuildings( @@ -382,7 +382,7 @@ const ResourceOverview = ({ let result = await deleteFloor(session, floor.floorId); if (result.response == ResourceResponse.Success) { - toast.success(result.message); + toast.success(`Floor ${floor.floorName} deleted!`); // Remove the floor from floorList setFloors(floors.filter((b) => b.floorId !== floor.floorId)); @@ -398,7 +398,7 @@ const ResourceOverview = ({ let result = await deleteRoom(session, room.roomId); if (result.response == ResourceResponse.Success) { - toast.success(result.message); + toast.success(`Room ${room.roomName} deleted!`); // Remove the room from roomList setRooms(rooms.filter((b) => b.roomId !== room.roomId)); @@ -414,7 +414,7 @@ const ResourceOverview = ({ let result = await deleteDesk(session, desk.deskId); if (result.response == ResourceResponse.Success) { - toast.success(result.message); + toast.success(`Desk ${desk.deskName} deleted!`); // Remove the desk from deskList setDesks(desks.filter((b) => b.deskId !== desk.deskId)); @@ -584,7 +584,7 @@ const ResourceOverview = ({ /> building.buildingId != selectedBuilding.buildingId @@ -94,7 +94,7 @@ export default function DeletedRessourceOverview({ selectedFloor.isMarkedForDeletion = false; const result = await restoreFloor(session, selectedFloor); if (result.response == ResourceResponse.Success) { - toast.success(result.message); + toast.success(`Floor ${selectedFloor.floorName} restored.`); setFloors( floors.filter((floor) => floor.floorId != selectedFloor.floorId) ); @@ -112,7 +112,7 @@ export default function DeletedRessourceOverview({ selectedRoom.isMarkedForDeletion = false; const result = await restoreRoom(session, selectedRoom); if (result.response == ResourceResponse.Success) { - toast.success(result.message); + toast.success(`Room ${selectedRoom.roomName} restored!`); setRooms(rooms.filter((room) => room.roomId != selectedRoom.roomId)); } else { console.error(result.message); @@ -128,7 +128,7 @@ export default function DeletedRessourceOverview({ selectedDesk.isMarkedForDeletion = false; const result = await restoreDesk(session, selectedDesk); if (result.response == ResourceResponse.Success) { - toast.success(result.message); + toast.success(`Desk ${selectedDesk.deskName} restored.`); setDesks(desks.filter((desk) => desk.deskName != selectedDesk.deskName)); } else { console.error(result.message); @@ -146,7 +146,7 @@ export default function DeletedRessourceOverview({ selectedDeskType.isMarkedForDeletion = false; const result = await restoreDeskType(session, selectedDeskType); if (result.response == ResourceResponse.Success) { - toast.success(result.message); + toast.success(`Desktype ${selectedDeskType.deskTypeName} restored.`); setDeskTypes( deskTypes.filter( (deskType) => deskType.deskTypeName != selectedDeskType.deskTypeName