diff --git a/src/deskstar-backend/Deskstar/Controllers/ResourcesController.cs b/src/deskstar-backend/Deskstar/Controllers/ResourcesController.cs index ee39878c..fd6a85f0 100644 --- a/src/deskstar-backend/Deskstar/Controllers/ResourcesController.cs +++ b/src/deskstar-backend/Deskstar/Controllers/ResourcesController.cs @@ -127,676 +127,676 @@ public IActionResult UpdateDeskType(string deskTypeId, UpdateDeskTypeDto dto) } } - /// - /// Updates a Building. - /// - /// - /// Sample request: - /// PUT /resources/buildings/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token - /// - /// - /// Ok - /// Bad Request - /// Not Found - /// Internal Server Error - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [HttpPut("buildings/{buildingId}")] - [Authorize(Policy = "Admin")] - [Produces("application/json")] - public IActionResult UpdateBuilding(string buildingId, UpdateBuildingDto dto) - { - var adminId = RequestInteractions.ExtractIdFromRequest(Request); - - try - { - var buildingGuid = new Guid(buildingId); - var companyId = _userUsecases.ReadSpecificUser(adminId).CompanyId; - - _resourceUsecases.UpdateBuilding(companyId, buildingGuid, dto.BuildingName, dto.Location); - - return Ok(); - } - catch (EntityNotFoundException e) - { - _logger.LogError(e, e.Message); - return NotFound(e.Message); - } - catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } - } - - /// - /// Updates a Floor. - /// - /// - /// Sample request: - /// PUT /resources/floors/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token - /// - /// - /// Ok - /// Bad Request - /// Not Found - /// Internal Server Error - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [HttpPut("floors/{floorId}")] - [Authorize(Policy = "Admin")] - [Produces("application/json")] - public IActionResult UpdateFloor(string floorId, UpdateFloorDto dto) - { - var adminId = RequestInteractions.ExtractIdFromRequest(Request); - - try - { - var floorGuid = new Guid(floorId); - var companyId = _userUsecases.ReadSpecificUser(adminId).CompanyId; - Guid? buildingGuid = dto.BuildingId==null?null: new Guid(dto.BuildingId); - - _resourceUsecases.UpdateFloor(companyId, floorGuid, dto.FloorName, buildingGuid); - - return Ok(); - } - catch (EntityNotFoundException e) - { - _logger.LogError(e, e.Message); - return NotFound(e.Message); - } - catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } - } - - /// - /// Updates a Room. - /// - /// - /// Sample request: - /// PUT /resources/rooms/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token - /// - /// - /// Ok - /// Bad Request - /// Not Found - /// Internal Server Error - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [HttpPut("rooms/{roomId}")] - [Authorize(Policy = "Admin")] - [Produces("application/json")] - public IActionResult UpdateRoom(string roomId, UpdateRoomDto dto) - { - var adminId = RequestInteractions.ExtractIdFromRequest(Request); - - try - { - var roomGuid = new Guid(roomId); - var companyId = _userUsecases.ReadSpecificUser(adminId).CompanyId; - Guid? floorId = dto.FloorId==null?null: new Guid(dto.FloorId); - - _resourceUsecases.UpdateRoom(companyId, roomGuid, dto.RoomName, floorId); - - return Ok(); - } - catch (EntityNotFoundException e) - { - _logger.LogError(e, e.Message); - return NotFound(e.Message); - } - catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } - } - - /// - /// Returns a list of Buildings. - /// - /// A List of Buildings in JSON Format (can be empty) - /// - /// Sample request: - /// GET /resources/buildings with JWT Token - /// - /// - /// Returns the buildings list - /// Bad Request - /// Internal Server Error - [HttpGet("buildings")] - [Authorize] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult GetAllBuildings() - { - var userId = RequestInteractions.ExtractIdFromRequest(Request); - List buildings; - try - { - buildings = _resourceUsecases.GetBuildings(userId); - } - catch (ArgumentException e) - { - return Problem(statusCode: 500, detail: e.Message); - } - - return Ok(buildings.ToList()); - } - - /// - /// Creates a new Building. - /// - /// - /// Sample request: - /// POST /resources/buildings with JWT-Admin Token - /// - /// - /// CreateBuildingResponseObject - /// Bad Request - /// Not Found - /// Internal Server Error - [HttpPost("buildings")] - [Authorize(Policy = "Admin")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult CreateBuilding(CreateBuildingDto buildingDto) - { - var adminId = RequestInteractions.ExtractIdFromRequest(Request); - - try - { - var companyId = _userUsecases.ReadSpecificUser(adminId).CompanyId; - var building = _resourceUsecases.CreateBuilding(buildingDto.BuildingName, buildingDto.Location, companyId); - var resultBuilding = _mapper.Map(building); - return Ok(resultBuilding); - } - catch (EntityNotFoundException e) - { - _logger.LogError(e, e.Message); - return NotFound(e.Message); - } - catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } - } - - /// - /// Deletes a Building. - /// - /// - /// Sample request: - /// DELETE /resources/buildings/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token - /// - /// - /// Bad Request - /// Not Implemented - [HttpDelete("buildings/{buildingId}")] - [Authorize(Policy = "Admin")] - [ProducesResponseType(StatusCodes.Status205ResetContent)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult DeleteBuilding(string buildingId) - { - return Problem(statusCode: 501); - } - - - /// - /// 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 - /// - /// - /// Returns the floor list - /// Bad Request - /// Internal Server Error - [HttpGet("buildings/{buildingId}/floors")] - [Authorize] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult GetFloorsByBuildingId(string buildingId) - { - List floor; - try - { - floor = _resourceUsecases.GetFloors(new Guid(buildingId)); - } - catch (ArgumentException e) - { - return Problem(statusCode: 500, detail: e.Message); - } - - return Ok(floor.ToList()); - } - - /// - /// Creates a new Floor. - /// - /// - /// Sample request: - /// POST /resources/floors with JWT-Admin Token - /// - /// - /// CreateFloorResponseObject - /// Bad Request - /// Not Found - /// Internal Server Error - [HttpPost("floors")] - [Authorize(Policy = "Admin")] - [ProducesResponseType(StatusCodes.Status201Created)] - [ProducesResponseType(StatusCodes.Status409Conflict)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult CreateFloor(CreateFloorDto floorDto) - { - var adminId = RequestInteractions.ExtractIdFromRequest(Request); - - try - { - var buildingId = new Guid(floorDto.BuildingId); - var floor = _resourceUsecases.CreateFloor(floorDto.FloorName, buildingId); - var resultFloor = _mapper.Map(floor); - return Ok(resultFloor); - } - catch (EntityNotFoundException e) - { - _logger.LogError(e, e.Message); - return NotFound(e.Message); - } - catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } - } - - /// - /// Deletes a Floor. - /// - /// - /// Sample request: - /// DELETE /resources/floors/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token - /// - /// - /// Bad Request - /// Not Impelemented - [HttpDelete("floors/{floorId}")] - [Authorize(Policy = "Admin")] - [ProducesResponseType(StatusCodes.Status205ResetContent)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult DeleteFloor(string floorId) - { - return Problem(statusCode: 501); - } - - /// - /// 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 - /// - /// - /// Returns the rooms list - /// Bad Request - /// Internal Server Error - [HttpGet("floors/{floorId}/rooms")] - [Authorize] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult GetRoomsByFloorId(string floorId) - { - List rooms; - try - { - rooms = _resourceUsecases.GetRooms(new Guid(floorId)); - } - catch (ArgumentException e) - { - return Problem(statusCode: 500, detail: e.Message); - } - - return Ok(rooms.ToList()); - } - - /// - /// Creates a new Room. - /// - /// - /// Sample request: - /// POST /resources/rooms with JWT-Admin Token - /// - /// - /// CreateRoomResponseObject - /// Bad Request - /// Not Found - /// Internal Server Error - [HttpPost("rooms")] - [Authorize(Policy = "Admin")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult CreateRoom(CreateRoomDto roomDto) - { - var adminId = RequestInteractions.ExtractIdFromRequest(Request); - - try - { - var floorId = new Guid(roomDto.FloorId); - var room = _resourceUsecases.CreateRoom(roomDto.RoomName, floorId); - var resultRoom = _mapper.Map(room); - return Ok(resultRoom); - } - catch (EntityNotFoundException e) - { - _logger.LogError(e, e.Message); - return NotFound(e.Message); - } - catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } - } - - /// - /// Deletes a Room. - /// - /// - /// Sample request: - /// DELETE /resources/rooms/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token - /// - /// - /// Bad Request - /// Not Implemented - [HttpDelete("rooms/{roomId}")] - [Authorize(Policy = "Admin")] - [ProducesResponseType(StatusCodes.Status205ResetContent)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult DeleteRoom(string roomId) - { - return Problem(statusCode: 501); - } - - /// - /// 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 - /// - /// - /// Returns the desks list - /// Bad Request - /// Internal Server Error - [HttpGet("rooms/{roomId}/desks")] - [Authorize] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult GetDesksByRoomId(string roomId, long start = 0, long end = 0) - { - var startDateTime = start == 0 ? DateTime.MinValue : DateTimeOffset.FromUnixTimeMilliseconds(start).DateTime; - var endDateTime = end == 0 ? DateTime.MaxValue : DateTimeOffset.FromUnixTimeMilliseconds(end).DateTime; - List desks; - try - { - desks = _resourceUsecases.GetDesks(new Guid(roomId), startDateTime, endDateTime); - } - catch (ArgumentException e) - { - return Problem(statusCode: 500, detail: e.Message); - } - - return Ok(desks.ToList()); - } - - /// - /// 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 - /// - /// - /// Returns the buildings list - /// Bad Request - /// Internal Server Error - [HttpGet("desks/{deskId}")] - [Authorize] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult GetDeskDetailsByDeskId(string deskId, long start = 0, long end = 0) - { - DateTime startDateTime; - DateTime endDateTime; - try - { - 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); - } - } - catch (FormatException e) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - - CurrentDesk desk; - try - { - desk = _resourceUsecases.GetDesk(new Guid(deskId), startDateTime, endDateTime); - } - catch (ArgumentException e) - { - return Problem(statusCode: 500, detail: e.Message); - } - - return Ok(desk); - } - - /// - /// Creates a new Desk. - /// - /// - /// Sample request: - /// POST /resources/desks with JWT-Admin Token - /// - /// - /// CreateDeskResponseObject - /// Bad Request - /// Not Found - /// Internal Server Error - [HttpPost("desks")] - [Authorize(Policy = "Admin")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult CreateDesk(CreateDeskDto deskDto) - { - var adminId = RequestInteractions.ExtractIdFromRequest(Request); - - try - { - var deskTypeId = new Guid(deskDto.DeskTypeId); - var roomId = new Guid(deskDto.RoomId); - var desk = _resourceUsecases.CreateDesk(deskDto.DeskName, deskTypeId, roomId); - var resultDesk = _mapper.Map(desk); - return Ok(resultDesk); - } - catch (EntityNotFoundException e) - { - _logger.LogError(e, e.Message); - return NotFound(e.Message); - } - catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) - { - _logger.LogError(e, e.Message); - return BadRequest(e.Message); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } - } - - /// - /// Deletes a Desk. - /// - /// - /// Sample request: - /// DELETE /resources/desks/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token - /// - /// - /// Bad Request - /// Not Implemented - [HttpDelete("desks/{deskId}")] - [Authorize(Policy = "Admin")] - [ProducesResponseType(StatusCodes.Status205ResetContent)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult DeleteDesk(string deskId) - { - return Problem(statusCode: 501); - } - - /// - /// Creates a new DeskType. - /// - /// - /// Sample request: - /// POST /resources/desktypes with JWT-Admin Token - /// - /// - /// CreateDeskTypeResponseObject - /// Bad Request - /// Internal Server Error - [HttpPost("desktypes")] - [Authorize(Policy = "Admin")] - [ProducesResponseType(StatusCodes.Status201Created)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult CreateDeskType(CreateDeskTypeDto deskTypeDto) - { - var adminId = RequestInteractions.ExtractIdFromRequest(Request); - try - { - var companyId = _userUsecases.ReadSpecificUser(adminId).CompanyId; - var deskType = _resourceUsecases.CreateDeskType(deskTypeDto.DeskTypeName, companyId); - var resultDeskType = _mapper.Map(deskType); - return Ok(resultDeskType); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } - } - /// - /// Return a list of desk types - /// - /// - /// Sample request: - /// Get /resources/desktypes with JWT-Admin Token - /// - /// - /// List - /// Bad Request - /// Internal Server Error - [HttpGet("desktypes")] - [Authorize(Policy = "Admin")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [Produces("application/json")] - public IActionResult ReadDeskTypes() - { - var adminId = RequestInteractions.ExtractIdFromRequest(Request); - - try - { - var companyId = _userUsecases.ReadSpecificUser(adminId).CompanyId; - var entities = _resourceUsecases.GetDeskTypes(companyId); - var deskTypes = entities.Select(desktype => _mapper.Map(desktype)).ToList(); - return Ok(deskTypes); - } - catch (Exception e) - { - _logger.LogError(e, e.Message); - return Problem(statusCode: 500); - } + /// + /// Updates a Building. + /// + /// + /// Sample request: + /// PUT /resources/buildings/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// + /// + /// Ok + /// Bad Request + /// Not Found + /// Internal Server Error + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [HttpPut("buildings/{buildingId}")] + [Authorize(Policy = "Admin")] + [Produces("application/json")] + public IActionResult UpdateBuilding(string buildingId, UpdateBuildingDto dto) + { + var adminId = RequestInteractions.ExtractIdFromRequest(Request); + + try + { + var buildingGuid = new Guid(buildingId); + var companyId = _userUsecases.ReadSpecificUser(adminId).CompanyId; + + _resourceUsecases.UpdateBuilding(companyId, buildingGuid, dto.BuildingName, dto.Location); + + return Ok(); + } + catch (EntityNotFoundException e) + { + _logger.LogError(e, e.Message); + return NotFound(e.Message); + } + catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) + { + _logger.LogError(e, e.Message); + return BadRequest(e.Message); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); } + } + + /// + /// Updates a Floor. + /// + /// + /// Sample request: + /// PUT /resources/floors/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// + /// + /// Ok + /// Bad Request + /// Not Found + /// Internal Server Error + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [HttpPut("floors/{floorId}")] + [Authorize(Policy = "Admin")] + [Produces("application/json")] + public IActionResult UpdateFloor(string floorId, UpdateFloorDto dto) + { + var adminId = RequestInteractions.ExtractIdFromRequest(Request); + + try + { + var floorGuid = new Guid(floorId); + var companyId = _userUsecases.ReadSpecificUser(adminId).CompanyId; + Guid? buildingGuid = dto.BuildingId == null ? null : new Guid(dto.BuildingId); + + _resourceUsecases.UpdateFloor(companyId, floorGuid, dto.FloorName, buildingGuid); + + return Ok(); + } + catch (EntityNotFoundException e) + { + _logger.LogError(e, e.Message); + return NotFound(e.Message); + } + catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) + { + _logger.LogError(e, e.Message); + return BadRequest(e.Message); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); + } + } + + /// + /// Updates a Room. + /// + /// + /// Sample request: + /// PUT /resources/rooms/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// + /// + /// Ok + /// Bad Request + /// Not Found + /// Internal Server Error + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [HttpPut("rooms/{roomId}")] + [Authorize(Policy = "Admin")] + [Produces("application/json")] + public IActionResult UpdateRoom(string roomId, UpdateRoomDto dto) + { + var adminId = RequestInteractions.ExtractIdFromRequest(Request); + + try + { + var roomGuid = new Guid(roomId); + var companyId = _userUsecases.ReadSpecificUser(adminId).CompanyId; + Guid? floorId = dto.FloorId == null ? null : new Guid(dto.FloorId); + + _resourceUsecases.UpdateRoom(companyId, roomGuid, dto.RoomName, floorId); + + return Ok(); + } + catch (EntityNotFoundException e) + { + _logger.LogError(e, e.Message); + return NotFound(e.Message); + } + catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) + { + _logger.LogError(e, e.Message); + return BadRequest(e.Message); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); + } + } + + /// + /// Returns a list of Buildings. + /// + /// A List of Buildings in JSON Format (can be empty) + /// + /// Sample request: + /// GET /resources/buildings with JWT Token + /// + /// + /// Returns the buildings list + /// Bad Request + /// Internal Server Error + [HttpGet("buildings")] + [Authorize] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult GetAllBuildings() + { + var userId = RequestInteractions.ExtractIdFromRequest(Request); + List buildings; + try + { + buildings = _resourceUsecases.GetBuildings(userId); + } + catch (ArgumentException e) + { + return Problem(statusCode: 500, detail: e.Message); + } + + return Ok(buildings.ToList()); + } + + /// + /// Creates a new Building. + /// + /// + /// Sample request: + /// POST /resources/buildings with JWT-Admin Token + /// + /// + /// CreateBuildingResponseObject + /// Bad Request + /// Not Found + /// Internal Server Error + [HttpPost("buildings")] + [Authorize(Policy = "Admin")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult CreateBuilding(CreateBuildingDto buildingDto) + { + var adminId = RequestInteractions.ExtractIdFromRequest(Request); + + try + { + var companyId = _userUsecases.ReadSpecificUser(adminId).CompanyId; + var building = _resourceUsecases.CreateBuilding(buildingDto.BuildingName, buildingDto.Location, companyId); + var resultBuilding = _mapper.Map(building); + return Ok(resultBuilding); + } + catch (EntityNotFoundException e) + { + _logger.LogError(e, e.Message); + return NotFound(e.Message); + } + catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) + { + _logger.LogError(e, e.Message); + return BadRequest(e.Message); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); + } + } + + /// + /// Deletes a Building. + /// + /// + /// Sample request: + /// DELETE /resources/buildings/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// + /// + /// Bad Request + /// Not Implemented + [HttpDelete("buildings/{buildingId}")] + [Authorize(Policy = "Admin")] + [ProducesResponseType(StatusCodes.Status205ResetContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult DeleteBuilding(string buildingId) + { + return Problem(statusCode: 501); + } + + + /// + /// 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 + /// + /// + /// Returns the floor list + /// Bad Request + /// Internal Server Error + [HttpGet("buildings/{buildingId}/floors")] + [Authorize] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult GetFloorsByBuildingId(string buildingId) + { + List floor; + try + { + floor = _resourceUsecases.GetFloors(new Guid(buildingId)); + } + catch (ArgumentException e) + { + return Problem(statusCode: 500, detail: e.Message); + } + + return Ok(floor.ToList()); + } + + /// + /// Creates a new Floor. + /// + /// + /// Sample request: + /// POST /resources/floors with JWT-Admin Token + /// + /// + /// CreateFloorResponseObject + /// Bad Request + /// Not Found + /// Internal Server Error + [HttpPost("floors")] + [Authorize(Policy = "Admin")] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult CreateFloor(CreateFloorDto floorDto) + { + var adminId = RequestInteractions.ExtractIdFromRequest(Request); + + try + { + var buildingId = new Guid(floorDto.BuildingId); + var floor = _resourceUsecases.CreateFloor(floorDto.FloorName, buildingId); + var resultFloor = _mapper.Map(floor); + return Ok(resultFloor); + } + catch (EntityNotFoundException e) + { + _logger.LogError(e, e.Message); + return NotFound(e.Message); + } + catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) + { + _logger.LogError(e, e.Message); + return BadRequest(e.Message); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); + } + } + + /// + /// Deletes a Floor. + /// + /// + /// Sample request: + /// DELETE /resources/floors/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// + /// + /// Bad Request + /// Not Impelemented + [HttpDelete("floors/{floorId}")] + [Authorize(Policy = "Admin")] + [ProducesResponseType(StatusCodes.Status205ResetContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult DeleteFloor(string floorId) + { + return Problem(statusCode: 501); + } + + /// + /// 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 + /// + /// + /// Returns the rooms list + /// Bad Request + /// Internal Server Error + [HttpGet("floors/{floorId}/rooms")] + [Authorize] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult GetRoomsByFloorId(string floorId) + { + List rooms; + try + { + rooms = _resourceUsecases.GetRooms(new Guid(floorId)); + } + catch (ArgumentException e) + { + return Problem(statusCode: 500, detail: e.Message); + } + + return Ok(rooms.ToList()); + } + + /// + /// Creates a new Room. + /// + /// + /// Sample request: + /// POST /resources/rooms with JWT-Admin Token + /// + /// + /// CreateRoomResponseObject + /// Bad Request + /// Not Found + /// Internal Server Error + [HttpPost("rooms")] + [Authorize(Policy = "Admin")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult CreateRoom(CreateRoomDto roomDto) + { + var adminId = RequestInteractions.ExtractIdFromRequest(Request); + + try + { + var floorId = new Guid(roomDto.FloorId); + var room = _resourceUsecases.CreateRoom(roomDto.RoomName, floorId); + var resultRoom = _mapper.Map(room); + return Ok(resultRoom); + } + catch (EntityNotFoundException e) + { + _logger.LogError(e, e.Message); + return NotFound(e.Message); + } + catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) + { + _logger.LogError(e, e.Message); + return BadRequest(e.Message); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); + } + } + + /// + /// Deletes a Room. + /// + /// + /// Sample request: + /// DELETE /resources/rooms/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// + /// + /// Bad Request + /// Not Implemented + [HttpDelete("rooms/{roomId}")] + [Authorize(Policy = "Admin")] + [ProducesResponseType(StatusCodes.Status205ResetContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult DeleteRoom(string roomId) + { + return Problem(statusCode: 501); + } + + /// + /// 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 + /// + /// + /// Returns the desks list + /// Bad Request + /// Internal Server Error + [HttpGet("rooms/{roomId}/desks")] + [Authorize] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult GetDesksByRoomId(string roomId, long start = 0, long end = 0) + { + var startDateTime = start == 0 ? DateTime.MinValue : DateTimeOffset.FromUnixTimeMilliseconds(start).DateTime; + var endDateTime = end == 0 ? DateTime.MaxValue : DateTimeOffset.FromUnixTimeMilliseconds(end).DateTime; + List desks; + try + { + desks = _resourceUsecases.GetDesks(new Guid(roomId), startDateTime, endDateTime); + } + catch (ArgumentException e) + { + return Problem(statusCode: 500, detail: e.Message); + } + + return Ok(desks.ToList()); + } + + /// + /// 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 + /// + /// + /// Returns the buildings list + /// Bad Request + /// Internal Server Error + [HttpGet("desks/{deskId}")] + [Authorize] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult GetDeskDetailsByDeskId(string deskId, long start = 0, long end = 0) + { + DateTime startDateTime; + DateTime endDateTime; + try + { + 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); + } + } + catch (FormatException e) + { + _logger.LogError(e, e.Message); + return BadRequest(e.Message); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return BadRequest(e.Message); + } + + CurrentDesk desk; + try + { + desk = _resourceUsecases.GetDesk(new Guid(deskId), startDateTime, endDateTime); + } + catch (ArgumentException e) + { + return Problem(statusCode: 500, detail: e.Message); + } + + return Ok(desk); + } + + /// + /// Creates a new Desk. + /// + /// + /// Sample request: + /// POST /resources/desks with JWT-Admin Token + /// + /// + /// CreateDeskResponseObject + /// Bad Request + /// Not Found + /// Internal Server Error + [HttpPost("desks")] + [Authorize(Policy = "Admin")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult CreateDesk(CreateDeskDto deskDto) + { + var adminId = RequestInteractions.ExtractIdFromRequest(Request); + + try + { + var deskTypeId = new Guid(deskDto.DeskTypeId); + var roomId = new Guid(deskDto.RoomId); + var desk = _resourceUsecases.CreateDesk(deskDto.DeskName, deskTypeId, roomId); + var resultDesk = _mapper.Map(desk); + return Ok(resultDesk); + } + catch (EntityNotFoundException e) + { + _logger.LogError(e, e.Message); + return NotFound(e.Message); + } + catch (Exception e) when (e is ArgumentInvalidException or ArgumentNullException or FormatException or OverflowException) + { + _logger.LogError(e, e.Message); + return BadRequest(e.Message); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); + } + } + + /// + /// Deletes a Desk. + /// + /// + /// Sample request: + /// DELETE /resources/desks/3de7afbf-0289-4ba6-bada-a34353c5548a with JWT-Admin Token + /// + /// + /// Bad Request + /// Not Implemented + [HttpDelete("desks/{deskId}")] + [Authorize(Policy = "Admin")] + [ProducesResponseType(StatusCodes.Status205ResetContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult DeleteDesk(string deskId) + { + return Problem(statusCode: 501); + } + + /// + /// Creates a new DeskType. + /// + /// + /// Sample request: + /// POST /resources/desktypes with JWT-Admin Token + /// + /// + /// CreateDeskTypeResponseObject + /// Bad Request + /// Internal Server Error + [HttpPost("desktypes")] + [Authorize(Policy = "Admin")] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult CreateDeskType(CreateDeskTypeDto deskTypeDto) + { + var adminId = RequestInteractions.ExtractIdFromRequest(Request); + try + { + var companyId = _userUsecases.ReadSpecificUser(adminId).CompanyId; + var deskType = _resourceUsecases.CreateDeskType(deskTypeDto.DeskTypeName, companyId); + var resultDeskType = _mapper.Map(deskType); + return Ok(resultDeskType); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); + } + } + /// + /// Return a list of desk types + /// + /// + /// Sample request: + /// Get /resources/desktypes with JWT-Admin Token + /// + /// + /// List + /// Bad Request + /// Internal Server Error + [HttpGet("desktypes")] + [Authorize(Policy = "Admin")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [Produces("application/json")] + public IActionResult ReadDeskTypes() + { + var adminId = RequestInteractions.ExtractIdFromRequest(Request); + + try + { + var companyId = _userUsecases.ReadSpecificUser(adminId).CompanyId; + var entities = _resourceUsecases.GetDeskTypes(companyId); + var deskTypes = entities.Select(desktype => _mapper.Map(desktype)).ToList(); + return Ok(deskTypes); + } + catch (Exception e) + { + _logger.LogError(e, e.Message); + return Problem(statusCode: 500); + } + } } \ No newline at end of file diff --git a/src/deskstar-backend/Deskstar/Usecases/ResourceUsecases.cs b/src/deskstar-backend/Deskstar/Usecases/ResourceUsecases.cs index d7a0e23d..f980e235 100644 --- a/src/deskstar-backend/Deskstar/Usecases/ResourceUsecases.cs +++ b/src/deskstar-backend/Deskstar/Usecases/ResourceUsecases.cs @@ -7,24 +7,24 @@ namespace Deskstar.Usecases; public interface IResourceUsecases { - public List GetDeskTypes(Guid companyId); - public List GetBuildings(Guid userId); - public List GetFloors(Guid buildingId); - public List GetRooms(Guid floorId); - public List GetDesks(Guid roomId, DateTime start, DateTime end); - public CurrentDesk GetDesk(Guid deskId, DateTime startDateTime, DateTime endDateTime); - - public Desk CreateDesk(string deskName, Guid deskTypeId, Guid roomId); - public DeskType CreateDeskType(string deskTypeName, Guid companyId); - public Room CreateRoom(string roomName, Guid floorId); - public Floor CreateFloor(string floorName, Guid buildingId); - public Building CreateBuilding(string buildingName, string location, Guid companyId); - - public Guid UpdateBuilding(Guid companyId, Guid buildingGuid, string? buildingName, string? location); - public Guid UpdateFloor(Guid companyId, Guid floorId, string? floorName, Guid? buildingId); - public Guid UpdateRoom(Guid companyId, Guid roomId, string? roomName, Guid? floorId); - public Guid UpdateDesk(Guid companyId, Guid deskId, string? deskName, Guid? roomId, Guid? deskTypeId); - public Guid UpdateDeskType(Guid companyId, Guid deskTypeId, string? deskTypeName); + public List GetDeskTypes(Guid companyId); + public List GetBuildings(Guid userId); + public List GetFloors(Guid buildingId); + public List GetRooms(Guid floorId); + public List GetDesks(Guid roomId, DateTime start, DateTime end); + public CurrentDesk GetDesk(Guid deskId, DateTime startDateTime, DateTime endDateTime); + + public Desk CreateDesk(string deskName, Guid deskTypeId, Guid roomId); + public DeskType CreateDeskType(string deskTypeName, Guid companyId); + public Room CreateRoom(string roomName, Guid floorId); + public Floor CreateFloor(string floorName, Guid buildingId); + public Building CreateBuilding(string buildingName, string location, Guid companyId); + + public Guid UpdateBuilding(Guid companyId, Guid buildingGuid, string? buildingName, string? location); + public Guid UpdateFloor(Guid companyId, Guid floorId, string? floorName, Guid? buildingId); + public Guid UpdateRoom(Guid companyId, Guid roomId, string? roomName, Guid? floorId); + public Guid UpdateDesk(Guid companyId, Guid deskId, string? deskName, Guid? roomId, Guid? deskTypeId); + public Guid UpdateDeskType(Guid companyId, Guid deskTypeId, string? deskTypeName); } public class ResourceUsecases : IResourceUsecases @@ -43,12 +43,10 @@ public ResourceUsecases(ILogger logger, DataContext context, I public Guid UpdateBuilding(Guid companyId, Guid buildingId, string? buildingName, string? location) { - //check if buildingId matches building var buildingExists = _context.Buildings.SingleOrDefault(b => b.BuildingId == buildingId); if (buildingExists == null) throw new EntityNotFoundException($"There is no building with id '{buildingId}'"); - //check if buildingId matches company if (buildingExists.CompanyId != companyId) throw new InsufficientPermissionException($"'{companyId}' has no access to administrate building '{buildingId}'"); @@ -63,7 +61,6 @@ public Guid UpdateBuilding(Guid companyId, Guid buildingId, string? buildingName //change building name if (buildingName != null) { - //check if buildingName is not empty if (buildingName == "") throw new ArgumentInvalidException($"Building name must not be empty"); var buildingNameIsUnique = buildingExists.Company.Buildings.Select(b => b.BuildingName).All(name => name != buildingName); @@ -73,7 +70,6 @@ public Guid UpdateBuilding(Guid companyId, Guid buildingId, string? buildingName buildingExists.BuildingName = buildingName; } - //save changes _context.Buildings.Update(buildingExists); _context.SaveChanges(); @@ -81,105 +77,98 @@ public Guid UpdateBuilding(Guid companyId, Guid buildingId, string? buildingName } public Guid UpdateFloor(Guid companyId, Guid floorId, string? floorName, Guid? buildingId) - { - var floorExists = _context.Floors.SingleOrDefault(f => f.FloorId == floorId); - if (floorExists == null) - throw new EntityNotFoundException($"There is no floor with id '{floorId}'"); + { + var floorExists = _context.Floors.SingleOrDefault(f => f.FloorId == floorId); + if (floorExists == null) + throw new EntityNotFoundException($"There is no floor with id '{floorId}'"); - //check if floorId matches company - if (floorExists.Building.CompanyId != companyId) - throw new InsufficientPermissionException($"'{companyId}' has no access to administrate floor '{floorId}'"); + if (floorExists.Building.CompanyId != companyId) + throw new InsufficientPermissionException($"'{companyId}' has no access to administrate floor '{floorId}'"); - //change building - if (buildingId != null) - { - //check if building exists - var buildingExists = _context.Buildings.SingleOrDefault(b => b.BuildingId == (Guid)buildingId); - if (buildingExists == null) - throw new EntityNotFoundException($"Building does not exist with id '{(Guid)buildingId}'"); - if (buildingExists.CompanyId != companyId) - throw new InsufficientPermissionException($"'{companyId}' has no access to move a floor to building '{(Guid)buildingId}'"); - var floorNameToBeChecked = floorName != null ? floorName : floorExists.FloorName; - var floorNameExists = _context.Floors.SingleOrDefault(f => f.BuildingId == buildingId && f.FloorName == floorNameToBeChecked); - if (floorNameExists != null) - throw new ArgumentInvalidException($"You cant move floor '{floorId}' to building '{buildingId}'. In building '{buildingId}' already exists a floor called '{floorNameToBeChecked}'"); - - floorExists.BuildingId = (Guid)buildingId; - } + //change building + if (buildingId != null) + { + var buildingExists = _context.Buildings.SingleOrDefault(b => b.BuildingId == (Guid)buildingId); + if (buildingExists == null) + throw new EntityNotFoundException($"Building does not exist with id '{(Guid)buildingId}'"); + if (buildingExists.CompanyId != companyId) + throw new InsufficientPermissionException($"'{companyId}' has no access to move a floor to building '{(Guid)buildingId}'"); + var floorNameToBeChecked = floorName != null ? floorName : floorExists.FloorName; + var floorNameExists = _context.Floors.SingleOrDefault(f => f.BuildingId == buildingId && f.FloorName == floorNameToBeChecked); + if (floorNameExists != null) + throw new ArgumentInvalidException($"You cant move floor '{floorId}' to building '{buildingId}'. In building '{buildingId}' already exists a floor called '{floorNameToBeChecked}'"); + + floorExists.BuildingId = (Guid)buildingId; + } - //change floorName - if (floorName != null) + //change floorName + if (floorName != null) + { + if (floorName == "") + throw new ArgumentInvalidException($"Floor name must not be empty"); + if (buildingId == null) { - //check if floorName is not empty - if (floorName == "") - throw new ArgumentInvalidException($"Floor name must not be empty"); - if (buildingId == null) - { - var floorNameIsUnique = floorExists.Building.Floors.Select(f => f.FloorName).All(name => name != floorName); - if (!floorNameIsUnique) - throw new ArgumentInvalidException($"There is already a floor named '{floorName}' in building '{floorExists.BuildingId}'"); - } - - floorExists.FloorName = floorName; + var floorNameIsUnique = floorExists.Building.Floors.Select(f => f.FloorName).All(name => name != floorName); + if (!floorNameIsUnique) + throw new ArgumentInvalidException($"There is already a floor named '{floorName}' in building '{floorExists.BuildingId}'"); } - //save changes - _context.Floors.Update(floorExists); - _context.SaveChanges(); + floorExists.FloorName = floorName; + } + + _context.Floors.Update(floorExists); + _context.SaveChanges(); + + return floorId; + } - return floorId; + public Guid UpdateRoom(Guid companyId, Guid roomId, string? roomName, Guid? floorId) + { + var roomExists = _context.Rooms.SingleOrDefault(r => r.RoomId == roomId); + if (roomExists == null) + throw new EntityNotFoundException($"There is no room with id '{roomId}'"); + + if (roomExists.Floor.Building.CompanyId != companyId) + throw new InsufficientPermissionException($"'{companyId}' has no access to administrate floor '{roomExists.FloorId}'"); + + //change floor + if (floorId != null) + { + var floorExists = _context.Floors.SingleOrDefault(f => f.FloorId == (Guid)floorId); + if (floorExists == null) + throw new EntityNotFoundException($"Floor does not exist with id '{(Guid)floorId}'"); + if (floorExists.Building.CompanyId != companyId) + throw new InsufficientPermissionException($"'{companyId}' has no access to move a room to floor '{(Guid)floorId}'"); + var roomNameToBeChecked = roomName != null ? roomName : roomExists.RoomName; + var roomNameExists = _context.Rooms.SingleOrDefault(r => r.FloorId == floorId && r.RoomName == roomNameToBeChecked); + if (roomNameExists != null) + throw new ArgumentInvalidException($"You cant move room '{roomId}' to floor '{floorId}'. In floor '{floorId}' already exists a room called '{roomNameToBeChecked}'"); + + roomExists.FloorId = (Guid)floorId; } - public Guid UpdateRoom(Guid companyId, Guid roomId, string? roomName, Guid? floorId) - { - var roomExists = _context.Rooms.SingleOrDefault(r => r.RoomId == roomId); - if (roomExists == null) - throw new EntityNotFoundException($"There is no room with id '{roomId}'"); - - if (roomExists.Floor.Building.CompanyId != companyId) - throw new InsufficientPermissionException($"'{companyId}' has no access to administrate floor '{roomExists.FloorId}'"); - - //change floor - if (floorId != null) - { - //check if floor exists - var floorExists = _context.Floors.SingleOrDefault(f => f.FloorId == (Guid)floorId); - if (floorExists == null) - throw new EntityNotFoundException($"Floor does not exist with id '{(Guid)floorId}'"); - if (floorExists.Building.CompanyId != companyId) - throw new InsufficientPermissionException($"'{companyId}' has no access to move a room to floor '{(Guid)floorId}'"); - var roomNameToBeChecked = roomName != null ? roomName : roomExists.RoomName; - var roomNameExists = _context.Rooms.SingleOrDefault(r => r.FloorId == floorId && r.RoomName == roomNameToBeChecked); - if (roomNameExists != null) - throw new ArgumentInvalidException($"You cant move room '{roomId}' to floor '{floorId}'. In floor '{floorId}' already exists a room called '{roomNameToBeChecked}'"); - - roomExists.FloorId = (Guid)floorId; - } - - //change roomName - if (roomName != null) - { - //check if roomName is not empty - if (roomName == "") - throw new ArgumentInvalidException($"Room name must not be empty"); - if (floorId == null) - { - var roomNameIsUnique = roomExists.Floor.Rooms.Select(r => r.RoomName).All(name => name != roomName); - if (!roomNameIsUnique) - throw new ArgumentInvalidException($"There is already a room named '{roomName}' in floor '{roomExists.FloorId}'"); - } - - roomExists.RoomName = roomName; - } - - //save changes - _context.Rooms.Update(roomExists); - _context.SaveChanges(); - - return roomId; + //change roomName + if (roomName != null) + { + if (roomName == "") + throw new ArgumentInvalidException($"Room name must not be empty"); + if (floorId == null) + { + var roomNameIsUnique = roomExists.Floor.Rooms.Select(r => r.RoomName).All(name => name != roomName); + if (!roomNameIsUnique) + throw new ArgumentInvalidException($"There is already a room named '{roomName}' in floor '{roomExists.FloorId}'"); + } + + roomExists.RoomName = roomName; } - public Guid UpdateDesk(Guid companyId, Guid deskId, string? deskName, Guid? roomId, Guid? deskTypeId) + _context.Rooms.Update(roomExists); + _context.SaveChanges(); + + return roomId; + } + + public Guid UpdateDesk(Guid companyId, Guid deskId, string? deskName, Guid? roomId, Guid? deskTypeId) { var deskExists = _context.Desks.SingleOrDefault(d => d.DeskId == deskId); if (deskExists == null) @@ -207,7 +196,6 @@ public Guid UpdateDesk(Guid companyId, Guid deskId, string? deskName, Guid? room //change deskName if (deskName != null) { - //check if deskName is not empty if (deskName == "") throw new ArgumentInvalidException($"Desk name must not be empty"); if (roomId == null) @@ -232,7 +220,6 @@ public Guid UpdateDesk(Guid companyId, Guid deskId, string? deskName, Guid? room deskExists.DeskTypeId = (Guid)deskTypeId; } - //save changes _context.Desks.Update(deskExists); _context.SaveChanges(); diff --git a/src/deskstar-backend/Teststar.Tests/Tests/ResourceUsecaseTests.cs b/src/deskstar-backend/Teststar.Tests/Tests/ResourceUsecaseTests.cs index 4bcf21b5..9f93ad43 100644 --- a/src/deskstar-backend/Teststar.Tests/Tests/ResourceUsecaseTests.cs +++ b/src/deskstar-backend/Teststar.Tests/Tests/ResourceUsecaseTests.cs @@ -10,752 +10,752 @@ namespace Teststar.Tests.Tests; public class ResourceUsecaseTests { - [Test] - public void UpdateBuilding_WhenBuildingIdDoesNotExist_ShouldThrowEntityNotFoundException() + [Test] + public void UpdateBuilding_WhenBuildingIdDoesNotExist_ShouldThrowEntityNotFoundException() + { + // setup + 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" }; + context.Buildings.Add(building); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + + // act+assert + var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, "Building Name", "Location")); + Assert.NotNull(ex); + Assert.That($"There is no building with id '{buildingId}'" == ex.Message); + + // cleanup + context.Database.EnsureDeleted(); + } + [Test] + public void UpdateBuilding_WhenBuildingNameDoesAlreadyExist_ShouldThrowArgumentInvalidException() + { + // setup + var context = new DataContext(); + + var companyId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + + var buildingName = "testbuilding"; + var company = new Company { CompanyId = companyId, CompanyName = "testcompany" }; + var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = buildingName, Location = "testlocation" }; + + context.Companies.Add(company); + context.Buildings.Add(building); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + + // act+assert + var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, buildingName, null)); + Assert.NotNull(ex); + Assert.AreEqual($"There is already a building named '{buildingName}' in company '{companyId}'", ex.Message); + + // cleanup + context.Database.EnsureDeleted(); + } + [Test] + public void UpdateBuilding_WhenCompanyIdDoesNotMatchBuilding_ShouldThrowInsufficientPermissionException() + { + // setup + var companyId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + var context = new DataContext(); + var building = new Building { BuildingId = buildingId, CompanyId = Guid.NewGuid(), BuildingName = "testname", Location = "testlocation" }; + context.Buildings.Add(building); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + + // act+assert + var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, "Building Name", "Location")); + Assert.NotNull(ex); + Assert.That($"'{companyId}' has no access to administrate building '{buildingId}'" == ex.Message); + + // cleanup + context.Database.EnsureDeleted(); + } + [Test] + public void UpdateBuilding_WhenAllInputIsValid_ShouldUpdateBuilding() + { + // setup + var context = new DataContext(); + + var companyId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + + var buildingName = "testbuilding"; + var company = new Company { CompanyId = companyId, CompanyName = "testcompany" }; + var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = buildingName, Location = "testlocation" }; + + context.Companies.Add(company); + context.Buildings.Add(building); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var updatedBuildingName = "New Building Name"; + var updatedLocation = "New York"; + // act + var result = resourceUsecases.UpdateBuilding(companyId, buildingId, updatedBuildingName, updatedLocation); + + // assert + Assert.IsNotNull(result); + Assert.AreEqual(buildingId, result); + + var updatedBuilding = context.Buildings.Find(buildingId); + Assert.IsNotNull(updatedBuilding); + Assert.AreEqual(updatedBuildingName, updatedBuilding.BuildingName); + Assert.AreEqual(updatedLocation, updatedBuilding.Location); + + // cleanup + context.Database.EnsureDeleted(); + } + [Test] + public void UpdateBuilding_WhenOnlyLocationIsProvided_ShouldUpdateBuildingLocation() + { + // setup + var companyId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + var context = new DataContext(); + var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + context.Buildings.Add(building); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var newLocation = "newlocation"; + + // act + var buildingIdReturned = resourceUsecases.UpdateBuilding(companyId, buildingId, null, newLocation); + + // assert + var updatedBuilding = context.Buildings.SingleOrDefault(b => b.BuildingId == buildingId); + Assert.NotNull(updatedBuilding); + Assert.That(updatedBuilding.Location == newLocation); + Assert.That(buildingIdReturned == buildingId); + + // cleanup + context.Database.EnsureDeleted(); + } + [Test] + public void UpdateBuilding_WhenOnlyBuildingNameIsProvided_ShouldUpdateBuildingName() + { + // setup + var context = new DataContext(); + + var companyId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + 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 }; + + context.Companies.Add(company); + context.Buildings.Add(building); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var updatedBuildingName = "updatedBuildingName"; + + // act + var returnedBuildingId = resourceUsecases.UpdateBuilding(companyId, buildingId, updatedBuildingName, null); + + // assert + Assert.AreEqual(buildingId, returnedBuildingId); + var updatedBuilding = context.Buildings.SingleOrDefault(b => b.BuildingId == buildingId); + Assert.NotNull(updatedBuilding); + Assert.AreEqual(updatedBuildingName, updatedBuilding.BuildingName); + Assert.AreEqual(location, updatedBuilding.Location); + + // cleanup + context.Database.EnsureDeleted(); + } + [Test] + public void UpdateBuilding_WhenNeitherLocationNorBuildingNameIsProvided_ShouldReturnBuildingId() + { + // setup + var companyId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + var context = new DataContext(); + var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + context.Buildings.Add(building); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + + // act + var buildingIdReturned = resourceUsecases.UpdateBuilding(companyId, buildingId, null, null); + + // assert + Assert.AreEqual(buildingId, buildingIdReturned); + + // cleanup + context.Database.EnsureDeleted(); + } + [Test] + public void UpdateBuilding_WhenLocationIsEmpty_ShouldThrowArgumentInvalidException() + { + // setup + var companyId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + var context = new DataContext(); + var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + context.Buildings.Add(building); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + + // act+assert + var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, "Building Name", "")); + Assert.NotNull(ex); + Assert.That($"Location must not be empty" == ex.Message); + + // cleanup + context.Database.EnsureDeleted(); + } + [Test] + public void UpdateBuilding_WhenBuildingNameIsEmpty_ShouldThrowArgumentInvalidException() + { + // setup + var companyId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + var context = new DataContext(); + var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + context.Buildings.Add(building); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + + // act+assert + var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, "", "New York")); + Assert.NotNull(ex); + Assert.That($"Building name must not be empty" == ex.Message); + + // cleanup + context.Database.EnsureDeleted(); + } + [Test] + public void GetBuildings_WhenNoBuildingFound_ShouldReturnAEmptyList() + { + //setup + using var db = new DataContext(); + + var userId = Guid.NewGuid(); + var companyId = Guid.NewGuid(); + var hasher = new PasswordHasher(); + var company = new Company { - // setup - 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" }; - context.Buildings.Add(building); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, "Building Name", "Location")); - Assert.NotNull(ex); - Assert.That($"There is no building with id '{buildingId}'" == ex.Message); - - // cleanup - context.Database.EnsureDeleted(); + 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"); + db.Add(company); + db.Add(user); + db.SaveChanges(); + + //arrange + var logger = new Mock>(); + var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); + + + //act + var result = usecases.GetBuildings(userId); + + //assert + Assert.That(result, Is.Empty); + + //cleanup + db.Database.EnsureDeleted(); + } + + [Test] + public void GetBuildings_WhenOneBuildingFound_ShouldReturnAException() + { + //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, SetupUserUsecases(db)); + var callId = Guid.NewGuid(); + + //act + try + { + usecases.GetBuildings(callId); + + //assert + Assert.Fail("No exception thrown"); } - [Test] - public void UpdateBuilding_WhenBuildingNameDoesAlreadyExist_ShouldThrowArgumentInvalidException() + catch (Exception e) { - // setup - var context = new DataContext(); + Assert.That(e.Message, Is.EqualTo($"There is no User with id '{callId}'")); + } + + //cleanup + db.Database.EnsureDeleted(); + } + + + [Test] + public void UpdateFloor_WhenFloorDoesNotExist_ShouldThrowEntitiesNotFoundException() + { + // setup + var companyId = Guid.NewGuid(); + var floorId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + var context = new DataContext(); + var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + context.Buildings.Add(building); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + + // act+assert + 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); + + // cleanup + context.Database.EnsureDeleted(); + } + + [Test] + public void UpdateFloor_WhenCompanyIdDoesNotMatchFloor_ShouldThrowInsufficientPermissionException() + { + // setup + var companyId = Guid.NewGuid(); + 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" }; + context.Buildings.Add(building); + var floor = new Floor { FloorId = floorId, FloorName = "testfloor", BuildingId = buildingId, Building = building }; + context.Floors.Add(floor); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + + // act+assert + var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, "Floor Name", null)); + Assert.NotNull(ex); + Assert.That($"'{companyId}' has no access to administrate floor '{floorId}'" == ex.Message); + + // cleanup + context.Database.EnsureDeleted(); + } + + [Test] + public void UpdateFloor_WhenFloorNameIsEmpty_ShouldThrowArgumentInvalidException() + { + // setup + var companyId = Guid.NewGuid(); + var floorId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + var context = new DataContext(); + 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); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + + // act+assert + var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, "", null)); + Assert.NotNull(ex); + Assert.That($"Floor name must not be empty" == ex.Message); + + // cleanup + context.Database.EnsureDeleted(); + } + + [Test] + public void UpdateFloor_WhenBuildingIdDoesNotExist_ShouldThrowEntityNotFoundException() + { + // setup + var companyId = Guid.NewGuid(); + var floorId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + var context = new DataContext(); + 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); + context.SaveChanges(); - var companyId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); + // arrange + var buildingIdNotExisting = Guid.NewGuid(); + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - var buildingName = "testbuilding"; - var company = new Company { CompanyId = companyId, CompanyName = "testcompany" }; - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = buildingName, Location = "testlocation" }; + // act+assert + var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, "testname", buildingIdNotExisting)); + Assert.NotNull(ex); + Assert.That($"Building does not exist with id '{buildingIdNotExisting}'" == ex.Message); - context.Companies.Add(company); - context.Buildings.Add(building); - context.SaveChanges(); + // cleanup + context.Database.EnsureDeleted(); + } - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + [Test] + public void UpdateFloor_WhenCompanyIdDoesNotMatchBuilding_ShouldThrowInsufficientPermissionException() + { + // setup + var companyId = Guid.NewGuid(); + 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 floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testname" }; + context.Buildings.Add(building); + context.Floors.Add(floor); + context.SaveChanges(); - // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, buildingName, null)); - Assert.NotNull(ex); - Assert.AreEqual($"There is already a building named '{buildingName}' in company '{companyId}'", ex.Message); + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - // cleanup - context.Database.EnsureDeleted(); - } - [Test] - public void UpdateBuilding_WhenCompanyIdDoesNotMatchBuilding_ShouldThrowInsufficientPermissionException() - { - // setup - var companyId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = Guid.NewGuid(), BuildingName = "testname", Location = "testlocation" }; - context.Buildings.Add(building); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, "Building Name", "Location")); - Assert.NotNull(ex); - Assert.That($"'{companyId}' has no access to administrate building '{buildingId}'" == ex.Message); - - // cleanup - context.Database.EnsureDeleted(); - } - [Test] - public void UpdateBuilding_WhenAllInputIsValid_ShouldUpdateBuilding() - { - // setup - var context = new DataContext(); - - var companyId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - - var buildingName = "testbuilding"; - var company = new Company { CompanyId = companyId, CompanyName = "testcompany" }; - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = buildingName, Location = "testlocation" }; - - context.Companies.Add(company); - context.Buildings.Add(building); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - var updatedBuildingName = "New Building Name"; - var updatedLocation = "New York"; - // act - var result = resourceUsecases.UpdateBuilding(companyId, buildingId, updatedBuildingName, updatedLocation); - - // assert - Assert.IsNotNull(result); - Assert.AreEqual(buildingId, result); - - var updatedBuilding = context.Buildings.Find(buildingId); - Assert.IsNotNull(updatedBuilding); - Assert.AreEqual(updatedBuildingName, updatedBuilding.BuildingName); - Assert.AreEqual(updatedLocation, updatedBuilding.Location); - - // cleanup - context.Database.EnsureDeleted(); - } - [Test] - public void UpdateBuilding_WhenOnlyLocationIsProvided_ShouldUpdateBuildingLocation() - { - // setup - var companyId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; - context.Buildings.Add(building); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - var newLocation = "newlocation"; - - // act - var buildingIdReturned = resourceUsecases.UpdateBuilding(companyId, buildingId, null, newLocation); - - // assert - var updatedBuilding = context.Buildings.SingleOrDefault(b => b.BuildingId == buildingId); - Assert.NotNull(updatedBuilding); - Assert.That(updatedBuilding.Location == newLocation); - Assert.That(buildingIdReturned == buildingId); - - // cleanup - context.Database.EnsureDeleted(); - } - [Test] - public void UpdateBuilding_WhenOnlyBuildingNameIsProvided_ShouldUpdateBuildingName() - { - // setup - var context = new DataContext(); - - var companyId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - 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 }; - - context.Companies.Add(company); - context.Buildings.Add(building); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - var updatedBuildingName = "updatedBuildingName"; - - // act - var returnedBuildingId = resourceUsecases.UpdateBuilding(companyId, buildingId, updatedBuildingName, null); - - // assert - Assert.AreEqual(buildingId, returnedBuildingId); - var updatedBuilding = context.Buildings.SingleOrDefault(b => b.BuildingId == buildingId); - Assert.NotNull(updatedBuilding); - Assert.AreEqual(updatedBuildingName, updatedBuilding.BuildingName); - Assert.AreEqual(location, updatedBuilding.Location); - - // cleanup - context.Database.EnsureDeleted(); - } - [Test] - public void UpdateBuilding_WhenNeitherLocationNorBuildingNameIsProvided_ShouldReturnBuildingId() - { - // setup - var companyId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; - context.Buildings.Add(building); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act - var buildingIdReturned = resourceUsecases.UpdateBuilding(companyId, buildingId, null, null); - - // assert - Assert.AreEqual(buildingId, buildingIdReturned); - - // cleanup - context.Database.EnsureDeleted(); - } - [Test] - public void UpdateBuilding_WhenLocationIsEmpty_ShouldThrowArgumentInvalidException() - { - // setup - var companyId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; - context.Buildings.Add(building); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, "Building Name", "")); - Assert.NotNull(ex); - Assert.That($"Location must not be empty" == ex.Message); - - // cleanup - context.Database.EnsureDeleted(); - } - [Test] - public void UpdateBuilding_WhenBuildingNameIsEmpty_ShouldThrowArgumentInvalidException() - { - // setup - var companyId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; - context.Buildings.Add(building); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateBuilding(companyId, buildingId, "", "New York")); - Assert.NotNull(ex); - Assert.That($"Building name must not be empty" == ex.Message); - - // cleanup - context.Database.EnsureDeleted(); - } - [Test] - public void GetBuildings_WhenNoBuildingFound_ShouldReturnAEmptyList() - { - //setup - using var db = new DataContext(); - - var userId = Guid.NewGuid(); - var companyId = 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"); - db.Add(company); - db.Add(user); - db.SaveChanges(); - - //arrange - var logger = new Mock>(); - var usecases = new ResourceUsecases(logger.Object, db, SetupUserUsecases(db)); - - - //act - var result = usecases.GetBuildings(userId); - - //assert - Assert.That(result, Is.Empty); - - //cleanup - db.Database.EnsureDeleted(); - } + // act+assert + var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, "new name", null)); + Assert.NotNull(ex); + Assert.That($"'{companyId}' has no access to administrate floor '{floorId}'" == ex.Message); - [Test] - public void GetBuildings_WhenOneBuildingFound_ShouldReturnAException() - { - //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, SetupUserUsecases(db)); - var callId = Guid.NewGuid(); - - //act - try - { - usecases.GetBuildings(callId); - - //assert - Assert.Fail("No exception thrown"); - } - catch (Exception e) - { - Assert.That(e.Message, Is.EqualTo($"There is no User with id '{callId}'")); - } - - //cleanup - db.Database.EnsureDeleted(); - } + // cleanup + context.Database.EnsureDeleted(); + } + [Test] + public void UpdateFloor_WhenUpdatedBuildingBelongsToDifferentCompany_ShouldThrowInsufficientPermissionException() + { + // setup + var context = new DataContext(); - [Test] - public void UpdateFloor_WhenFloorDoesNotExist_ShouldThrowEntitiesNotFoundException() - { - // setup - var companyId = Guid.NewGuid(); - var floorId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - var context = new DataContext(); - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; - context.Buildings.Add(building); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act+assert - 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); - - // cleanup - context.Database.EnsureDeleted(); - } + var companyId = Guid.NewGuid(); + var floorId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); - [Test] - public void UpdateFloor_WhenCompanyIdDoesNotMatchFloor_ShouldThrowInsufficientPermissionException() - { - // setup - var companyId = Guid.NewGuid(); - 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" }; - context.Buildings.Add(building); - var floor = new Floor { FloorId = floorId, FloorName = "testfloor", BuildingId = buildingId, Building = building }; - context.Floors.Add(floor); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, "Floor Name", null)); - Assert.NotNull(ex); - Assert.That($"'{companyId}' has no access to administrate floor '{floorId}'" == ex.Message); - - // cleanup - context.Database.EnsureDeleted(); - } + 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); - [Test] - public void UpdateFloor_WhenFloorNameIsEmpty_ShouldThrowArgumentInvalidException() - { - // setup - var companyId = Guid.NewGuid(); - var floorId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - var context = new DataContext(); - 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); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, "", null)); - Assert.NotNull(ex); - Assert.That($"Floor name must not be empty" == ex.Message); - - // cleanup - context.Database.EnsureDeleted(); - } + var anotherCompanyId = Guid.NewGuid(); + var building2Id = Guid.NewGuid(); + var building2 = new Building { BuildingId = building2Id, CompanyId = anotherCompanyId, BuildingName = "testbuilding2", Location = "testlocation" }; + context.Buildings.Add(building2); + context.SaveChanges(); - [Test] - public void UpdateFloor_WhenBuildingIdDoesNotExist_ShouldThrowEntityNotFoundException() - { - // setup - var companyId = Guid.NewGuid(); - var floorId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - var context = new DataContext(); - 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); - context.SaveChanges(); - - // arrange - var buildingIdNotExisting = Guid.NewGuid(); - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, "testname", buildingIdNotExisting)); - Assert.NotNull(ex); - Assert.That($"Building does not exist with id '{buildingIdNotExisting}'" == ex.Message); - - // cleanup - context.Database.EnsureDeleted(); - } + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - [Test] - public void UpdateFloor_WhenCompanyIdDoesNotMatchBuilding_ShouldThrowInsufficientPermissionException() - { - // setup - var companyId = Guid.NewGuid(); - 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 floor = new Floor { FloorId = floorId, BuildingId = buildingId, FloorName = "testname" }; - context.Buildings.Add(building); - context.Floors.Add(floor); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, "new name", null)); - Assert.NotNull(ex); - Assert.That($"'{companyId}' has no access to administrate floor '{floorId}'" == ex.Message); - - // cleanup - context.Database.EnsureDeleted(); - } + // act+assert + var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, null, building2Id)); + Assert.NotNull(ex); + Assert.AreEqual($"'{companyId}' has no access to move a floor to building '{building2Id}'", ex.Message); - [Test] - public void UpdateFloor_WhenUpdatedBuildingBelongsToDifferentCompany_ShouldThrowInsufficientPermissionException() - { - // setup - var context = new DataContext(); - - var companyId = Guid.NewGuid(); - var floorId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - - 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); - - var anotherCompanyId = Guid.NewGuid(); - var building2Id = Guid.NewGuid(); - var building2 = new Building { BuildingId = building2Id, CompanyId = anotherCompanyId, BuildingName = "testbuilding2", Location = "testlocation" }; - context.Buildings.Add(building2); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, null, building2Id)); - Assert.NotNull(ex); - Assert.AreEqual($"'{companyId}' has no access to move a floor to building '{building2Id}'", ex.Message); - - // cleanup - context.Database.EnsureDeleted(); - } + // cleanup + context.Database.EnsureDeleted(); + } - [Test] - public void UpdateFloor_WhenUpdatedBuildingNameAlreadyExists_ShouldThrowArgumentInvalidException() - { - // setup - var context = new DataContext(); - - var companyId = Guid.NewGuid(); - var floorId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - var floorName = "testfloor"; - var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", 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" }; - context.Buildings.Add(building2); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, floorName, null)); - Assert.NotNull(ex); - Assert.AreEqual($"There is already a floor named '{floorName}' in building '{buildingId}'", ex.Message); - - // cleanup - context.Database.EnsureDeleted(); - } + [Test] + public void UpdateFloor_WhenUpdatedBuildingNameAlreadyExists_ShouldThrowArgumentInvalidException() + { + // setup + var context = new DataContext(); - [Test] - public void UpdateFloor_WhenAllInputIsValid_ShouldUpdateFloorAndReturnFloorId() - { - // setup - var companyId = Guid.NewGuid(); - var floorId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - var context = new DataContext(); - 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" }; - context.Buildings.Add(building2); - var floor = new Floor { FloorId = floorId, FloorName = "testfloor", BuildingId = buildingId, Building = building }; - context.Floors.Add(floor); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - var newFloorName = "new name"; - - // act - var returnedFloorId = resourceUsecases.UpdateFloor(companyId, floorId, newFloorName, building2Id); - var updatedFloor = context.Floors.SingleOrDefault(f => f.FloorId == floorId); - - // assert - Assert.That(floorId == returnedFloorId); - Assert.NotNull(updatedFloor); - Assert.That(newFloorName == updatedFloor.FloorName); - Assert.That(building2Id == updatedFloor.BuildingId); - - // cleanup - context.Database.EnsureDeleted(); - } + var companyId = Guid.NewGuid(); + var floorId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + var floorName = "testfloor"; + var building = new Building { BuildingId = buildingId, CompanyId = companyId, BuildingName = "testname", Location = "testlocation" }; + var floor = new Floor { FloorId = floorId, FloorName = floorName, BuildingId = buildingId, Building = building }; + context.Buildings.Add(building); + context.Floors.Add(floor); - [Test] - public void UpdateFloor_WhenFloorNameAlreadyExistsInUpdatedBuilding_ShouldThrowArgumentInvalidException() - { - // setup - var context = new DataContext(); - - var companyId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - var floorId = Guid.NewGuid(); - var floorName = "testfloor"; - - 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 building2 = new Building { BuildingId = building2Id, CompanyId = companyId, BuildingName = "testbuilding2", Location = "testlocation" }; - var floor2 = new Floor { FloorId = floor2Id, FloorName = floorName, BuildingId = building2Id }; - - context.Buildings.Add(building2); - context.Floors.Add(floor2); - - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act+assert - var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, floorName, building2Id)); - Assert.NotNull(ex); - Assert.AreEqual($"You cant move floor '{floorId}' to building '{building2Id}'. In building '{building2Id}' already exists a floor called '{floorName}'", ex.Message); - - // cleanup - context.Database.EnsureDeleted(); - } + var anotherCompanyId = Guid.NewGuid(); + var building2Id = Guid.NewGuid(); + var building2 = new Building { BuildingId = building2Id, CompanyId = anotherCompanyId, BuildingName = "testbuilding2", Location = "testlocation" }; + context.Buildings.Add(building2); + context.SaveChanges(); - [Test] - public void UpdateFloor_WhenOnlyFloorNameIsProvided_ShouldUpdateFloorNameAndReturnFloorId() - { - // setup - var companyId = Guid.NewGuid(); - var floorId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - var context = new DataContext(); - 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 }; - context.Floors.Add(floor); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - var newFloorName = "newFloorName"; - - // act - var returnedFloorId = resourceUsecases.UpdateFloor(companyId, floorId, newFloorName, null); - var updatedFloor = context.Floors.SingleOrDefault(f => f.FloorId == floorId); - - // assert - Assert.That(floorId == returnedFloorId); - Assert.NotNull(updatedFloor); - Assert.That(buildingId == updatedFloor.BuildingId); - Assert.That(newFloorName == updatedFloor.FloorName); - - // cleanup - context.Database.EnsureDeleted(); - } + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - [Test] - public void UpdateFloor_WhenOnlyBuildingIdIsProvided_ShouldUpdateFloorBuildingAndReturnFloorId() - { - // setup - var companyId = Guid.NewGuid(); - var floorId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - var context = new DataContext(); - 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" }; - context.Buildings.Add(building2); - var floorName = "testfloor"; - var floor = new Floor { FloorId = floorId, FloorName = floorName, BuildingId = buildingId, Building = building }; - context.Floors.Add(floor); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act - var returnedFloorId = resourceUsecases.UpdateFloor(companyId, floorId, null, building2Id); - var updatedFloor = context.Floors.SingleOrDefault(f => f.FloorId == floorId); - - // assert - Assert.That(floorId == returnedFloorId); - Assert.NotNull(updatedFloor); - Assert.That(building2Id == updatedFloor.BuildingId); - Assert.That(floorName == updatedFloor.FloorName); - - // cleanup - context.Database.EnsureDeleted(); - } + // act+assert + var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, floorName, null)); + Assert.NotNull(ex); + Assert.AreEqual($"There is already a floor named '{floorName}' in building '{buildingId}'", ex.Message); - [Test] - public void UpdateFloor_WhenNeitherFloorNameNorBuildingIdIsProvided_ShouldReturnFloorId() - { - // setup - var companyId = Guid.NewGuid(); - var floorId = Guid.NewGuid(); - var buildingId = Guid.NewGuid(); - var context = new DataContext(); - 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 }; - context.Floors.Add(floor); - context.SaveChanges(); - - // arrange - var userLogger = new Mock>(); - var userUsecases = new UserUsecases(userLogger.Object, context); - var resourceLogger = new Mock>(); - var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); - - // act - var returnedFloorId = resourceUsecases.UpdateFloor(companyId, floorId, null, null); - var updatedFloor = context.Floors.SingleOrDefault(f => f.FloorId == floorId); - - // assert - Assert.That(floorId == returnedFloorId); - Assert.NotNull(updatedFloor); - Assert.That(buildingId == updatedFloor.BuildingId); - Assert.That(floorName == updatedFloor.FloorName); - - // cleanup - context.Database.EnsureDeleted(); - } + // cleanup + context.Database.EnsureDeleted(); + } + + [Test] + public void UpdateFloor_WhenAllInputIsValid_ShouldUpdateFloorAndReturnFloorId() + { + // setup + var companyId = Guid.NewGuid(); + var floorId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + var context = new DataContext(); + 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" }; + context.Buildings.Add(building2); + var floor = new Floor { FloorId = floorId, FloorName = "testfloor", BuildingId = buildingId, Building = building }; + context.Floors.Add(floor); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var newFloorName = "new name"; + + // act + var returnedFloorId = resourceUsecases.UpdateFloor(companyId, floorId, newFloorName, building2Id); + var updatedFloor = context.Floors.SingleOrDefault(f => f.FloorId == floorId); + + // assert + Assert.That(floorId == returnedFloorId); + Assert.NotNull(updatedFloor); + Assert.That(newFloorName == updatedFloor.FloorName); + Assert.That(building2Id == updatedFloor.BuildingId); + + // cleanup + context.Database.EnsureDeleted(); + } + + [Test] + public void UpdateFloor_WhenFloorNameAlreadyExistsInUpdatedBuilding_ShouldThrowArgumentInvalidException() + { + // setup + var context = new DataContext(); + + var companyId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + var floorId = Guid.NewGuid(); + var floorName = "testfloor"; + + 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 building2 = new Building { BuildingId = building2Id, CompanyId = companyId, BuildingName = "testbuilding2", Location = "testlocation" }; + var floor2 = new Floor { FloorId = floor2Id, FloorName = floorName, BuildingId = building2Id }; + + context.Buildings.Add(building2); + context.Floors.Add(floor2); + + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + + // act+assert + var ex = Assert.Throws(() => resourceUsecases.UpdateFloor(companyId, floorId, floorName, building2Id)); + Assert.NotNull(ex); + Assert.AreEqual($"You cant move floor '{floorId}' to building '{building2Id}'. In building '{building2Id}' already exists a floor called '{floorName}'", ex.Message); + + // cleanup + context.Database.EnsureDeleted(); + } + + [Test] + public void UpdateFloor_WhenOnlyFloorNameIsProvided_ShouldUpdateFloorNameAndReturnFloorId() + { + // setup + var companyId = Guid.NewGuid(); + var floorId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + var context = new DataContext(); + 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 }; + context.Floors.Add(floor); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + var newFloorName = "newFloorName"; + + // act + var returnedFloorId = resourceUsecases.UpdateFloor(companyId, floorId, newFloorName, null); + var updatedFloor = context.Floors.SingleOrDefault(f => f.FloorId == floorId); + + // assert + Assert.That(floorId == returnedFloorId); + Assert.NotNull(updatedFloor); + Assert.That(buildingId == updatedFloor.BuildingId); + Assert.That(newFloorName == updatedFloor.FloorName); + + // cleanup + context.Database.EnsureDeleted(); + } + + [Test] + public void UpdateFloor_WhenOnlyBuildingIdIsProvided_ShouldUpdateFloorBuildingAndReturnFloorId() + { + // setup + var companyId = Guid.NewGuid(); + var floorId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + var context = new DataContext(); + 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" }; + context.Buildings.Add(building2); + var floorName = "testfloor"; + var floor = new Floor { FloorId = floorId, FloorName = floorName, BuildingId = buildingId, Building = building }; + context.Floors.Add(floor); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + + // act + var returnedFloorId = resourceUsecases.UpdateFloor(companyId, floorId, null, building2Id); + var updatedFloor = context.Floors.SingleOrDefault(f => f.FloorId == floorId); + + // assert + Assert.That(floorId == returnedFloorId); + Assert.NotNull(updatedFloor); + Assert.That(building2Id == updatedFloor.BuildingId); + Assert.That(floorName == updatedFloor.FloorName); + + // cleanup + context.Database.EnsureDeleted(); + } + + [Test] + public void UpdateFloor_WhenNeitherFloorNameNorBuildingIdIsProvided_ShouldReturnFloorId() + { + // setup + var companyId = Guid.NewGuid(); + var floorId = Guid.NewGuid(); + var buildingId = Guid.NewGuid(); + var context = new DataContext(); + 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 }; + context.Floors.Add(floor); + context.SaveChanges(); + + // arrange + var userLogger = new Mock>(); + var userUsecases = new UserUsecases(userLogger.Object, context); + var resourceLogger = new Mock>(); + var resourceUsecases = new ResourceUsecases(resourceLogger.Object, context, userUsecases); + + // act + var returnedFloorId = resourceUsecases.UpdateFloor(companyId, floorId, null, null); + var updatedFloor = context.Floors.SingleOrDefault(f => f.FloorId == floorId); + + // assert + Assert.That(floorId == returnedFloorId); + Assert.NotNull(updatedFloor); + Assert.That(buildingId == updatedFloor.BuildingId); + Assert.That(floorName == updatedFloor.FloorName); + + // cleanup + context.Database.EnsureDeleted(); + } [Test] public void UpdateRoom_WhenRoomDoesNotExist_ShouldThrowEntityNotFoundException() @@ -799,7 +799,7 @@ public void UpdateRoom_WhenRoomDoesNotExist_ShouldThrowEntityNotFoundException() // cleanup context.Database.EnsureDeleted(); } - + [Test] public void UpdateRoom_WhenCompanyHasInsufficientPermission_ShouldThrowInsufficientPermissionException() {