refactor: optimize crud services

fix: data shaping removes fields from objects
This commit is contained in:
cuqmbr 2022-11-30 16:38:30 +02:00
parent 280d883213
commit 1ba0867390
45 changed files with 569 additions and 911 deletions

View File

@ -24,7 +24,7 @@ public class AddressController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return CreatedAtAction(nameof(GetAddress), new {id = result.address.Id}, result.address); return CreatedAtAction(nameof(GetAddress), new {id = result.address.Id}, result.address);
@ -37,7 +37,7 @@ public class AddressController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata)); Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata));
@ -48,16 +48,11 @@ public class AddressController : ControllerBase
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<IActionResult> GetAddress(int id, [FromQuery] string? fields) public async Task<IActionResult> GetAddress(int id, [FromQuery] string? fields)
{ {
if (!await _addressManagementService.IsAddressExists(id))
{
return NotFound();
}
var result = await _addressManagementService.GetAddress(id, fields); var result = await _addressManagementService.GetAddress(id, fields);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.address); return Ok(result.address);
@ -66,16 +61,11 @@ public class AddressController : ControllerBase
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> UpdateAddress(int id, UpdateAddressDto address) public async Task<IActionResult> UpdateAddress(int id, UpdateAddressDto address)
{ {
if (id != address.Id)
{
return BadRequest();
}
var result = await _addressManagementService.UpdateAddress(address); var result = await _addressManagementService.UpdateAddress(address);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.address); return Ok(result.address);
@ -84,16 +74,11 @@ public class AddressController : ControllerBase
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteAddress(int id) public async Task<IActionResult> DeleteAddress(int id)
{ {
if (!await _addressManagementService.IsAddressExists(id))
{
return NotFound();
}
var result = await _addressManagementService.DeleteAddress(id); var result = await _addressManagementService.DeleteAddress(id);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return NoContent(); return NoContent();

View File

@ -24,7 +24,7 @@ public class CityController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return CreatedAtAction(nameof(GetCity), new {id = result.city.Id}, result.city); return CreatedAtAction(nameof(GetCity), new {id = result.city.Id}, result.city);
@ -37,7 +37,7 @@ public class CityController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata)); Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata));
@ -48,16 +48,11 @@ public class CityController : ControllerBase
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<IActionResult> GetCity(int id, [FromQuery] string? fields) public async Task<IActionResult> GetCity(int id, [FromQuery] string? fields)
{ {
if (!await _cityManagementService.IsCityExists(id))
{
return NotFound();
}
var result = await _cityManagementService.GetCity(id, fields); var result = await _cityManagementService.GetCity(id, fields);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.city); return Ok(result.city);
@ -75,7 +70,7 @@ public class CityController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.city); return Ok(result.city);
@ -84,16 +79,11 @@ public class CityController : ControllerBase
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteCountry(int id) public async Task<IActionResult> DeleteCountry(int id)
{ {
if (!await _cityManagementService.IsCityExists(id))
{
return NotFound();
}
var result = await _cityManagementService.DeleteCity(id); var result = await _cityManagementService.DeleteCity(id);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return NoContent(); return NoContent();

View File

@ -24,7 +24,7 @@ public class CompanyController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return CreatedAtAction(nameof(GetCompany), new {id = result.company.Id}, result.company); return CreatedAtAction(nameof(GetCompany), new {id = result.company.Id}, result.company);
@ -37,7 +37,7 @@ public class CompanyController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata)); Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata));
@ -48,16 +48,11 @@ public class CompanyController : ControllerBase
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<IActionResult> GetCompany(int id, [FromQuery] string? fields) public async Task<IActionResult> GetCompany(int id, [FromQuery] string? fields)
{ {
if (!await _companyManagementService.IsCompanyExists(id))
{
return NotFound();
}
var result = await _companyManagementService.GetCompany(id, fields); var result = await _companyManagementService.GetCompany(id, fields);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.company); return Ok(result.company);
@ -66,16 +61,11 @@ public class CompanyController : ControllerBase
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> UpdateCompany(int id, UpdateCompanyDto company) public async Task<IActionResult> UpdateCompany(int id, UpdateCompanyDto company)
{ {
if (id != company.Id)
{
return BadRequest();
}
var result = await _companyManagementService.UpdateCompany(company); var result = await _companyManagementService.UpdateCompany(company);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.company); return Ok(result.company);
@ -84,16 +74,11 @@ public class CompanyController : ControllerBase
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteCompany(int id) public async Task<IActionResult> DeleteCompany(int id)
{ {
if (!await _companyManagementService.IsCompanyExists(id))
{
return NotFound();
}
var result = await _companyManagementService.DeleteCompany(id); var result = await _companyManagementService.DeleteCompany(id);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return NoContent(); return NoContent();

View File

@ -24,7 +24,7 @@ public class CountryController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return CreatedAtAction(nameof(GetCountry), new {id = result.country.Id}, result.country); return CreatedAtAction(nameof(GetCountry), new {id = result.country.Id}, result.country);
@ -37,7 +37,7 @@ public class CountryController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata)); Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata));
@ -48,16 +48,11 @@ public class CountryController : ControllerBase
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<IActionResult> GetCountry(int id, [FromQuery] string? fields) public async Task<IActionResult> GetCountry(int id, [FromQuery] string? fields)
{ {
if (!await _countryManagementService.IsCountryExists(id))
{
return NotFound();
}
var result = await _countryManagementService.GetCountry(id, fields); var result = await _countryManagementService.GetCountry(id, fields);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.country); return Ok(result.country);
@ -66,16 +61,11 @@ public class CountryController : ControllerBase
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> UpdateCountry(int id, UpdateCountryDto country) public async Task<IActionResult> UpdateCountry(int id, UpdateCountryDto country)
{ {
if (id != country.Id)
{
return BadRequest();
}
var result = await _countryManagementService.UpdateCountry(country); var result = await _countryManagementService.UpdateCountry(country);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.country); return Ok(result.country);
@ -84,16 +74,11 @@ public class CountryController : ControllerBase
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteCountry(int id) public async Task<IActionResult> DeleteCountry(int id)
{ {
if (!await _countryManagementService.IsCountryExists(id))
{
return NotFound();
}
var result = await _countryManagementService.DeleteCountry(id); var result = await _countryManagementService.DeleteCountry(id);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return NoContent(); return NoContent();

View File

@ -24,7 +24,7 @@ public class ReviewController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return CreatedAtAction(nameof(GetReview), new {id = result.review.Id}, result.review); return CreatedAtAction(nameof(GetReview), new {id = result.review.Id}, result.review);
@ -37,7 +37,7 @@ public class ReviewController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata)); Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata));
@ -48,16 +48,11 @@ public class ReviewController : ControllerBase
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<IActionResult> GetReview(int id, [FromQuery] string? fields) public async Task<IActionResult> GetReview(int id, [FromQuery] string? fields)
{ {
if (!await _reviewManagementService.IsReviewExists(id))
{
return NotFound();
}
var result = await _reviewManagementService.GetReview(id, fields); var result = await _reviewManagementService.GetReview(id, fields);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.review); return Ok(result.review);
@ -66,16 +61,11 @@ public class ReviewController : ControllerBase
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> UpdateReview(int id, UpdateReviewDto review) public async Task<IActionResult> UpdateReview(int id, UpdateReviewDto review)
{ {
if (id != review.Id)
{
return BadRequest();
}
var result = await _reviewManagementService.UpdateReview(review); var result = await _reviewManagementService.UpdateReview(review);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.review); return Ok(result.review);
@ -84,16 +74,11 @@ public class ReviewController : ControllerBase
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteReview(int id) public async Task<IActionResult> DeleteReview(int id)
{ {
if (!await _reviewManagementService.IsReviewExists(id))
{
return NotFound();
}
var result = await _reviewManagementService.DeleteReview(id); var result = await _reviewManagementService.DeleteReview(id);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return NoContent(); return NoContent();

View File

@ -24,7 +24,7 @@ public class RouteAddressController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return CreatedAtAction(nameof(GetRouteAddress), new {id = result.routeAddress.Id}, result.routeAddress); return CreatedAtAction(nameof(GetRouteAddress), new {id = result.routeAddress.Id}, result.routeAddress);
@ -37,7 +37,7 @@ public class RouteAddressController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata)); Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata));
@ -48,16 +48,11 @@ public class RouteAddressController : ControllerBase
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<IActionResult> GetRouteAddress(int id, [FromQuery] string? fields) public async Task<IActionResult> GetRouteAddress(int id, [FromQuery] string? fields)
{ {
if (!await _routeAddressManagementService.IsRouteAddressExists(id))
{
return NotFound();
}
var result = await _routeAddressManagementService.GetRouteAddress(id, fields); var result = await _routeAddressManagementService.GetRouteAddress(id, fields);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.routeAddress); return Ok(result.routeAddress);
@ -66,16 +61,11 @@ public class RouteAddressController : ControllerBase
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> UpdateRouteAddress(int id, UpdateRouteAddressDto routeAddress) public async Task<IActionResult> UpdateRouteAddress(int id, UpdateRouteAddressDto routeAddress)
{ {
if (id != routeAddress.Id)
{
return BadRequest();
}
var result = await _routeAddressManagementService.UpdateRouteAddress(routeAddress); var result = await _routeAddressManagementService.UpdateRouteAddress(routeAddress);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.routeAddress); return Ok(result.routeAddress);
@ -84,16 +74,11 @@ public class RouteAddressController : ControllerBase
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteRouteAddress(int id) public async Task<IActionResult> DeleteRouteAddress(int id)
{ {
if (!await _routeAddressManagementService.IsRouteAddressExists(id))
{
return NotFound();
}
var result = await _routeAddressManagementService.DeleteRouteAddress(id); var result = await _routeAddressManagementService.DeleteRouteAddress(id);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return NoContent(); return NoContent();

View File

@ -24,7 +24,7 @@ public class RouteController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return CreatedAtAction(nameof(GetRoute), new {id = result.route.Id}, result.route); return CreatedAtAction(nameof(GetRoute), new {id = result.route.Id}, result.route);
@ -50,7 +50,7 @@ public class RouteController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata)); Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata));
@ -85,7 +85,7 @@ public class RouteController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.route); return Ok(result.route);
@ -103,7 +103,7 @@ public class RouteController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.route); return Ok(result.route);
@ -121,7 +121,7 @@ public class RouteController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.route); return Ok(result.route);
@ -139,7 +139,7 @@ public class RouteController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return NoContent(); return NoContent();

View File

@ -24,7 +24,7 @@ public class StateController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return CreatedAtAction(nameof(GetState), new {id = result.state.Id}, result.state); return CreatedAtAction(nameof(GetState), new {id = result.state.Id}, result.state);
@ -37,7 +37,7 @@ public class StateController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata)); Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata));
@ -48,16 +48,11 @@ public class StateController : ControllerBase
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<IActionResult> GetState(int id, [FromQuery] string? fields) public async Task<IActionResult> GetState(int id, [FromQuery] string? fields)
{ {
if (!await _stateManagementService.IsStateExists(id))
{
return NotFound();
}
var result = await _stateManagementService.GetState(id, fields); var result = await _stateManagementService.GetState(id, fields);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.state); return Ok(result.state);
@ -75,7 +70,7 @@ public class StateController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.state); return Ok(result.state);
@ -84,16 +79,11 @@ public class StateController : ControllerBase
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteState(int id) public async Task<IActionResult> DeleteState(int id)
{ {
if (!await _stateManagementService.IsStateExists(id))
{
return NotFound();
}
var result = await _stateManagementService.DeleteState(id); var result = await _stateManagementService.DeleteState(id);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return NoContent(); return NoContent();

View File

@ -24,7 +24,7 @@ public class TicketController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return CreatedAtAction(nameof(GetTicket), new {id = result.ticket.Id}, result.ticket); return CreatedAtAction(nameof(GetTicket), new {id = result.ticket.Id}, result.ticket);
@ -37,7 +37,7 @@ public class TicketController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata)); Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata));
@ -48,16 +48,11 @@ public class TicketController : ControllerBase
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<IActionResult> GetTicket(int id, [FromQuery] string? fields) public async Task<IActionResult> GetTicket(int id, [FromQuery] string? fields)
{ {
if (!await _ticketManagementService.IsTicketExists(id))
{
return NotFound();
}
var result = await _ticketManagementService.GetTicket(id, fields); var result = await _ticketManagementService.GetTicket(id, fields);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.ticket); return Ok(result.ticket);
@ -66,16 +61,11 @@ public class TicketController : ControllerBase
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> UpdateTicket(int id, UpdateTicketDto ticket) public async Task<IActionResult> UpdateTicket(int id, UpdateTicketDto ticket)
{ {
if (id != ticket.Id)
{
return BadRequest();
}
var result = await _ticketManagementService.UpdateTicket(ticket); var result = await _ticketManagementService.UpdateTicket(ticket);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.ticket); return Ok(result.ticket);
@ -84,16 +74,11 @@ public class TicketController : ControllerBase
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteTicket(int id) public async Task<IActionResult> DeleteTicket(int id)
{ {
if (!await _ticketManagementService.IsTicketExists(id))
{
return NotFound();
}
var result = await _ticketManagementService.DeleteTicket(id); var result = await _ticketManagementService.DeleteTicket(id);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return NoContent(); return NoContent();

View File

@ -24,7 +24,7 @@ public class VehicleController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return CreatedAtAction(nameof(GetVehicle), new {id = result.vehicle.Id}, result.vehicle); return CreatedAtAction(nameof(GetVehicle), new {id = result.vehicle.Id}, result.vehicle);
@ -37,7 +37,7 @@ public class VehicleController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata)); Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata));
@ -48,16 +48,11 @@ public class VehicleController : ControllerBase
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<IActionResult> GetVehicle(int id, [FromQuery] string? fields) public async Task<IActionResult> GetVehicle(int id, [FromQuery] string? fields)
{ {
if (!await _vehicleManagementService.IsVehicleExists(id))
{
return NotFound();
}
var result = await _vehicleManagementService.GetVehicle(id, fields); var result = await _vehicleManagementService.GetVehicle(id, fields);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.vehicle); return Ok(result.vehicle);
@ -66,16 +61,11 @@ public class VehicleController : ControllerBase
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> UpdateVehicle(int id, UpdateVehicleDto vehicle) public async Task<IActionResult> UpdateVehicle(int id, UpdateVehicleDto vehicle)
{ {
if (id != vehicle.Id)
{
return BadRequest();
}
var result = await _vehicleManagementService.UpdateVehicle(vehicle); var result = await _vehicleManagementService.UpdateVehicle(vehicle);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.vehicle); return Ok(result.vehicle);
@ -84,16 +74,11 @@ public class VehicleController : ControllerBase
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteVehicle(int id) public async Task<IActionResult> DeleteVehicle(int id)
{ {
if (!await _vehicleManagementService.IsVehicleExists(id))
{
return NotFound();
}
var result = await _vehicleManagementService.DeleteVehicle(id); var result = await _vehicleManagementService.DeleteVehicle(id);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return NoContent(); return NoContent();

View File

@ -25,7 +25,7 @@ public class VehicleEnrollmentController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return CreatedAtAction(nameof(GetEnrollment), new {id = result.enrollment.Id}, result.enrollment); return CreatedAtAction(nameof(GetEnrollment), new {id = result.enrollment.Id}, result.enrollment);
@ -38,7 +38,7 @@ public class VehicleEnrollmentController : ControllerBase
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata)); Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(result.pagingMetadata));
@ -49,16 +49,11 @@ public class VehicleEnrollmentController : ControllerBase
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<IActionResult> GetEnrollment(int id, [FromQuery] string? fields) public async Task<IActionResult> GetEnrollment(int id, [FromQuery] string? fields)
{ {
if (!await _vehicleEnrollmentManagementService.IsEnrollmentExists(id))
{
return NotFound();
}
var result = await _vehicleEnrollmentManagementService.GetEnrollment(id, fields); var result = await _vehicleEnrollmentManagementService.GetEnrollment(id, fields);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.enrollment); return Ok(result.enrollment);
@ -67,16 +62,11 @@ public class VehicleEnrollmentController : ControllerBase
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> UpdateVehicle(int id, UpdateVehicleEnrollmentDto enrollment) public async Task<IActionResult> UpdateVehicle(int id, UpdateVehicleEnrollmentDto enrollment)
{ {
if (id != enrollment.Id)
{
return BadRequest();
}
var result = await _vehicleEnrollmentManagementService.UpdateEnrollment(enrollment); var result = await _vehicleEnrollmentManagementService.UpdateEnrollment(enrollment);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return Ok(result.enrollment); return Ok(result.enrollment);
@ -85,16 +75,11 @@ public class VehicleEnrollmentController : ControllerBase
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteEnrollment(int id) public async Task<IActionResult> DeleteEnrollment(int id)
{ {
if (!await _vehicleEnrollmentManagementService.IsEnrollmentExists(id))
{
return NotFound();
}
var result = await _vehicleEnrollmentManagementService.DeleteEnrollment(id); var result = await _vehicleEnrollmentManagementService.DeleteEnrollment(id);
if (!result.isSucceed) if (!result.isSucceed)
{ {
return BadRequest(result.message); return result.actionResult;
} }
return NoContent(); return NoContent();

View File

@ -105,41 +105,20 @@ builder.Services.AddScoped<IVehicleEnrollmentManagementService, VehicleEnrollmen
builder.Services.AddScoped<IRouteManagementService, RouteManagementService>(); builder.Services.AddScoped<IRouteManagementService, RouteManagementService>();
builder.Services.AddScoped<IRouteAddressManagementService, RouteAddressManagementService>(); builder.Services.AddScoped<IRouteAddressManagementService, RouteAddressManagementService>();
builder.Services.AddScoped<IStatisticsService, StatisticsService>();
builder.Services.AddScoped<IReportService, ReportService>();
builder.Services.AddScoped<ISortHelper<Country>, SortHelper<Country>>();
builder.Services.AddScoped<ISortHelper<State>, SortHelper<State>>();
builder.Services.AddScoped<ISortHelper<City>, SortHelper<City>>();
builder.Services.AddScoped<ISortHelper<Address>, SortHelper<Address>>();
builder.Services.AddScoped<ISortHelper<Ticket>, SortHelper<Ticket>>();
builder.Services.AddScoped<ISortHelper<Review>, SortHelper<Review>>();
builder.Services.AddScoped<ISortHelper<Company>, SortHelper<Company>>();
builder.Services.AddScoped<ISortHelper<Vehicle>, SortHelper<Vehicle>>();
builder.Services.AddScoped<ISortHelper<VehicleEnrollment>, SortHelper<VehicleEnrollment>>();
builder.Services.AddScoped<ISortHelper<Route>, SortHelper<Route>>();
builder.Services.AddScoped<ISortHelper<RouteAddress>, SortHelper<RouteAddress>>();
builder.Services.AddScoped<IDataShaper<User>, DataShaper<User>>();
builder.Services.AddScoped<IDataShaper<Country>, DataShaper<Country>>();
builder.Services.AddScoped<IDataShaper<State>, DataShaper<State>>();
builder.Services.AddScoped<IDataShaper<City>, DataShaper<City>>();
builder.Services.AddScoped<IDataShaper<Address>, DataShaper<Address>>();
builder.Services.AddScoped<IDataShaper<Ticket>, DataShaper<Ticket>>();
builder.Services.AddScoped<IDataShaper<Review>, DataShaper<Review>>();
builder.Services.AddScoped<IDataShaper<Company>, DataShaper<Company>>();
builder.Services.AddScoped<IDataShaper<Vehicle>, DataShaper<Vehicle>>();
builder.Services.AddScoped<IDataShaper<VehicleEnrollment>, DataShaper<VehicleEnrollment>>();
builder.Services.AddScoped<IDataShaper<Route>, DataShaper<Route>>();
builder.Services.AddScoped<IDataShaper<RouteAddress>, DataShaper<RouteAddress>>();
builder.Services.AddScoped<ISortHelper<ExpandoObject>, SortHelper<ExpandoObject>>(); builder.Services.AddScoped<ISortHelper<ExpandoObject>, SortHelper<ExpandoObject>>();
builder.Services.AddScoped<IDataShaper<UserDto>, DataShaper<UserDto>>(); builder.Services.AddScoped<IDataShaper<CountryDto>, DataShaper<CountryDto>>();
builder.Services.AddScoped<IDataShaper<CompanyDto>, DataShaper<CompanyDto>>(); builder.Services.AddScoped<IDataShaper<StateDto>, DataShaper<StateDto>>();
builder.Services.AddScoped<IDataShaper<CityDto>, DataShaper<CityDto>>();
builder.Services.AddScoped<IDataShaper<AddressDto>, DataShaper<AddressDto>>(); builder.Services.AddScoped<IDataShaper<AddressDto>, DataShaper<AddressDto>>();
builder.Services.AddScoped<IDataShaper<TicketDto>, DataShaper<TicketDto>>();
builder.Services.AddScoped<IDataShaper<ReviewDto>, DataShaper<ReviewDto>>();
builder.Services.AddScoped<IDataShaper<CompanyDto>, DataShaper<CompanyDto>>();
builder.Services.AddScoped<IDataShaper<VehicleDto>, DataShaper<VehicleDto>>();
builder.Services.AddScoped<IDataShaper<VehicleEnrollmentDto>, DataShaper<VehicleEnrollmentDto>>();
builder.Services.AddScoped<IDataShaper<RouteDto>, DataShaper<RouteDto>>(); builder.Services.AddScoped<IDataShaper<RouteDto>, DataShaper<RouteDto>>();
builder.Services.AddScoped<IDataShaper<RouteWithAddressesDto>, DataShaper<RouteWithAddressesDto>>(); builder.Services.AddScoped<IDataShaper<RouteWithAddressesDto>, DataShaper<RouteWithAddressesDto>>();
builder.Services.AddScoped<IDataShaper<RouteAddressDto>, DataShaper<RouteAddressDto>>();
builder.Services.AddScoped<IPager<ExpandoObject>, Pager<ExpandoObject>>(); builder.Services.AddScoped<IPager<ExpandoObject>, Pager<ExpandoObject>>();

View File

@ -1,4 +1,6 @@
using System.Dynamic;
using AutoMapper; using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Server.Data; using Server.Data;
using Server.Helpers; using Server.Helpers;
@ -13,31 +15,33 @@ public class AddressManagementService : IAddressManagementService
{ {
private readonly ApplicationDbContext _dbContext; private readonly ApplicationDbContext _dbContext;
private readonly IMapper _mapper; private readonly IMapper _mapper;
private readonly ISortHelper<Address> _addressSortHelper; private readonly ISortHelper<ExpandoObject> _addressSortHelper;
private readonly IDataShaper<Address> _addressDataShaper; private readonly IDataShaper<AddressDto> _addressDataShaper;
private readonly IPager<ExpandoObject> _pager;
public AddressManagementService(ApplicationDbContext dbContext, public AddressManagementService(ApplicationDbContext dbContext,
IMapper mapper, ISortHelper<Address> addressSortHelper, IMapper mapper, ISortHelper<ExpandoObject> addressSortHelper,
IDataShaper<Address> addressDataShaper) IDataShaper<AddressDto> addressDataShaper, IPager<ExpandoObject> pager)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_mapper = mapper; _mapper = mapper;
_addressSortHelper = addressSortHelper; _addressSortHelper = addressSortHelper;
_addressDataShaper = addressDataShaper; _addressDataShaper = addressDataShaper;
_pager = pager;
} }
public async Task<(bool isSucceed, string message, AddressDto address)> AddAddress(CreateAddressDto createAddressDto) public async Task<(bool isSucceed, IActionResult? actionResult, AddressDto address)> AddAddress(CreateAddressDto createAddressDto)
{ {
var address = _mapper.Map<Address>(createAddressDto); var address = _mapper.Map<Address>(createAddressDto);
await _dbContext.Addresses.AddAsync(address); await _dbContext.Addresses.AddAsync(address);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty, _mapper.Map<AddressDto>(address)); return (true, null, _mapper.Map<AddressDto>(address));
} }
public async Task<(bool isSucceed, string message, IEnumerable<AddressDto> addresses, public async Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> addresses,
PagingMetadata<Address> pagingMetadata)> GetAddresses(AddressParameters parameters) PagingMetadata<ExpandoObject> pagingMetadata)> GetAddresses(AddressParameters parameters)
{ {
var dbAddresses = _dbContext.Addresses.Include(a => a.City) var dbAddresses = _dbContext.Addresses.Include(a => a.City)
.ThenInclude(c => c.State).ThenInclude(s => s.Country) .ThenInclude(c => c.State).ThenInclude(s => s.Country)
@ -47,26 +51,23 @@ public class AddressManagementService : IAddressManagementService
FilterByAddressName(ref dbAddresses, parameters.Name); FilterByAddressName(ref dbAddresses, parameters.Name);
FilterByCityId(ref dbAddresses, parameters.CityId); FilterByCityId(ref dbAddresses, parameters.CityId);
var addressDtos = dbAddresses.ToList().ConvertAll(a => _mapper.Map<AddressDto>(a));
var shapedData = _addressDataShaper.ShapeData(addressDtos, parameters.Fields).AsQueryable();
try try
{ {
dbAddresses = _addressSortHelper.ApplySort(dbAddresses, parameters.Sort); shapedData = _addressSortHelper.ApplySort(shapedData, parameters.Sort);
// By calling Any() we will check if LINQ to Entities Query will be
// executed. If not it will throw an InvalidOperationException exception
var isExecuted = dbAddresses.Any();
} }
catch (Exception e) catch (Exception)
{ {
return (false, "Invalid sorting string", null, null)!; return (false, new BadRequestObjectResult("Invalid sorting string"), null, null)!;
} }
var pagingMetadata = ApplyPaging(ref dbAddresses, parameters.PageNumber,
parameters.PageSize);
var shapedAddressesData = _addressDataShaper.ShapeData(dbAddresses, parameters.Fields);
var addressDtos = shapedAddressesData.ToList().ConvertAll(a => _mapper.Map<AddressDto>(a));
return (true, "", addressDtos, pagingMetadata); var pagingMetadata = _pager.ApplyPaging(ref shapedData, parameters.PageNumber,
parameters.PageSize);
return (true, null, shapedData, pagingMetadata);
void SearchByAllAddressFields(ref IQueryable<Address> addresses, void SearchByAllAddressFields(ref IQueryable<Address> addresses,
string? search) string? search)
@ -102,45 +103,32 @@ public class AddressManagementService : IAddressManagementService
addresses = addresses.Where(a => addresses = addresses.Where(a =>
a.Name.ToLower().Contains(addressName.Trim().ToLower())); a.Name.ToLower().Contains(addressName.Trim().ToLower()));
} }
PagingMetadata<Address> ApplyPaging(ref IQueryable<Address> addresses,
int pageNumber, int pageSize)
{
var metadata = new PagingMetadata<Address>(addresses,
pageNumber, pageSize);
addresses = addresses
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
return metadata;
}
} }
public async Task<(bool isSucceed, string message, AddressDto address)> GetAddress(int id, string? fields) public async Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject address)> GetAddress(int id, string? fields)
{ {
if (!await IsAddressExists(id))
{
return (false, new NotFoundResult(), null!);
}
var dbAddress = await _dbContext.Addresses.Where(a => a.Id == id) var dbAddress = await _dbContext.Addresses.Where(a => a.Id == id)
.Include(a => a.City).ThenInclude(c => c.State) .Include(a => a.City).ThenInclude(c => c.State)
.ThenInclude(s => s.Country) .ThenInclude(s => s.Country)
.FirstOrDefaultAsync(); .FirstAsync();
if (dbAddress == null)
{
return (false, $"Address doesn't exist", null)!;
}
if (String.IsNullOrWhiteSpace(fields)) if (String.IsNullOrWhiteSpace(fields))
{ {
fields = AddressParameters.DefaultFields; fields = AddressParameters.DefaultFields;
} }
var shapedAddressData = _addressDataShaper.ShapeData(dbAddress, fields); var addressDto = _mapper.Map<AddressDto>(dbAddress);
var addressDto = _mapper.Map<AddressDto>(shapedAddressData); var shapedData = _addressDataShaper.ShapeData(addressDto, fields);
return (true, "", addressDto); return (true, null, shapedData);
} }
public async Task<(bool isSucceed, string message, UpdateAddressDto address)> UpdateAddress(UpdateAddressDto updateAddressDto) public async Task<(bool isSucceed, IActionResult? actionResult, AddressDto address)> UpdateAddress(UpdateAddressDto updateAddressDto)
{ {
var address = _mapper.Map<Address>(updateAddressDto); var address = _mapper.Map<Address>(updateAddressDto);
_dbContext.Entry(address).State = EntityState.Modified; _dbContext.Entry(address).State = EntityState.Modified;
@ -153,30 +141,28 @@ public class AddressManagementService : IAddressManagementService
{ {
if (!await IsAddressExists(updateAddressDto.Id)) if (!await IsAddressExists(updateAddressDto.Id))
{ {
return (false, $"Address with id:{updateAddressDto.Id} doesn't exist", null)!; return (false, new NotFoundResult(), null!);
} }
throw;
} }
var dbAddress = await _dbContext.Addresses.FirstOrDefaultAsync(a => a.Id == address.Id); var dbAddress = await _dbContext.Addresses.FirstAsync(a => a.Id == address.Id);
return (true, String.Empty, _mapper.Map<UpdateAddressDto>(dbAddress)); return (true, null, _mapper.Map<AddressDto>(dbAddress));
} }
public async Task<(bool isSucceed, string message)> DeleteAddress(int id) public async Task<(bool isSucceed, IActionResult? actionResult)> DeleteAddress(int id)
{ {
var dbAddress = await _dbContext.Addresses.FirstOrDefaultAsync(a => a.Id == id); var dbAddress = await _dbContext.Addresses.FirstOrDefaultAsync(a => a.Id == id);
if (dbAddress == null) if (dbAddress == null)
{ {
return (false, $"Address with id:{id} doesn't exist"); return (false, new NotFoundResult());
} }
_dbContext.Addresses.Remove(dbAddress); _dbContext.Addresses.Remove(dbAddress);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty); return (true, null);
} }
public async Task<bool> IsAddressExists(int id) public async Task<bool> IsAddressExists(int id)

View File

@ -1,4 +1,6 @@
using System.Dynamic;
using AutoMapper; using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Server.Data; using Server.Data;
using Server.Helpers; using Server.Helpers;
@ -13,31 +15,33 @@ public class CityManagementService : ICityManagementService
{ {
private readonly ApplicationDbContext _dbContext; private readonly ApplicationDbContext _dbContext;
private readonly IMapper _mapper; private readonly IMapper _mapper;
private readonly ISortHelper<City> _citySortHelper; private readonly ISortHelper<ExpandoObject> _citySortHelper;
private readonly IDataShaper<City> _cityDataShaper; private readonly IDataShaper<CityDto> _cityDataShaper;
private readonly IPager<ExpandoObject> _pager;
public CityManagementService(ApplicationDbContext dbContext, public CityManagementService(ApplicationDbContext dbContext,
IMapper mapper, ISortHelper<City> citySortHelper, IMapper mapper, ISortHelper<ExpandoObject> citySortHelper,
IDataShaper<City> cityDataShaper) IDataShaper<CityDto> cityDataShaper, IPager<ExpandoObject> pager)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_mapper = mapper; _mapper = mapper;
_citySortHelper = citySortHelper; _citySortHelper = citySortHelper;
_cityDataShaper = cityDataShaper; _cityDataShaper = cityDataShaper;
_pager = pager;
} }
public async Task<(bool isSucceed, string message, CityDto city)> AddCity(CreateCityDto createCityDto) public async Task<(bool isSucceed, IActionResult? actionResult, CityDto city)> AddCity(CreateCityDto createCityDto)
{ {
var city = _mapper.Map<City>(createCityDto); var city = _mapper.Map<City>(createCityDto);
await _dbContext.Cities.AddAsync(city); await _dbContext.Cities.AddAsync(city);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty, _mapper.Map<CityDto>(city)); return (true, null, _mapper.Map<CityDto>(city));
} }
public async Task<(bool isSucceed, string message, IEnumerable<CityDto> cities, public async Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> cities,
PagingMetadata<City> pagingMetadata)> GetCities(CityParameters parameters) PagingMetadata<ExpandoObject> pagingMetadata)> GetCities(CityParameters parameters)
{ {
var dbCities = _dbContext.Cities.Include(c => c.State) var dbCities = _dbContext.Cities.Include(c => c.State)
.ThenInclude(s => s.Country).Include(c => c.Addresses) .ThenInclude(s => s.Country).Include(c => c.Addresses)
@ -47,26 +51,22 @@ public class CityManagementService : ICityManagementService
FilterByCityName(ref dbCities, parameters.Name); FilterByCityName(ref dbCities, parameters.Name);
FilterByStateId(ref dbCities, parameters.StateId); FilterByStateId(ref dbCities, parameters.StateId);
var cityDtos = _mapper.ProjectTo<CityDto>(dbCities);
var shapedData = _cityDataShaper.ShapeData(cityDtos, parameters.Fields).AsQueryable();
try try
{ {
dbCities = _citySortHelper.ApplySort(dbCities, parameters.Sort); shapedData = _citySortHelper.ApplySort(shapedData, parameters.Sort);
// By calling Any() we will check if LINQ to Entities Query will be
// executed. If not it will throw an InvalidOperationException exception
var isExecuted = dbCities.Any();
} }
catch (Exception e) catch (Exception e)
{ {
return (false, "Invalid sorting string", null, null)!; return (false, new BadRequestObjectResult("Invalid sorting string"), null, null)!;
} }
var pagingMetadata = ApplyPaging(ref dbCities, parameters.PageNumber,
parameters.PageSize);
var shapedCitiesData = _cityDataShaper.ShapeData(dbCities, parameters.Fields);
var cityDtos = shapedCitiesData.ToList().ConvertAll(s => _mapper.Map<CityDto>(s));
return (true, "", cityDtos, pagingMetadata); var pagingMetadata = _pager.ApplyPaging(ref shapedData, parameters.PageNumber,
parameters.PageSize);
return (true, null, shapedData, pagingMetadata);
void SearchByAllCityFields(ref IQueryable<City> cities, void SearchByAllCityFields(ref IQueryable<City> cities,
string? search) string? search)
@ -102,45 +102,32 @@ public class CityManagementService : ICityManagementService
cities = cities.Where(s => cities = cities.Where(s =>
s.Name.ToLower().Contains(cityName.Trim().ToLower())); s.Name.ToLower().Contains(cityName.Trim().ToLower()));
} }
PagingMetadata<City> ApplyPaging(ref IQueryable<City> cities,
int pageNumber, int pageSize)
{
var metadata = new PagingMetadata<City>(cities,
pageNumber, pageSize);
cities = cities
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
return metadata;
}
} }
public async Task<(bool isSucceed, string message, CityDto city)> GetCity(int id, string? fields) public async Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject city)> GetCity(int id, string? fields)
{ {
if (!await IsCityExists(id))
{
return (false, new NotFoundResult(), null!);
}
var dbCity = await _dbContext.Cities.Where(s => s.Id == id) var dbCity = await _dbContext.Cities.Where(s => s.Id == id)
.Include(c => c.State).ThenInclude(s => s.Country) .Include(c => c.State).ThenInclude(s => s.Country)
.Include(c => c.Addresses) .Include(c => c.Addresses)
.FirstOrDefaultAsync(); .FirstAsync();
if (dbCity == null)
{
return (false, $"City doesn't exist", null)!;
}
if (String.IsNullOrWhiteSpace(fields)) if (String.IsNullOrWhiteSpace(fields))
{ {
fields = CityParameters.DefaultFields; fields = CityParameters.DefaultFields;
} }
var shapedCityData = _cityDataShaper.ShapeData(dbCity, fields); var cityDto = _mapper.Map<CityDto>(dbCity);
var cityDto = _mapper.Map<CityDto>(shapedCityData); var shapedData = _cityDataShaper.ShapeData(cityDto, fields);
return (true, "", cityDto); return (true, null, shapedData);
} }
public async Task<(bool isSucceed, string message, UpdateCityDto city)> UpdateCity(UpdateCityDto updateCityDto) public async Task<(bool isSucceed, IActionResult? actionResult, CityDto city)> UpdateCity(UpdateCityDto updateCityDto)
{ {
var city = _mapper.Map<City>(updateCityDto); var city = _mapper.Map<City>(updateCityDto);
_dbContext.Entry(city).State = EntityState.Modified; _dbContext.Entry(city).State = EntityState.Modified;
@ -153,30 +140,28 @@ public class CityManagementService : ICityManagementService
{ {
if (!await IsCityExists(updateCityDto.Id)) if (!await IsCityExists(updateCityDto.Id))
{ {
return (false, $"City with id:{updateCityDto.Id} doesn't exist", null)!; return (false, new NotFoundResult(), null)!;
} }
throw;
} }
var dbCity = await _dbContext.Cities.FirstOrDefaultAsync(s => s.Id == city.Id); var dbCity = await _dbContext.Cities.FirstAsync(s => s.Id == city.Id);
return (true, String.Empty, _mapper.Map<UpdateCityDto>(dbCity)); return (true, null, _mapper.Map<CityDto>(dbCity));
} }
public async Task<(bool isSucceed, string message)> DeleteCity(int id) public async Task<(bool isSucceed, IActionResult? actionResult)> DeleteCity(int id)
{ {
var dbCity = await _dbContext.Cities.FirstOrDefaultAsync(s => s.Id == id); var dbCity = await _dbContext.Cities.FirstOrDefaultAsync(s => s.Id == id);
if (dbCity == null) if (dbCity == null)
{ {
return (false, $"City with id:{id} doesn't exist"); return (false, new NotFoundResult());
} }
_dbContext.Cities.Remove(dbCity); _dbContext.Cities.Remove(dbCity);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty); return (true, null);
} }
public async Task<bool> IsCityExists(int id) public async Task<bool> IsCityExists(int id)

View File

@ -1,4 +1,6 @@
using System.Dynamic;
using AutoMapper; using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Server.Data; using Server.Data;
using Server.Helpers; using Server.Helpers;
@ -13,61 +15,57 @@ public class CompanyManagementService : ICompanyManagementService
{ {
private readonly ApplicationDbContext _dbContext; private readonly ApplicationDbContext _dbContext;
private readonly IMapper _mapper; private readonly IMapper _mapper;
private readonly ISortHelper<Company> _companySortHelper; private readonly ISortHelper<ExpandoObject> _companySortHelper;
private readonly IDataShaper<Company> _companyDataShaper; private readonly IDataShaper<CompanyDto> _companyDataShaper;
private readonly IPager<ExpandoObject> _pager;
public CompanyManagementService(ApplicationDbContext dbContext, public CompanyManagementService(ApplicationDbContext dbContext,
IMapper mapper, ISortHelper<Company> companySortHelper, IMapper mapper, ISortHelper<ExpandoObject> companySortHelper,
IDataShaper<Company> companyDataShaper) IDataShaper<CompanyDto> companyDataShaper, IPager<ExpandoObject> pager)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_mapper = mapper; _mapper = mapper;
_companySortHelper = companySortHelper; _companySortHelper = companySortHelper;
_companyDataShaper = companyDataShaper; _companyDataShaper = companyDataShaper;
_pager = pager;
} }
public async Task<(bool isSucceed, string message, CompanyDto company)> AddCompany(CreateCompanyDto createCompanyDto) public async Task<(bool isSucceed, IActionResult? actionResult, CompanyDto company)> AddCompany(CreateCompanyDto createCompanyDto)
{ {
var company = _mapper.Map<Company>(createCompanyDto); var company = _mapper.Map<Company>(createCompanyDto);
await _dbContext.Companies.AddAsync(company); await _dbContext.Companies.AddAsync(company);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty, _mapper.Map<CompanyDto>(company)); return (true, null, _mapper.Map<CompanyDto>(company));
} }
public async Task<(bool isSucceed, string message, IEnumerable<CompanyDto> companies, public async Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> companies,
PagingMetadata<Company> pagingMetadata)> GetCompanies(CompanyParameters parameters) PagingMetadata<ExpandoObject> pagingMetadata)> GetCompanies(CompanyParameters parameters)
{ {
var dbCompanies = _dbContext.Companies var dbCompanies = _dbContext.Companies
.AsQueryable(); .AsQueryable();
var v = dbCompanies.Any();
SearchByAllCompanyFields(ref dbCompanies, parameters.Search); SearchByAllCompanyFields(ref dbCompanies, parameters.Search);
FilterByCompanyName(ref dbCompanies, parameters.Name); FilterByCompanyName(ref dbCompanies, parameters.Name);
FilterByCompanyOwnerId(ref dbCompanies, parameters.OwnerId); FilterByCompanyOwnerId(ref dbCompanies, parameters.OwnerId);
var companyDtos = _mapper.ProjectTo<CompanyDto>(dbCompanies);
var shapedData = _companyDataShaper.ShapeData(companyDtos, parameters.Fields).AsQueryable();
try try
{ {
dbCompanies = _companySortHelper.ApplySort(dbCompanies, parameters.Sort); shapedData = _companySortHelper.ApplySort(shapedData, parameters.Sort);
// By calling Any() we will check if LINQ to Entities Query will be
// executed. If not it will throw an InvalidOperationException exception
var isExecuted = dbCompanies.Any();
} }
catch (Exception e) catch (Exception)
{ {
return (false, "Invalid sorting string", null, null)!; return (false, new BadRequestObjectResult("Invalid sorting string"), null!, null!);
} }
var pagingMetadata = ApplyPaging(ref dbCompanies, parameters.PageNumber,
parameters.PageSize);
var shapedCompaniesData = _companyDataShaper.ShapeData(dbCompanies, parameters.Fields);
var companyDtos = shapedCompaniesData.ToList().ConvertAll(c => _mapper.Map<CompanyDto>(c));
return (true, "", companyDtos, pagingMetadata); var pagingMetadata = _pager.ApplyPaging(ref shapedData, parameters.PageNumber,
parameters.PageSize);
return (true, null, shapedData, pagingMetadata);
void SearchByAllCompanyFields(ref IQueryable<Company> companies, void SearchByAllCompanyFields(ref IQueryable<Company> companies,
string? search) string? search)
@ -102,43 +100,30 @@ public class CompanyManagementService : ICompanyManagementService
companies = companies.Where(c => c.OwnerId == ownerId); companies = companies.Where(c => c.OwnerId == ownerId);
} }
PagingMetadata<Company> ApplyPaging(ref IQueryable<Company> companies,
int pageNumber, int pageSize)
{
var metadata = new PagingMetadata<Company>(companies,
pageNumber, pageSize);
companies = companies
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
return metadata;
}
} }
public async Task<(bool isSucceed, string message, CompanyDto company)> GetCompany(int id, string? fields) public async Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject company)> GetCompany(int id, string? fields)
{ {
var dbCompany = await _dbContext.Companies.Where(c => c.Id == id) if (!await IsCompanyExists(id))
.FirstOrDefaultAsync();
if (dbCompany == null)
{ {
return (false, $"Company doesn't exist", null)!; return (false, new NotFoundResult(), null!);
} }
var dbCompany = await _dbContext.Companies.Where(c => c.Id == id)
.FirstAsync();
if (String.IsNullOrWhiteSpace(fields)) if (String.IsNullOrWhiteSpace(fields))
{ {
fields = CompanyParameters.DefaultFields; fields = CompanyParameters.DefaultFields;
} }
var shapedCompanyData = _companyDataShaper.ShapeData(dbCompany, fields); var companyDto = _mapper.Map<CompanyDto>(dbCompany);
var companyDto = _mapper.Map<CompanyDto>(shapedCompanyData); var shapedData = _companyDataShaper.ShapeData(companyDto, fields);
return (true, "", companyDto); return (true, null, shapedData);
} }
public async Task<(bool isSucceed, string message, UpdateCompanyDto company)> UpdateCompany(UpdateCompanyDto updateCompanyDto) public async Task<(bool isSucceed, IActionResult? actionResult, CompanyDto company)> UpdateCompany(UpdateCompanyDto updateCompanyDto)
{ {
var company = _mapper.Map<Company>(updateCompanyDto); var company = _mapper.Map<Company>(updateCompanyDto);
_dbContext.Entry(company).State = EntityState.Modified; _dbContext.Entry(company).State = EntityState.Modified;
@ -151,30 +136,28 @@ public class CompanyManagementService : ICompanyManagementService
{ {
if (!await IsCompanyExists(updateCompanyDto.Id)) if (!await IsCompanyExists(updateCompanyDto.Id))
{ {
return (false, $"Company with id:{updateCompanyDto.Id} doesn'c exist", null)!; return (false, new BadRequestResult(), null!);
} }
throw;
} }
var dbCompany = await _dbContext.Companies.FirstOrDefaultAsync(c => c.Id == company.Id); var dbCompany = await _dbContext.Companies.FirstAsync(c => c.Id == company.Id);
return (true, String.Empty, _mapper.Map<UpdateCompanyDto>(dbCompany)); return (true, null, _mapper.Map<CompanyDto>(dbCompany));
} }
public async Task<(bool isSucceed, string message)> DeleteCompany(int id) public async Task<(bool isSucceed, IActionResult? actionResult)> DeleteCompany(int id)
{ {
var dbCompany = await _dbContext.Companies.FirstOrDefaultAsync(c => c.Id == id); var dbCompany = await _dbContext.Companies.FirstOrDefaultAsync(c => c.Id == id);
if (dbCompany == null) if (dbCompany == null)
{ {
return (false, $"Company with id:{id} doesn't exist"); return (false, new NotFoundResult());
} }
_dbContext.Companies.Remove(dbCompany); _dbContext.Companies.Remove(dbCompany);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty); return (true, null);
} }
public async Task<bool> IsCompanyExists(int id) public async Task<bool> IsCompanyExists(int id)

View File

@ -1,5 +1,6 @@
using System.Dynamic; using System.Dynamic;
using AutoMapper; using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Server.Data; using Server.Data;
using Server.Helpers; using Server.Helpers;
@ -14,31 +15,33 @@ public class CountryManagementService : ICountryManagementService
{ {
private readonly ApplicationDbContext _dbContext; private readonly ApplicationDbContext _dbContext;
private readonly IMapper _mapper; private readonly IMapper _mapper;
private readonly ISortHelper<Country> _countrySortHelper; private readonly ISortHelper<ExpandoObject> _countrySortHelper;
private readonly IDataShaper<Country> _countryDataShaper; private readonly IDataShaper<CountryDto> _countryDataShaper;
private readonly IPager<ExpandoObject> _pager;
public CountryManagementService(ApplicationDbContext dbContext, public CountryManagementService(ApplicationDbContext dbContext,
IMapper mapper, ISortHelper<Country> countrySortHelper, IMapper mapper, ISortHelper<ExpandoObject> countrySortHelper,
IDataShaper<Country> countryDataShaper) IDataShaper<CountryDto> countryDataShaper, IPager<ExpandoObject> pager)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_mapper = mapper; _mapper = mapper;
_countrySortHelper = countrySortHelper; _countrySortHelper = countrySortHelper;
_countryDataShaper = countryDataShaper; _countryDataShaper = countryDataShaper;
_pager = pager;
} }
public async Task<(bool isSucceed, string message, CountryDto country)> AddCountry(CreateCountryDto createCountryDto) public async Task<(bool isSucceed, IActionResult? actionResult, CountryDto country)> AddCountry(CreateCountryDto createCountryDto)
{ {
var country = _mapper.Map<Country>(createCountryDto); var country = _mapper.Map<Country>(createCountryDto);
await _dbContext.Countries.AddAsync(country); await _dbContext.Countries.AddAsync(country);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty, _mapper.Map<CountryDto>(country)); return (true, null, _mapper.Map<CountryDto>(country));
} }
public async Task<(bool isSucceed, string message, IEnumerable<CountryDto> countries, public async Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> countries,
PagingMetadata<Country> pagingMetadata)> GetCountries(CountryParameters parameters) PagingMetadata<ExpandoObject> pagingMetadata)> GetCountries(CountryParameters parameters)
{ {
var dbCountries = _dbContext.Countries.Include(c => c.States) var dbCountries = _dbContext.Countries.Include(c => c.States)
.ThenInclude(s => s.Cities).ThenInclude(c => c.Addresses) .ThenInclude(s => s.Cities).ThenInclude(c => c.Addresses)
@ -48,26 +51,22 @@ public class CountryManagementService : ICountryManagementService
FilterByCountryCode(ref dbCountries, parameters.Code); FilterByCountryCode(ref dbCountries, parameters.Code);
FilterByCountryName(ref dbCountries, parameters.Name); FilterByCountryName(ref dbCountries, parameters.Name);
var countryDtos = _mapper.ProjectTo<CountryDto>(dbCountries);
var shapedData = _countryDataShaper.ShapeData(countryDtos, parameters.Fields).AsQueryable();
try try
{ {
dbCountries = _countrySortHelper.ApplySort(dbCountries, parameters.Sort); shapedData = _countrySortHelper.ApplySort(shapedData, parameters.Sort);
// By calling Any() we will check if LINQ to Entities Query will be
// executed. If not it will throw an InvalidOperationException exception
var isExecuted = dbCountries.Any();
} }
catch (Exception e) catch (Exception)
{ {
return (false, "Invalid sorting string", null, null)!; return (false, new BadRequestObjectResult("Invalid sorting string"), null, null)!;
} }
var pagingMetadata = ApplyPaging(ref dbCountries, parameters.PageNumber,
parameters.PageSize);
var shapedCountiesData = _countryDataShaper.ShapeData(dbCountries, parameters.Fields);
var countryDtos = shapedCountiesData.ToList().ConvertAll(d => _mapper.Map<CountryDto>(d));
return (true, "", countryDtos, pagingMetadata); var pagingMetadata = _pager.ApplyPaging(ref shapedData, parameters.PageNumber,
parameters.PageSize);
return (true, null, shapedData, pagingMetadata);
void SearchByAllCountryFields(ref IQueryable<Country> countries, void SearchByAllCountryFields(ref IQueryable<Country> countries,
string? search) string? search)
@ -105,45 +104,32 @@ public class CountryManagementService : ICountryManagementService
countries = countries.Where(c => countries = countries.Where(c =>
c.Name.ToLower().Contains(countryName.Trim().ToLower())); c.Name.ToLower().Contains(countryName.Trim().ToLower()));
} }
PagingMetadata<Country> ApplyPaging(ref IQueryable<Country> countries,
int pageNumber, int pageSize)
{
var metadata = new PagingMetadata<Country>(countries,
pageNumber, pageSize);
countries = countries
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
return metadata;
}
} }
public async Task<(bool isSucceed, string message, CountryDto country)> GetCountry(int id, string? fields) public async Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject country)> GetCountry(int id, string? fields)
{ {
if (!await IsCountryExists(id))
{
return (false, new NotFoundResult(), null!);
}
var dbCountry = await _dbContext.Countries.Where(c => c.Id == id) var dbCountry = await _dbContext.Countries.Where(c => c.Id == id)
.Include(c => c.States).ThenInclude(s => s.Cities) .Include(c => c.States).ThenInclude(s => s.Cities)
.ThenInclude(c => c.Addresses) .ThenInclude(c => c.Addresses)
.FirstOrDefaultAsync(); .FirstAsync();
if (dbCountry == null)
{
return (false, $"Country doesn't exist", null)!;
}
if (String.IsNullOrWhiteSpace(fields)) if (String.IsNullOrWhiteSpace(fields))
{ {
fields = CountryParameters.DefaultFields; fields = CountryParameters.DefaultFields;
} }
var shapedCountryData = _countryDataShaper.ShapeData(dbCountry, fields); var countryDto = _mapper.Map<CountryDto>(dbCountry);
var countryDto = _mapper.Map<CountryDto>(shapedCountryData); var shapedData = _countryDataShaper.ShapeData(countryDto, fields);
return (true, "", countryDto); return (true, null, shapedData);
} }
public async Task<(bool isSucceed, string message, UpdateCountryDto country)> UpdateCountry(UpdateCountryDto updateCountryDto) public async Task<(bool isSucceed, IActionResult? actionResult, CountryDto country)> UpdateCountry(UpdateCountryDto updateCountryDto)
{ {
var country = _mapper.Map<Country>(updateCountryDto); var country = _mapper.Map<Country>(updateCountryDto);
_dbContext.Entry(country).State = EntityState.Modified; _dbContext.Entry(country).State = EntityState.Modified;
@ -156,30 +142,28 @@ public class CountryManagementService : ICountryManagementService
{ {
if (!await IsCountryExists(updateCountryDto.Id)) if (!await IsCountryExists(updateCountryDto.Id))
{ {
return (false, $"Country with id:{updateCountryDto.Id} doesn't exist", null)!; return (false, new NotFoundResult(), null!);
} }
throw;
} }
var dbCountry = await _dbContext.Countries.FirstOrDefaultAsync(c => c.Id == country.Id); var dbCountry = await _dbContext.Countries.FirstAsync(c => c.Id == country.Id);
return (true, String.Empty, _mapper.Map<UpdateCountryDto>(dbCountry)); return (true, null, _mapper.Map<CountryDto>(dbCountry));
} }
public async Task<(bool isSucceed, string message)> DeleteCountry(int id) public async Task<(bool isSucceed, IActionResult? actionResult)> DeleteCountry(int id)
{ {
var dbCountry = await _dbContext.Countries.FirstOrDefaultAsync(c => c.Id == id); var dbCountry = await _dbContext.Countries.FirstOrDefaultAsync(c => c.Id == id);
if (dbCountry == null) if (dbCountry == null)
{ {
return (false, $"Country with id:{id} doesn't exist"); return (false, new NotFoundResult());
} }
_dbContext.Countries.Remove(dbCountry); _dbContext.Countries.Remove(dbCountry);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty); return (true, null);
} }
public async Task<bool> IsCountryExists(int id) public async Task<bool> IsCountryExists(int id)

View File

@ -1,4 +1,5 @@
using Server.Models; using System.Dynamic;
using Microsoft.AspNetCore.Mvc;
using SharedModels.DataTransferObjects; using SharedModels.DataTransferObjects;
using SharedModels.QueryParameters; using SharedModels.QueryParameters;
using SharedModels.QueryParameters.Objects; using SharedModels.QueryParameters.Objects;
@ -7,11 +8,11 @@ namespace Server.Services;
public interface IAddressManagementService public interface IAddressManagementService
{ {
Task<(bool isSucceed, string message, AddressDto address)> AddAddress(CreateAddressDto createAddressDto); Task<(bool isSucceed, IActionResult? actionResult, AddressDto address)> AddAddress(CreateAddressDto createAddressDto);
Task<(bool isSucceed, string message, IEnumerable<AddressDto> addresses, Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> addresses,
PagingMetadata<Address> pagingMetadata)> GetAddresses(AddressParameters parameters); PagingMetadata<ExpandoObject> pagingMetadata)> GetAddresses(AddressParameters parameters);
Task<(bool isSucceed, string message, AddressDto address)> GetAddress(int id, string? fields); Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject address)> GetAddress(int id, string? fields);
Task<(bool isSucceed, string message, UpdateAddressDto address)> UpdateAddress(UpdateAddressDto updateAddressDto); Task<(bool isSucceed, IActionResult? actionResult, AddressDto address)> UpdateAddress(UpdateAddressDto updateAddressDto);
Task<(bool isSucceed, string message)> DeleteAddress(int id); Task<(bool isSucceed, IActionResult? actionResult)> DeleteAddress(int id);
Task<bool> IsAddressExists(int id); Task<bool> IsAddressExists(int id);
} }

View File

@ -1,4 +1,5 @@
using Server.Models; using System.Dynamic;
using Microsoft.AspNetCore.Mvc;
using SharedModels.DataTransferObjects; using SharedModels.DataTransferObjects;
using SharedModels.QueryParameters; using SharedModels.QueryParameters;
using SharedModels.QueryParameters.Objects; using SharedModels.QueryParameters.Objects;
@ -7,11 +8,11 @@ namespace Server.Services;
public interface ICityManagementService public interface ICityManagementService
{ {
Task<(bool isSucceed, string message, CityDto city)> AddCity(CreateCityDto createCityDto); Task<(bool isSucceed, IActionResult? actionResult, CityDto city)> AddCity(CreateCityDto createCityDto);
Task<(bool isSucceed, string message, IEnumerable<CityDto> cities, Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> cities,
PagingMetadata<City> pagingMetadata)> GetCities(CityParameters parameters); PagingMetadata<ExpandoObject> pagingMetadata)> GetCities(CityParameters parameters);
Task<(bool isSucceed, string message, CityDto city)> GetCity(int id, string? fields); Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject city)> GetCity(int id, string? fields);
Task<(bool isSucceed, string message, UpdateCityDto city)> UpdateCity(UpdateCityDto updateCityDto); Task<(bool isSucceed, IActionResult? actionResult, CityDto city)> UpdateCity(UpdateCityDto updateCityDto);
Task<(bool isSucceed, string message)> DeleteCity(int id); Task<(bool isSucceed, IActionResult? actionResult)> DeleteCity(int id);
Task<bool> IsCityExists(int id); Task<bool> IsCityExists(int id);
} }

View File

@ -1,3 +1,5 @@
using System.Dynamic;
using Microsoft.AspNetCore.Mvc;
using Server.Models; using Server.Models;
using SharedModels.DataTransferObjects; using SharedModels.DataTransferObjects;
using SharedModels.QueryParameters; using SharedModels.QueryParameters;
@ -7,11 +9,11 @@ namespace Server.Services;
public interface ICompanyManagementService public interface ICompanyManagementService
{ {
Task<(bool isSucceed, string message, CompanyDto company)> AddCompany(CreateCompanyDto createCompanyDto); Task<(bool isSucceed, IActionResult? actionResult, CompanyDto company)> AddCompany(CreateCompanyDto createCompanyDto);
Task<(bool isSucceed, string message, IEnumerable<CompanyDto> companies, Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> companies,
PagingMetadata<Company> pagingMetadata)> GetCompanies(CompanyParameters parameters); PagingMetadata<ExpandoObject> pagingMetadata)> GetCompanies(CompanyParameters parameters);
Task<(bool isSucceed, string message, CompanyDto company)> GetCompany(int id, string? fields); Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject company)> GetCompany(int id, string? fields);
Task<(bool isSucceed, string message, UpdateCompanyDto company)> UpdateCompany(UpdateCompanyDto updateCompanyDto); Task<(bool isSucceed, IActionResult? actionResult, CompanyDto company)> UpdateCompany(UpdateCompanyDto updateCompanyDto);
Task<(bool isSucceed, string message)> DeleteCompany(int id); Task<(bool isSucceed, IActionResult? actionResult)> DeleteCompany(int id);
Task<bool> IsCompanyExists(int id); Task<bool> IsCompanyExists(int id);
} }

View File

@ -1,3 +1,5 @@
using System.Dynamic;
using Microsoft.AspNetCore.Mvc;
using Server.Models; using Server.Models;
using SharedModels.DataTransferObjects; using SharedModels.DataTransferObjects;
using SharedModels.QueryParameters; using SharedModels.QueryParameters;
@ -7,11 +9,11 @@ namespace Server.Services;
public interface ICountryManagementService public interface ICountryManagementService
{ {
Task<(bool isSucceed, string message, CountryDto country)> AddCountry(CreateCountryDto createCountryDto); Task<(bool isSucceed, IActionResult? actionResult, CountryDto country)> AddCountry(CreateCountryDto createCountryDto);
Task<(bool isSucceed, string message, IEnumerable<CountryDto> countries, Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> countries,
PagingMetadata<Country> pagingMetadata)> GetCountries(CountryParameters parameters); PagingMetadata<ExpandoObject> pagingMetadata)> GetCountries(CountryParameters parameters);
Task<(bool isSucceed, string message, CountryDto country)> GetCountry(int id, string? fields); Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject country)> GetCountry(int id, string? fields);
Task<(bool isSucceed, string message, UpdateCountryDto country)> UpdateCountry(UpdateCountryDto updateCountryDto); Task<(bool isSucceed, IActionResult? actionResult, CountryDto country)> UpdateCountry(UpdateCountryDto updateCountryDto);
Task<(bool isSucceed, string message)> DeleteCountry(int id); Task<(bool isSucceed, IActionResult? actionResult)> DeleteCountry(int id);
Task<bool> IsCountryExists(int id); Task<bool> IsCountryExists(int id);
} }

View File

@ -1,4 +1,5 @@
using Server.Models; using System.Dynamic;
using Microsoft.AspNetCore.Mvc;
using SharedModels.DataTransferObjects; using SharedModels.DataTransferObjects;
using SharedModels.QueryParameters; using SharedModels.QueryParameters;
using SharedModels.QueryParameters.Objects; using SharedModels.QueryParameters.Objects;
@ -7,11 +8,11 @@ namespace Server.Services;
public interface IReviewManagementService public interface IReviewManagementService
{ {
Task<(bool isSucceed, string message, ReviewDto review)> AddReview(CreateReviewDto createReviewDto); Task<(bool isSucceed, IActionResult? actionResult, ReviewDto review)> AddReview(CreateReviewDto createReviewDto);
Task<(bool isSucceed, string message, IEnumerable<ReviewDto> reviews, Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> reviews,
PagingMetadata<Review> pagingMetadata)> GetReviews(ReviewParameters parameters); PagingMetadata<ExpandoObject> pagingMetadata)> GetReviews(ReviewParameters parameters);
Task<(bool isSucceed, string message, ReviewDto review)> GetReview(int id, string? fields); Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject review)> GetReview(int id, string? fields);
Task<(bool isSucceed, string message, UpdateReviewDto review)> UpdateReview(UpdateReviewDto updateReviewDto); Task<(bool isSucceed, IActionResult? actionResult, ReviewDto review)> UpdateReview(UpdateReviewDto updateReviewDto);
Task<(bool isSucceed, string message)> DeleteReview(int id); Task<(bool isSucceed, IActionResult? actionResult)> DeleteReview(int id);
Task<bool> IsReviewExists(int id); Task<bool> IsReviewExists(int id);
} }

View File

@ -1,4 +1,5 @@
using Server.Models; using System.Dynamic;
using Microsoft.AspNetCore.Mvc;
using SharedModels.DataTransferObjects; using SharedModels.DataTransferObjects;
using SharedModels.QueryParameters; using SharedModels.QueryParameters;
using SharedModels.QueryParameters.Objects; using SharedModels.QueryParameters.Objects;
@ -7,11 +8,11 @@ namespace Server.Services;
public interface IRouteAddressManagementService public interface IRouteAddressManagementService
{ {
Task<(bool isSucceed, string message, RouteAddressDto routeAddress)> AddRouteAddress(CreateRouteAddressDto createRouteAddressDto); Task<(bool isSucceed, IActionResult? actionResult, RouteAddressDto routeAddress)> AddRouteAddress(CreateRouteAddressDto createRouteAddressDto);
Task<(bool isSucceed, string message, IEnumerable<RouteAddressDto> routeAddresses, Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> routeAddresses,
PagingMetadata<RouteAddress> pagingMetadata)> GetRouteAddresses(RouteAddressParameters parameters); PagingMetadata<ExpandoObject> pagingMetadata)> GetRouteAddresses(RouteAddressParameters parameters);
Task<(bool isSucceed, string message, RouteAddressDto routeAddress)> GetRouteAddress(int id, string? fields); Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject routeAddress)> GetRouteAddress(int id, string? fields);
Task<(bool isSucceed, string message, UpdateRouteAddressDto routeAddress)> UpdateRouteAddress(UpdateRouteAddressDto updateRouteAddressDto); Task<(bool isSucceed, IActionResult? actionResult, RouteAddressDto routeAddress)> UpdateRouteAddress(UpdateRouteAddressDto updateRouteAddressDto);
Task<(bool isSucceed, string message)> DeleteRouteAddress(int id); Task<(bool isSucceed, IActionResult? actionResult)> DeleteRouteAddress(int id);
Task<bool> IsRouteAddressExists(int id); Task<bool> IsRouteAddressExists(int id);
} }

View File

@ -9,15 +9,15 @@ namespace Server.Services;
public interface IRouteManagementService public interface IRouteManagementService
{ {
Task<(bool isSucceed, string message, RouteDto route)> AddRoute(CreateRouteDto createRouteDto); Task<(bool isSucceed, IActionResult? actionResult, RouteDto route)> AddRoute(CreateRouteDto createRouteDto);
Task<(bool isSucceed, IActionResult? actionResult, RouteWithAddressesDto route)> AddRouteWithAddresses(CreateRouteWithAddressesDto createRouteWithAddressesDto); Task<(bool isSucceed, IActionResult? actionResult, RouteWithAddressesDto route)> AddRouteWithAddresses(CreateRouteWithAddressesDto createRouteWithAddressesDto);
Task<(bool isSucceed, string message, IEnumerable<ExpandoObject> routes, Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> routes,
PagingMetadata<ExpandoObject> pagingMetadata)> GetRoutes(RouteParameters parameters); PagingMetadata<ExpandoObject> pagingMetadata)> GetRoutes(RouteParameters parameters);
Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> routes, Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> routes,
PagingMetadata<ExpandoObject> pagingMetadata)> GetRoutesWithAddresses(RouteWithAddressesParameters parameters); PagingMetadata<ExpandoObject> pagingMetadata)> GetRoutesWithAddresses(RouteWithAddressesParameters parameters);
Task<(bool isSucceed, string message, ExpandoObject route)> GetRoute(int id, string? fields); Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject route)> GetRoute(int id, string? fields);
Task<(bool isSucceed, string message, ExpandoObject route)> GetRouteWithAddresses(int id, string? fields); Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject route)> GetRouteWithAddresses(int id, string? fields);
Task<(bool isSucceed, string message, UpdateRouteDto route)> UpdateRoute(UpdateRouteDto updateRouteDto); Task<(bool isSucceed, IActionResult? actionResult, UpdateRouteDto route)> UpdateRoute(UpdateRouteDto updateRouteDto);
Task<(bool isSucceed, string message)> DeleteRoute(int id); Task<(bool isSucceed, IActionResult? actionResult)> DeleteRoute(int id);
Task<bool> IsRouteExists(int id); Task<bool> IsRouteExists(int id);
} }

View File

@ -1,4 +1,5 @@
using Server.Models; using System.Dynamic;
using Microsoft.AspNetCore.Mvc;
using SharedModels.DataTransferObjects; using SharedModels.DataTransferObjects;
using SharedModels.QueryParameters; using SharedModels.QueryParameters;
using SharedModels.QueryParameters.Objects; using SharedModels.QueryParameters.Objects;
@ -7,11 +8,11 @@ namespace Server.Services;
public interface IStateManagementService public interface IStateManagementService
{ {
Task<(bool isSucceed, string message, StateDto state)> AddState(CreateStateDto createStateDto); Task<(bool isSucceed, IActionResult? actionResult, StateDto state)> AddState(CreateStateDto createStateDto);
Task<(bool isSucceed, string message, IEnumerable<StateDto> states, Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> states,
PagingMetadata<State> pagingMetadata)> GetStates(StateParameters parameters); PagingMetadata<ExpandoObject> pagingMetadata)> GetStates(StateParameters parameters);
Task<(bool isSucceed, string message, StateDto state)> GetState(int id, string? fields); Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject state)> GetState(int id, string? fields);
Task<(bool isSucceed, string message, UpdateStateDto state)> UpdateState(UpdateStateDto updateStateDto); Task<(bool isSucceed, IActionResult? actionResult, StateDto state)> UpdateState(UpdateStateDto updateStateDto);
Task<(bool isSucceed, string message)> DeleteState(int id); Task<(bool isSucceed, IActionResult? actionResult)> DeleteState(int id);
Task<bool> IsStateExists(int id); Task<bool> IsStateExists(int id);
} }

View File

@ -1,4 +1,5 @@
using Server.Models; using System.Dynamic;
using Microsoft.AspNetCore.Mvc;
using SharedModels.DataTransferObjects; using SharedModels.DataTransferObjects;
using SharedModels.QueryParameters; using SharedModels.QueryParameters;
using SharedModels.QueryParameters.Objects; using SharedModels.QueryParameters.Objects;
@ -7,11 +8,11 @@ namespace Server.Services;
public interface ITicketManagementService public interface ITicketManagementService
{ {
Task<(bool isSucceed, string message, TicketDto ticket)> AddTicket(CreateTicketDto createTicketDto); Task<(bool isSucceed, IActionResult? actionResult, TicketDto ticket)> AddTicket(CreateTicketDto createTicketDto);
Task<(bool isSucceed, string message, IEnumerable<TicketDto> tickets, Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> tickets,
PagingMetadata<Ticket> pagingMetadata)> GetTickets(TicketParameters parameters); PagingMetadata<ExpandoObject> pagingMetadata)> GetTickets(TicketParameters parameters);
Task<(bool isSucceed, string message, TicketDto ticket)> GetTicket(int id, string? fields); Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject ticket)> GetTicket(int id, string? fields);
Task<(bool isSucceed, string message, UpdateTicketDto ticket)> UpdateTicket(UpdateTicketDto updateTicketDto); Task<(bool isSucceed, IActionResult? actionResult, TicketDto ticket)> UpdateTicket(UpdateTicketDto updateTicketDto);
Task<(bool isSucceed, string message)> DeleteTicket(int id); Task<(bool isSucceed, IActionResult? actionResult)> DeleteTicket(int id);
Task<bool> IsTicketExists(int id); Task<bool> IsTicketExists(int id);
} }

View File

@ -1,4 +1,5 @@
using Server.Models; using System.Dynamic;
using Microsoft.AspNetCore.Mvc;
using SharedModels.DataTransferObjects; using SharedModels.DataTransferObjects;
using SharedModels.QueryParameters; using SharedModels.QueryParameters;
using SharedModels.QueryParameters.Objects; using SharedModels.QueryParameters.Objects;
@ -7,11 +8,11 @@ namespace Server.Services;
public interface IVehicleEnrollmentManagementService public interface IVehicleEnrollmentManagementService
{ {
Task<(bool isSucceed, string message, VehicleEnrollmentDto enrollment)> AddEnrollment(CreateVehicleEnrollmentDto createEnrollmentDto); Task<(bool isSucceed, IActionResult? actionResult, VehicleEnrollmentDto enrollment)> AddEnrollment(CreateVehicleEnrollmentDto createEnrollmentDto);
Task<(bool isSucceed, string message, IEnumerable<VehicleEnrollmentDto> enrollments, Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> enrollments,
PagingMetadata<VehicleEnrollment> pagingMetadata)> GetEnrollments(VehicleEnrollmentParameters parameters); PagingMetadata<ExpandoObject> pagingMetadata)> GetEnrollments(VehicleEnrollmentParameters parameters);
Task<(bool isSucceed, string message, VehicleEnrollmentDto enrollment)> GetEnrollment(int id, string? fields); Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject enrollment)> GetEnrollment(int id, string? fields);
Task<(bool isSucceed, string message, UpdateVehicleEnrollmentDto enrollment)> UpdateEnrollment(UpdateVehicleEnrollmentDto updateEnrollmentDto); Task<(bool isSucceed, IActionResult? actionResult, VehicleEnrollmentDto enrollment)> UpdateEnrollment(UpdateVehicleEnrollmentDto updateEnrollmentDto);
Task<(bool isSucceed, string message)> DeleteEnrollment(int id); Task<(bool isSucceed, IActionResult? actionResult)> DeleteEnrollment(int id);
Task<bool> IsEnrollmentExists(int id); Task<bool> IsEnrollmentExists(int id);
} }

View File

@ -1,4 +1,5 @@
using Server.Models; using System.Dynamic;
using Microsoft.AspNetCore.Mvc;
using SharedModels.DataTransferObjects; using SharedModels.DataTransferObjects;
using SharedModels.QueryParameters; using SharedModels.QueryParameters;
using SharedModels.QueryParameters.Objects; using SharedModels.QueryParameters.Objects;
@ -7,11 +8,11 @@ namespace Server.Services;
public interface IVehicleManagementService public interface IVehicleManagementService
{ {
Task<(bool isSucceed, string message, VehicleDto vehicle)> AddVehicle(CreateVehicleDto createVehicleDto); Task<(bool isSucceed, IActionResult? actionResult, VehicleDto vehicle)> AddVehicle(CreateVehicleDto createVehicleDto);
Task<(bool isSucceed, string message, IEnumerable<VehicleDto> vehicles, Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> vehicles,
PagingMetadata<Vehicle> pagingMetadata)> GetVehicles(VehicleParameters parameters); PagingMetadata<ExpandoObject> pagingMetadata)> GetVehicles(VehicleParameters parameters);
Task<(bool isSucceed, string message, VehicleDto vehicle)> GetVehicle(int id, string? fields); Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject vehicle)> GetVehicle(int id, string? fields);
Task<(bool isSucceed, string message, UpdateVehicleDto vehicle)> UpdateVehicle(UpdateVehicleDto updateVehicleDto); Task<(bool isSucceed, IActionResult? actionResult, VehicleDto vehicle)> UpdateVehicle(UpdateVehicleDto updateVehicleDto);
Task<(bool isSucceed, string message)> DeleteVehicle(int id); Task<(bool isSucceed, IActionResult? actionResult)> DeleteVehicle(int id);
Task<bool> IsVehicleExists(int id); Task<bool> IsVehicleExists(int id);
} }

View File

@ -1,4 +1,6 @@
using System.Dynamic;
using AutoMapper; using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Server.Data; using Server.Data;
using Server.Helpers; using Server.Helpers;
@ -13,31 +15,33 @@ public class ReviewManagementService : IReviewManagementService
{ {
private readonly ApplicationDbContext _dbContext; private readonly ApplicationDbContext _dbContext;
private readonly IMapper _mapper; private readonly IMapper _mapper;
private readonly ISortHelper<Review> _reviewSortHelper; private readonly ISortHelper<ExpandoObject> _reviewSortHelper;
private readonly IDataShaper<Review> _reviewDataShaper; private readonly IDataShaper<ReviewDto> _reviewDataShaper;
private readonly IPager<ExpandoObject> _pager;
public ReviewManagementService(ApplicationDbContext dbContext, public ReviewManagementService(ApplicationDbContext dbContext,
IMapper mapper, ISortHelper<Review> reviewSortHelper, IMapper mapper, ISortHelper<ExpandoObject> reviewSortHelper,
IDataShaper<Review> reviewDataShaper) IDataShaper<ReviewDto> reviewDataShaper, IPager<ExpandoObject> pager)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_mapper = mapper; _mapper = mapper;
_reviewSortHelper = reviewSortHelper; _reviewSortHelper = reviewSortHelper;
_reviewDataShaper = reviewDataShaper; _reviewDataShaper = reviewDataShaper;
_pager = pager;
} }
public async Task<(bool isSucceed, string message, ReviewDto review)> AddReview(CreateReviewDto createReviewDto) public async Task<(bool isSucceed, IActionResult? actionResult, ReviewDto review)> AddReview(CreateReviewDto createReviewDto)
{ {
var review = _mapper.Map<Review>(createReviewDto); var review = _mapper.Map<Review>(createReviewDto);
await _dbContext.Reviews.AddAsync(review); await _dbContext.Reviews.AddAsync(review);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty, _mapper.Map<ReviewDto>(review)); return (true, null, _mapper.Map<ReviewDto>(review));
} }
public async Task<(bool isSucceed, string message, IEnumerable<ReviewDto> reviews, public async Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> reviews,
PagingMetadata<Review> pagingMetadata)> GetReviews(ReviewParameters parameters) PagingMetadata<ExpandoObject> pagingMetadata)> GetReviews(ReviewParameters parameters)
{ {
var dbReviews = _dbContext.Reviews var dbReviews = _dbContext.Reviews
.AsQueryable(); .AsQueryable();
@ -46,26 +50,22 @@ public class ReviewManagementService : IReviewManagementService
FilterByReviewComment(ref dbReviews, parameters.Comment); FilterByReviewComment(ref dbReviews, parameters.Comment);
FilterByReviewUserId(ref dbReviews, parameters.UserId); FilterByReviewUserId(ref dbReviews, parameters.UserId);
var reviewDtos = _mapper.ProjectTo<ReviewDto>(dbReviews);
var shapedData = _reviewDataShaper.ShapeData(reviewDtos, parameters.Fields).AsQueryable();
try try
{ {
dbReviews = _reviewSortHelper.ApplySort(dbReviews, parameters.Sort); shapedData = _reviewSortHelper.ApplySort(shapedData, parameters.Sort);
// By calling Any() we will check if LINQ to Entities Query will be
// executed. If not it will throw an InvalidOperationException exception
var isExecuted = dbReviews.Any();
} }
catch (Exception e) catch (Exception e)
{ {
return (false, "Invalid sorting string", null, null)!; return (false, new BadRequestObjectResult("Invalid sorting string"), null!, null!);
} }
var pagingMetadata = ApplyPaging(ref dbReviews, parameters.PageNumber,
parameters.PageSize);
var shapedReviewsData = _reviewDataShaper.ShapeData(dbReviews, parameters.Fields);
var reviewDtos = shapedReviewsData.ToList().ConvertAll(r => _mapper.Map<ReviewDto>(r));
return (true, "", reviewDtos, pagingMetadata); var pagingMetadata = _pager.ApplyPaging(ref shapedData, parameters.PageNumber,
parameters.PageSize);
return (true, null, shapedData, pagingMetadata);
void FilterByReviewRating(ref IQueryable<Review> reviews, void FilterByReviewRating(ref IQueryable<Review> reviews,
int? fromRating, int? toRating) int? fromRating, int? toRating)
@ -103,43 +103,30 @@ public class ReviewManagementService : IReviewManagementService
reviews = reviews.Where(r => reviews = reviews.Where(r =>
r.UserId.Contains(userId.ToLower())); r.UserId.Contains(userId.ToLower()));
} }
PagingMetadata<Review> ApplyPaging(ref IQueryable<Review> reviews,
int pageNumber, int pageSize)
{
var metadata = new PagingMetadata<Review>(reviews,
pageNumber, pageSize);
reviews = reviews
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
return metadata;
}
} }
public async Task<(bool isSucceed, string message, ReviewDto review)> GetReview(int id, string? fields) public async Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject review)> GetReview(int id, string? fields)
{ {
var dbReview = await _dbContext.Reviews.Where(r => r.Id == id) if (!await IsReviewExists(id))
.FirstOrDefaultAsync();
if (dbReview == null)
{ {
return (false, $"Review doesn't exist", null)!; return (false, new NotFoundResult(), null!);
} }
var dbReview = await _dbContext.Reviews.Where(r => r.Id == id)
.FirstAsync();
if (String.IsNullOrWhiteSpace(fields)) if (String.IsNullOrWhiteSpace(fields))
{ {
fields = ReviewParameters.DefaultFields; fields = ReviewParameters.DefaultFields;
} }
var shapedReviewData = _reviewDataShaper.ShapeData(dbReview, fields); var reviewDto = _mapper.Map<ReviewDto>(dbReview);
var reviewDto = _mapper.Map<ReviewDto>(shapedReviewData); var shapedData = _reviewDataShaper.ShapeData(reviewDto, fields);
return (true, "", reviewDto); return (true, null, shapedData);
} }
public async Task<(bool isSucceed, string message, UpdateReviewDto review)> UpdateReview(UpdateReviewDto updateReviewDto) public async Task<(bool isSucceed, IActionResult? actionResult, ReviewDto review)> UpdateReview(UpdateReviewDto updateReviewDto)
{ {
var review = _mapper.Map<Review>(updateReviewDto); var review = _mapper.Map<Review>(updateReviewDto);
_dbContext.Entry(review).State = EntityState.Modified; _dbContext.Entry(review).State = EntityState.Modified;
@ -152,30 +139,28 @@ public class ReviewManagementService : IReviewManagementService
{ {
if (!await IsReviewExists(updateReviewDto.Id)) if (!await IsReviewExists(updateReviewDto.Id))
{ {
return (false, $"Review with id:{updateReviewDto.Id} doesn't exist", null)!; return (false, new NotFoundResult(), null!);
} }
throw;
} }
var dbReview = await _dbContext.Reviews.FirstOrDefaultAsync(r => r.Id == review.Id); var dbReview = await _dbContext.Reviews.FirstAsync(r => r.Id == review.Id);
return (true, String.Empty, _mapper.Map<UpdateReviewDto>(dbReview)); return (true, null, _mapper.Map<ReviewDto>(dbReview));
} }
public async Task<(bool isSucceed, string message)> DeleteReview(int id) public async Task<(bool isSucceed, IActionResult? actionResult)> DeleteReview(int id)
{ {
var dbReview = await _dbContext.Reviews.FirstOrDefaultAsync(r => r.Id == id); var dbReview = await _dbContext.Reviews.FirstOrDefaultAsync(r => r.Id == id);
if (dbReview == null) if (dbReview == null)
{ {
return (false, $"Review with id:{id} doesn't exist"); return (false,new NotFoundResult());
} }
_dbContext.Reviews.Remove(dbReview); _dbContext.Reviews.Remove(dbReview);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty); return (true, null);
} }
public async Task<bool> IsReviewExists(int id) public async Task<bool> IsReviewExists(int id)

View File

@ -1,4 +1,6 @@
using System.Dynamic;
using AutoMapper; using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Server.Data; using Server.Data;
using Server.Helpers; using Server.Helpers;
@ -13,31 +15,33 @@ public class RouteAddressManagementService : IRouteAddressManagementService
{ {
private readonly ApplicationDbContext _dbContext; private readonly ApplicationDbContext _dbContext;
private readonly IMapper _mapper; private readonly IMapper _mapper;
private readonly ISortHelper<RouteAddress> _routeAddressSortHelper; private readonly ISortHelper<ExpandoObject> _routeAddressSortHelper;
private readonly IDataShaper<RouteAddress> _routeAddressDataShaper; private readonly IDataShaper<RouteAddressDto> _routeAddressDataShaper;
private readonly IPager<ExpandoObject> _pager;
public RouteAddressManagementService(ApplicationDbContext dbContext, public RouteAddressManagementService(ApplicationDbContext dbContext,
IMapper mapper, ISortHelper<RouteAddress> routeAddressSortHelper, IMapper mapper, ISortHelper<ExpandoObject> routeAddressSortHelper,
IDataShaper<RouteAddress> routeAddressDataShaper) IDataShaper<RouteAddressDto> routeAddressDataShaper, IPager<ExpandoObject> pager)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_mapper = mapper; _mapper = mapper;
_routeAddressSortHelper = routeAddressSortHelper; _routeAddressSortHelper = routeAddressSortHelper;
_routeAddressDataShaper = routeAddressDataShaper; _routeAddressDataShaper = routeAddressDataShaper;
_pager = pager;
} }
public async Task<(bool isSucceed, string message, RouteAddressDto routeAddress)> AddRouteAddress(CreateRouteAddressDto createRouteAddressDto) public async Task<(bool isSucceed, IActionResult? actionResult, RouteAddressDto routeAddress)> AddRouteAddress(CreateRouteAddressDto createRouteAddressDto)
{ {
var routeAddress = _mapper.Map<RouteAddress>(createRouteAddressDto); var routeAddress = _mapper.Map<RouteAddress>(createRouteAddressDto);
await _dbContext.RouteAddresses.AddAsync(routeAddress); await _dbContext.RouteAddresses.AddAsync(routeAddress);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty, _mapper.Map<RouteAddressDto>(routeAddress)); return (true, null, _mapper.Map<RouteAddressDto>(routeAddress));
} }
public async Task<(bool isSucceed, string message, IEnumerable<RouteAddressDto> routeAddresses, public async Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> routeAddresses,
PagingMetadata<RouteAddress> pagingMetadata)> GetRouteAddresses(RouteAddressParameters parameters) PagingMetadata<ExpandoObject> pagingMetadata)> GetRouteAddresses(RouteAddressParameters parameters)
{ {
var dbRouteAddresses = _dbContext.RouteAddresses var dbRouteAddresses = _dbContext.RouteAddresses
.AsQueryable(); .AsQueryable();
@ -45,26 +49,22 @@ public class RouteAddressManagementService : IRouteAddressManagementService
FilterByRouteAddressRouteId(ref dbRouteAddresses, parameters.RouteId); FilterByRouteAddressRouteId(ref dbRouteAddresses, parameters.RouteId);
FilterByRouteAddressAddressId(ref dbRouteAddresses, parameters.AddressId); FilterByRouteAddressAddressId(ref dbRouteAddresses, parameters.AddressId);
var routeAddressDtos = _mapper.ProjectTo<RouteAddressDto>(dbRouteAddresses);
var shapedData = _routeAddressDataShaper.ShapeData(routeAddressDtos, parameters.Fields).AsQueryable();
try try
{ {
dbRouteAddresses = _routeAddressSortHelper.ApplySort(dbRouteAddresses, parameters.Sort); shapedData = _routeAddressSortHelper.ApplySort(shapedData, parameters.Sort);
// By calling Any() we will check if LINQ to Entities Query will be
// executed. If not it will throw an InvalidOperationException exception
var isExecuted = dbRouteAddresses.Any();
} }
catch (Exception e) catch (Exception)
{ {
return (false, "Invalid sorting string", null, null)!; return (false, new BadRequestObjectResult("Invalid sorting string"), null!, null!);
} }
var pagingMetadata = ApplyPaging(ref dbRouteAddresses, parameters.PageNumber,
parameters.PageSize);
var shapedRouteAddressesData = _routeAddressDataShaper.ShapeData(dbRouteAddresses, parameters.Fields);
var routeAddressDtos = shapedRouteAddressesData.ToList().ConvertAll(ra => _mapper.Map<RouteAddressDto>(ra));
return (true, "", routeAddressDtos, pagingMetadata); var pagingMetadata = _pager.ApplyPaging(ref shapedData, parameters.PageNumber,
parameters.PageSize);
return (true, null, shapedData, pagingMetadata);
void FilterByRouteAddressRouteId(ref IQueryable<RouteAddress> routeAddresses, void FilterByRouteAddressRouteId(ref IQueryable<RouteAddress> routeAddresses,
int? routeId) int? routeId)
@ -87,43 +87,30 @@ public class RouteAddressManagementService : IRouteAddressManagementService
routeAddresses = routeAddresses.Where(ra => ra.AddressId == addressId); routeAddresses = routeAddresses.Where(ra => ra.AddressId == addressId);
} }
PagingMetadata<RouteAddress> ApplyPaging(ref IQueryable<RouteAddress> routeAddresses,
int pageNumber, int pageSize)
{
var metadata = new PagingMetadata<RouteAddress>(routeAddresses,
pageNumber, pageSize);
routeAddresses = routeAddresses
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
return metadata;
}
} }
public async Task<(bool isSucceed, string message, RouteAddressDto routeAddress)> GetRouteAddress(int id, string? fields) public async Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject routeAddress)> GetRouteAddress(int id, string? fields)
{ {
var dbRouteAddress = await _dbContext.RouteAddresses.Where(ra => ra.Id == id) if (!await IsRouteAddressExists(id))
.FirstOrDefaultAsync();
if (dbRouteAddress == null)
{ {
return (false, $"RouteAddress doesn't exist", null)!; return (false, new NotFoundResult(), null!);
} }
var dbRouteAddress = await _dbContext.RouteAddresses.Where(ra => ra.Id == id)
.FirstAsync();
if (String.IsNullOrWhiteSpace(fields)) if (String.IsNullOrWhiteSpace(fields))
{ {
fields = RouteAddressParameters.DefaultFields; fields = RouteAddressParameters.DefaultFields;
} }
var shapedRouteAddressData = _routeAddressDataShaper.ShapeData(dbRouteAddress, fields); var routeAddressDto = _mapper.Map<RouteAddressDto>(dbRouteAddress);
var routeAddressDto = _mapper.Map<RouteAddressDto>(shapedRouteAddressData); var shapedData = _routeAddressDataShaper.ShapeData(routeAddressDto, fields);
return (true, "", routeAddressDto); return (true, null, shapedData);
} }
public async Task<(bool isSucceed, string message, UpdateRouteAddressDto routeAddress)> UpdateRouteAddress(UpdateRouteAddressDto updateRouteAddressDto) public async Task<(bool isSucceed, IActionResult? actionResult, RouteAddressDto routeAddress)> UpdateRouteAddress(UpdateRouteAddressDto updateRouteAddressDto)
{ {
var routeAddress = _mapper.Map<RouteAddress>(updateRouteAddressDto); var routeAddress = _mapper.Map<RouteAddress>(updateRouteAddressDto);
_dbContext.Entry(routeAddress).State = EntityState.Modified; _dbContext.Entry(routeAddress).State = EntityState.Modified;
@ -136,30 +123,30 @@ public class RouteAddressManagementService : IRouteAddressManagementService
{ {
if (!await IsRouteAddressExists(updateRouteAddressDto.Id)) if (!await IsRouteAddressExists(updateRouteAddressDto.Id))
{ {
return (false, $"RouteAddress with id:{updateRouteAddressDto.Id} doesn't exist", null)!; return (false, new NotFoundResult(), null!);
} }
throw; throw;
} }
var dbRouteAddress = await _dbContext.RouteAddresses.FirstOrDefaultAsync(ra => ra.Id == routeAddress.Id); var dbRouteAddress = await _dbContext.RouteAddresses.FirstAsync(ra => ra.Id == routeAddress.Id);
return (true, String.Empty, _mapper.Map<UpdateRouteAddressDto>(dbRouteAddress)); return (true, null, _mapper.Map<RouteAddressDto>(dbRouteAddress));
} }
public async Task<(bool isSucceed, string message)> DeleteRouteAddress(int id) public async Task<(bool isSucceed, IActionResult? actionResult)> DeleteRouteAddress(int id)
{ {
var dbRouteAddress = await _dbContext.RouteAddresses.FirstOrDefaultAsync(ra => ra.Id == id); var dbRouteAddress = await _dbContext.RouteAddresses.FirstOrDefaultAsync(ra => ra.Id == id);
if (dbRouteAddress == null) if (dbRouteAddress == null)
{ {
return (false, $"RouteAddress with id:{id} doesn't exist"); return (false, new NotFoundResult());
} }
_dbContext.RouteAddresses.Remove(dbRouteAddress); _dbContext.RouteAddresses.Remove(dbRouteAddress);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty); return (true, null);
} }
public async Task<bool> IsRouteAddressExists(int id) public async Task<bool> IsRouteAddressExists(int id)

View File

@ -35,14 +35,14 @@ public class RouteManagementService : IRouteManagementService
_pager = pager; _pager = pager;
} }
public async Task<(bool isSucceed, string message, RouteDto route)> AddRoute(CreateRouteDto createRouteDto) public async Task<(bool isSucceed, IActionResult? actionResult, RouteDto route)> AddRoute(CreateRouteDto createRouteDto)
{ {
var route = _mapper.Map<Route>(createRouteDto); var route = _mapper.Map<Route>(createRouteDto);
await _dbContext.Routes.AddAsync(route); await _dbContext.Routes.AddAsync(route);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty, _mapper.Map<RouteDto>(route)); return (true, null, _mapper.Map<RouteDto>(route));
} }
public async Task<(bool isSucceed, IActionResult? actionResult, RouteWithAddressesDto route)> AddRouteWithAddresses(CreateRouteWithAddressesDto createRouteWithAddressesDto) public async Task<(bool isSucceed, IActionResult? actionResult, RouteWithAddressesDto route)> AddRouteWithAddresses(CreateRouteWithAddressesDto createRouteWithAddressesDto)
@ -56,7 +56,7 @@ public class RouteManagementService : IRouteManagementService
if (dbAddress == null) if (dbAddress == null)
{ {
return (false, new BadRequestObjectResult($"Address with Id = {routeAddress.AddressId} doesn't exist"), null!); return (false, new BadRequestObjectResult($"Address with Id {routeAddress.AddressId} doesn't exist"), null!);
} }
routeAddress.Address = dbAddress; routeAddress.Address = dbAddress;
@ -68,7 +68,7 @@ public class RouteManagementService : IRouteManagementService
return (true, null, _mapper.Map<RouteWithAddressesDto>(route)); return (true, null, _mapper.Map<RouteWithAddressesDto>(route));
} }
public async Task<(bool isSucceed, string message, IEnumerable<ExpandoObject> routes, public async Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> routes,
PagingMetadata<ExpandoObject> pagingMetadata)> GetRoutes(RouteParameters parameters) PagingMetadata<ExpandoObject> pagingMetadata)> GetRoutes(RouteParameters parameters)
{ {
var dbRoutes = _dbContext.Routes var dbRoutes = _dbContext.Routes
@ -83,20 +83,16 @@ public class RouteManagementService : IRouteManagementService
try try
{ {
shapedData = _routeSortHelper.ApplySort(shapedData, parameters.Sort); shapedData = _routeSortHelper.ApplySort(shapedData, parameters.Sort);
// By calling Any() we will check if LINQ to Entities Query will be
// executed. If not it will throw an InvalidOperationException exception
var isExecuted = dbRoutes.Any();
} }
catch (Exception e) catch (Exception e)
{ {
return (false, "Invalid sorting string", null, null)!; return (false, new BadRequestObjectResult("Invalid sorting string"), null, null)!;
} }
var pagingMetadata = _pager.ApplyPaging(ref shapedData, parameters.PageNumber, var pagingMetadata = _pager.ApplyPaging(ref shapedData, parameters.PageNumber,
parameters.PageSize); parameters.PageSize);
return (true, "", shapedData, pagingMetadata); return (true, null, shapedData, pagingMetadata);
void SearchByAllRouteFields(ref IQueryable<Route> route, void SearchByAllRouteFields(ref IQueryable<Route> route,
string? search) string? search)
@ -213,16 +209,16 @@ public class RouteManagementService : IRouteManagementService
} }
} }
public async Task<(bool isSucceed, string message, ExpandoObject route)> GetRoute(int id, string? fields) public async Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject route)> GetRoute(int id, string? fields)
{ {
var dbRoute = await _dbContext.Routes.Where(r => r.Id == id) if (!await IsRouteExists(id))
.FirstOrDefaultAsync();
if (dbRoute == null)
{ {
return (false, $"Route doesn't exist", null)!; return (false, new NotFoundResult(), null)!;
} }
var dbRoute = await _dbContext.Routes.Where(r => r.Id == id)
.FirstAsync();
if (String.IsNullOrWhiteSpace(fields)) if (String.IsNullOrWhiteSpace(fields))
{ {
fields = RouteParameters.DefaultFields; fields = RouteParameters.DefaultFields;
@ -231,33 +227,33 @@ public class RouteManagementService : IRouteManagementService
var routeDto = _mapper.Map<RouteDto>(dbRoute); var routeDto = _mapper.Map<RouteDto>(dbRoute);
var shapedRouteData = _routeDataShaper.ShapeData(routeDto, fields); var shapedRouteData = _routeDataShaper.ShapeData(routeDto, fields);
return (true, "", shapedRouteData); return (true, null, shapedRouteData);
} }
public async Task<(bool isSucceed, string message, ExpandoObject route)> GetRouteWithAddresses(int id, string? fields) public async Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject route)> GetRouteWithAddresses(int id, string? fields)
{ {
if (!await IsRouteExists(id))
{
return (false, new NotFoundResult(), null)!;
}
var dbRoute = await _dbContext.Routes.Where(r => r.Id == id) var dbRoute = await _dbContext.Routes.Where(r => r.Id == id)
.Include(r => r.RouteAddresses).ThenInclude(ra => ra.Address) .Include(r => r.RouteAddresses).ThenInclude(ra => ra.Address)
.ThenInclude(a => a.City).ThenInclude(c => c.State) .ThenInclude(a => a.City).ThenInclude(c => c.State)
.ThenInclude(s => s.Country).FirstOrDefaultAsync(); .ThenInclude(s => s.Country).FirstAsync();
if (dbRoute == null)
{
return (false, $"Route doesn't exist", null)!;
}
if (String.IsNullOrWhiteSpace(fields)) if (String.IsNullOrWhiteSpace(fields))
{ {
fields = RouteWithAddressesParameters.DefaultFields; fields = RouteWithAddressesParameters.DefaultFields;
} }
var routeDto = _mapper.Map<RouteWithAddressesDto>(dbRoute); var routeDto = _mapper.Map<RouteWithAddressesDto>(dbRoute);
var shapedRouteData = _routeDataShaper.ShapeData(routeDto, fields); var shapedData = _routeDataShaper.ShapeData(routeDto, fields);
return (true, "", shapedRouteData); return (true, null, shapedData);
} }
public async Task<(bool isSucceed, string message, UpdateRouteDto route)> UpdateRoute(UpdateRouteDto updateRouteDto) public async Task<(bool isSucceed, IActionResult? actionResult, UpdateRouteDto route)> UpdateRoute(UpdateRouteDto updateRouteDto)
{ {
var route = _mapper.Map<Route>(updateRouteDto); var route = _mapper.Map<Route>(updateRouteDto);
_dbContext.Entry(route).State = EntityState.Modified; _dbContext.Entry(route).State = EntityState.Modified;
@ -270,30 +266,28 @@ public class RouteManagementService : IRouteManagementService
{ {
if (!await IsRouteExists(updateRouteDto.Id)) if (!await IsRouteExists(updateRouteDto.Id))
{ {
return (false, $"Route with id:{updateRouteDto.Id} doesn't exist", null)!; return (false, new NotFoundResult(), null)!;
} }
throw;
} }
var dbRoute = await _dbContext.Routes.FirstOrDefaultAsync(r => r.Id == route.Id); var dbRoute = await _dbContext.Routes.FirstAsync(r => r.Id == route.Id);
return (true, String.Empty, _mapper.Map<UpdateRouteDto>(dbRoute)); return (true, null, _mapper.Map<UpdateRouteDto>(dbRoute));
} }
public async Task<(bool isSucceed, string message)> DeleteRoute(int id) public async Task<(bool isSucceed, IActionResult? actionResult)> DeleteRoute(int id)
{ {
var dbRoute = await _dbContext.Routes.FirstOrDefaultAsync(r => r.Id == id); var dbRoute = await _dbContext.Routes.FirstOrDefaultAsync(r => r.Id == id);
if (dbRoute == null) if (dbRoute == null)
{ {
return (false, $"Route with id:{id} doesn't exist"); return (false, new NotFoundResult());
} }
_dbContext.Routes.Remove(dbRoute); _dbContext.Routes.Remove(dbRoute);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty); return (true, null);
} }
public async Task<bool> IsRouteExists(int id) public async Task<bool> IsRouteExists(int id)

View File

@ -1,5 +1,6 @@
using System.Dynamic; using System.Dynamic;
using AutoMapper; using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Server.Data; using Server.Data;
using Server.Helpers; using Server.Helpers;
@ -14,62 +15,58 @@ public class StateManagementService : IStateManagementService
{ {
private readonly ApplicationDbContext _dbContext; private readonly ApplicationDbContext _dbContext;
private readonly IMapper _mapper; private readonly IMapper _mapper;
private readonly ISortHelper<State> _stateSortHelper; private readonly ISortHelper<ExpandoObject> _stateSortHelper;
private readonly IDataShaper<State> _stateDataShaper; private readonly IDataShaper<StateDto> _stateDataShaper;
private readonly IPager<ExpandoObject> _pager;
public StateManagementService(ApplicationDbContext dbContext, public StateManagementService(ApplicationDbContext dbContext,
IMapper mapper, ISortHelper<State> stateSortHelper, IMapper mapper, ISortHelper<ExpandoObject> stateSortHelper,
IDataShaper<State> stateDataShaper) IDataShaper<StateDto> stateDataShaper, IPager<ExpandoObject> pager)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_mapper = mapper; _mapper = mapper;
_stateSortHelper = stateSortHelper; _stateSortHelper = stateSortHelper;
_stateDataShaper = stateDataShaper; _stateDataShaper = stateDataShaper;
_pager = pager;
} }
public async Task<(bool isSucceed, string message, StateDto state)> AddState(CreateStateDto createStateDto) public async Task<(bool isSucceed, IActionResult? actionResult, StateDto state)> AddState(CreateStateDto createStateDto)
{ {
var state = _mapper.Map<State>(createStateDto); var state = _mapper.Map<State>(createStateDto);
await _dbContext.States.AddAsync(state); await _dbContext.States.AddAsync(state);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty, _mapper.Map<StateDto>(state)); return (true, null, _mapper.Map<StateDto>(state));
} }
public async Task<(bool isSucceed, string message, IEnumerable<StateDto> states, public async Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> states,
PagingMetadata<State> pagingMetadata)> GetStates(StateParameters parameters) PagingMetadata<ExpandoObject> pagingMetadata)> GetStates(StateParameters parameters)
{ {
var dbStates = _dbContext.States.Include(s => s.Country) var dbStates = _dbContext.States.Include(s => s.Country)
.Include(s => s.Cities) .Include(s => s.Cities)
.ThenInclude(c => c.Addresses).AsQueryable(); .ThenInclude(c => c.Addresses).AsQueryable();
var s = dbStates.ToList().ConvertAll(s => _mapper.Map<StateDto>(s));
SearchByAllStateFields(ref dbStates, parameters.Search); SearchByAllStateFields(ref dbStates, parameters.Search);
FilterByStateName(ref dbStates, parameters.Name); FilterByStateName(ref dbStates, parameters.Name);
FilterByCountryId(ref dbStates, parameters.CountryId); FilterByCountryId(ref dbStates, parameters.CountryId);
var stateDtos = _mapper.ProjectTo<StateDto>(dbStates);
var shapedData = _stateDataShaper.ShapeData(stateDtos, parameters.Fields).AsQueryable();
try try
{ {
dbStates = _stateSortHelper.ApplySort(dbStates, parameters.Sort); shapedData = _stateSortHelper.ApplySort(shapedData, parameters.Sort);
// By calling Any() we will check if LINQ to Entities Query will be
// executed. If not it will throw an InvalidOperationException exception
var isExecuted = dbStates.Any();
} }
catch (Exception e) catch (Exception)
{ {
return (false, "Invalid sorting string", null, null)!; return (false, new BadRequestObjectResult("Invalid sorting string"), null!, null!);
} }
var pagingMetadata = ApplyPaging(ref dbStates, parameters.PageNumber,
parameters.PageSize);
var shapedStatesData = _stateDataShaper.ShapeData(dbStates, parameters.Fields);
var stateDtos = shapedStatesData.ToList().ConvertAll(s => _mapper.Map<StateDto>(s));
return (true, "", stateDtos, pagingMetadata); var pagingMetadata = _pager.ApplyPaging(ref shapedData, parameters.PageNumber,
parameters.PageSize);
return (true, null, shapedData, pagingMetadata);
void SearchByAllStateFields(ref IQueryable<State> states, void SearchByAllStateFields(ref IQueryable<State> states,
string? search) string? search)
@ -105,45 +102,32 @@ public class StateManagementService : IStateManagementService
states = states.Where(s => states = states.Where(s =>
s.Name.ToLower().Contains(stateName.Trim().ToLower())); s.Name.ToLower().Contains(stateName.Trim().ToLower()));
} }
PagingMetadata<State> ApplyPaging(ref IQueryable<State> states,
int pageNumber, int pageSize)
{
var metadata = new PagingMetadata<State>(states,
pageNumber, pageSize);
states = states
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
return metadata;
}
} }
public async Task<(bool isSucceed, string message, StateDto state)> GetState(int id, string? fields) public async Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject state)> GetState(int id, string? fields)
{ {
if (!await IsStateExists(id))
{
return (false, new NotFoundResult(), null!);
}
var dbState = await _dbContext.States.Where(s => s.Id == id) var dbState = await _dbContext.States.Where(s => s.Id == id)
.Include(s => s.Country).Include(s => s.Cities) .Include(s => s.Country).Include(s => s.Cities)
.ThenInclude(c => c.Addresses) .ThenInclude(c => c.Addresses)
.FirstOrDefaultAsync(); .FirstAsync();
if (dbState == null)
{
return (false, $"State doesn't exist", null)!;
}
if (String.IsNullOrWhiteSpace(fields)) if (String.IsNullOrWhiteSpace(fields))
{ {
fields = StateParameters.DefaultFields; fields = StateParameters.DefaultFields;
} }
var shapedStateData = _stateDataShaper.ShapeData(dbState, fields); var stateDto = _mapper.Map<StateDto>(dbState);
var stateDto = _mapper.Map<StateDto>(shapedStateData); var shapedData = _stateDataShaper.ShapeData(stateDto, fields);
return (true, "", stateDto); return (true, null, shapedData);
} }
public async Task<(bool isSucceed, string message, UpdateStateDto state)> UpdateState(UpdateStateDto updateStateDto) public async Task<(bool isSucceed, IActionResult? actionResult, StateDto state)> UpdateState(UpdateStateDto updateStateDto)
{ {
var state = _mapper.Map<State>(updateStateDto); var state = _mapper.Map<State>(updateStateDto);
_dbContext.Entry(state).State = EntityState.Modified; _dbContext.Entry(state).State = EntityState.Modified;
@ -156,30 +140,28 @@ public class StateManagementService : IStateManagementService
{ {
if (!await IsStateExists(updateStateDto.Id)) if (!await IsStateExists(updateStateDto.Id))
{ {
return (false, $"State with id:{updateStateDto.Id} doesn't exist", null)!; return (false, new NotFoundResult(), null!);
} }
throw;
} }
var dbState = await _dbContext.States.FirstOrDefaultAsync(s => s.Id == state.Id); var dbState = await _dbContext.States.FirstAsync(s => s.Id == state.Id);
return (true, String.Empty, _mapper.Map<UpdateStateDto>(dbState)); return (true, null, _mapper.Map<StateDto>(dbState));
} }
public async Task<(bool isSucceed, string message)> DeleteState(int id) public async Task<(bool isSucceed, IActionResult? actionResult)> DeleteState(int id)
{ {
var dbState = await _dbContext.States.FirstOrDefaultAsync(s => s.Id == id); var dbState = await _dbContext.States.FirstOrDefaultAsync(s => s.Id == id);
if (dbState == null) if (dbState == null)
{ {
return (false, $"State with id:{id} doesn't exist"); return (false, new NotFoundResult());
} }
_dbContext.States.Remove(dbState); _dbContext.States.Remove(dbState);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty); return (true, null);
} }
public async Task<bool> IsStateExists(int id) public async Task<bool> IsStateExists(int id)

View File

@ -1,4 +1,6 @@
using System.Dynamic;
using AutoMapper; using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Server.Data; using Server.Data;
using Server.Helpers; using Server.Helpers;
@ -13,31 +15,33 @@ public class TicketManagementService : ITicketManagementService
{ {
private readonly ApplicationDbContext _dbContext; private readonly ApplicationDbContext _dbContext;
private readonly IMapper _mapper; private readonly IMapper _mapper;
private readonly ISortHelper<Ticket> _ticketSortHelper; private readonly ISortHelper<ExpandoObject> _ticketSortHelper;
private readonly IDataShaper<Ticket> _ticketDataShaper; private readonly IDataShaper<TicketDto> _ticketDataShaper;
private readonly IPager<ExpandoObject> _pager;
public TicketManagementService(ApplicationDbContext dbContext, public TicketManagementService(ApplicationDbContext dbContext,
IMapper mapper, ISortHelper<Ticket> ticketSortHelper, IMapper mapper, ISortHelper<ExpandoObject> ticketSortHelper,
IDataShaper<Ticket> ticketDataShaper) IDataShaper<TicketDto> ticketDataShaper, IPager<ExpandoObject> pager)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_mapper = mapper; _mapper = mapper;
_ticketSortHelper = ticketSortHelper; _ticketSortHelper = ticketSortHelper;
_ticketDataShaper = ticketDataShaper; _ticketDataShaper = ticketDataShaper;
_pager = pager;
} }
public async Task<(bool isSucceed, string message, TicketDto ticket)> AddTicket(CreateTicketDto createTicketDto) public async Task<(bool isSucceed, IActionResult? actionResult, TicketDto ticket)> AddTicket(CreateTicketDto createTicketDto)
{ {
var ticket = _mapper.Map<Ticket>(createTicketDto); var ticket = _mapper.Map<Ticket>(createTicketDto);
await _dbContext.Tickets.AddAsync(ticket); await _dbContext.Tickets.AddAsync(ticket);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty, _mapper.Map<TicketDto>(ticket)); return (true, null, _mapper.Map<TicketDto>(ticket));
} }
public async Task<(bool isSucceed, string message, IEnumerable<TicketDto> tickets, public async Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> tickets,
PagingMetadata<Ticket> pagingMetadata)> GetTickets(TicketParameters parameters) PagingMetadata<ExpandoObject> pagingMetadata)> GetTickets(TicketParameters parameters)
{ {
var dbTickets = _dbContext.Tickets var dbTickets = _dbContext.Tickets
.AsQueryable(); .AsQueryable();
@ -46,27 +50,23 @@ public class TicketManagementService : ITicketManagementService
parameters.ToPurchaseDateTimeUtc); parameters.ToPurchaseDateTimeUtc);
FilterByTicketReturnedState(ref dbTickets, parameters.IsReturned); FilterByTicketReturnedState(ref dbTickets, parameters.IsReturned);
FilterByTicketUserId(ref dbTickets, parameters.UserId); FilterByTicketUserId(ref dbTickets, parameters.UserId);
var ticketDtos = _mapper.ProjectTo<TicketDto>(dbTickets);
var shapedData = _ticketDataShaper.ShapeData(ticketDtos, parameters.Fields).AsQueryable();
try try
{ {
dbTickets = _ticketSortHelper.ApplySort(dbTickets, parameters.Sort); shapedData = _ticketSortHelper.ApplySort(shapedData, parameters.Sort);
// By calling Any() we will check if LINQ to Entities Query will be
// executed. If not it will throw an InvalidOperationException exception
var isExecuted = dbTickets.Any();
} }
catch (Exception e) catch (Exception)
{ {
return (false, "Invalid sorting string", null, null)!; return (false, new BadRequestObjectResult("Invalid sorting string"), null!, null!);
} }
var pagingMetadata = ApplyPaging(ref dbTickets, parameters.PageNumber,
parameters.PageSize);
var shapedTicketsData = _ticketDataShaper.ShapeData(dbTickets, parameters.Fields);
var ticketDtos = shapedTicketsData.ToList().ConvertAll(t => _mapper.Map<TicketDto>(t));
return (true, "", ticketDtos, pagingMetadata); var pagingMetadata = _pager.ApplyPaging(ref shapedData, parameters.PageNumber,
parameters.PageSize);
return (true, null, shapedData, pagingMetadata);
void FilterByTicketPurchaseDateTime(ref IQueryable<Ticket> tickets, void FilterByTicketPurchaseDateTime(ref IQueryable<Ticket> tickets,
DateTime? fromDateTime, DateTime? toDateTime) DateTime? fromDateTime, DateTime? toDateTime)
@ -104,43 +104,30 @@ public class TicketManagementService : ITicketManagementService
// tickets = tickets.Where(t => // tickets = tickets.Where(t =>
// t.UserId.ToLower().Contains(userId.ToLower())); // t.UserId.ToLower().Contains(userId.ToLower()));
} }
PagingMetadata<Ticket> ApplyPaging(ref IQueryable<Ticket> tickets,
int pageNumber, int pageSize)
{
var metadata = new PagingMetadata<Ticket>(tickets,
pageNumber, pageSize);
tickets = tickets
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
return metadata;
}
} }
public async Task<(bool isSucceed, string message, TicketDto ticket)> GetTicket(int id, string? fields) public async Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject ticket)> GetTicket(int id, string? fields)
{ {
var dbTicket = await _dbContext.Tickets.Where(t => t.Id == id) if (!await IsTicketExists(id))
.FirstOrDefaultAsync();
if (dbTicket == null)
{ {
return (false, $"Ticket doesn't exist", null)!; return (false, new NotFoundResult(), null!);
} }
var dbTicket = await _dbContext.Tickets.Where(t => t.Id == id)
.FirstAsync();
if (String.IsNullOrWhiteSpace(fields)) if (String.IsNullOrWhiteSpace(fields))
{ {
fields = TicketParameters.DefaultFields; fields = TicketParameters.DefaultFields;
} }
var shapedTicketData = _ticketDataShaper.ShapeData(dbTicket, fields); var ticketDto = _mapper.Map<TicketDto>(dbTicket);
var ticketDto = _mapper.Map<TicketDto>(shapedTicketData); var shapedData = _ticketDataShaper.ShapeData(ticketDto, fields);
return (true, "", ticketDto); return (true, null, shapedData);
} }
public async Task<(bool isSucceed, string message, UpdateTicketDto ticket)> UpdateTicket(UpdateTicketDto updateTicketDto) public async Task<(bool isSucceed, IActionResult? actionResult, TicketDto ticket)> UpdateTicket(UpdateTicketDto updateTicketDto)
{ {
var ticket = _mapper.Map<Ticket>(updateTicketDto); var ticket = _mapper.Map<Ticket>(updateTicketDto);
_dbContext.Entry(ticket).State = EntityState.Modified; _dbContext.Entry(ticket).State = EntityState.Modified;
@ -153,30 +140,28 @@ public class TicketManagementService : ITicketManagementService
{ {
if (!await IsTicketExists(updateTicketDto.Id)) if (!await IsTicketExists(updateTicketDto.Id))
{ {
return (false, $"Ticket with id:{updateTicketDto.Id} doesn't exist", null)!; return (false, new NotFoundResult(), null!);
} }
throw;
} }
var dbTicket = await _dbContext.Tickets.FirstOrDefaultAsync(t => t.Id == ticket.Id); var dbTicket = await _dbContext.Tickets.FirstAsync(t => t.Id == ticket.Id);
return (true, String.Empty, _mapper.Map<UpdateTicketDto>(dbTicket)); return (true, null, _mapper.Map<TicketDto>(dbTicket));
} }
public async Task<(bool isSucceed, string message)> DeleteTicket(int id) public async Task<(bool isSucceed, IActionResult? actionResult)> DeleteTicket(int id)
{ {
var dbTicket = await _dbContext.Tickets.FirstOrDefaultAsync(t => t.Id == id); var dbTicket = await _dbContext.Tickets.FirstOrDefaultAsync(t => t.Id == id);
if (dbTicket == null) if (dbTicket == null)
{ {
return (false, $"Ticket with id:{id} doesn't exist"); return (false, new NotFoundResult());
} }
_dbContext.Tickets.Remove(dbTicket); _dbContext.Tickets.Remove(dbTicket);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty); return (true, null);
} }
public async Task<bool> IsTicketExists(int id) public async Task<bool> IsTicketExists(int id)

View File

@ -1,4 +1,6 @@
using System.Dynamic;
using AutoMapper; using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Server.Data; using Server.Data;
using Server.Helpers; using Server.Helpers;
@ -13,31 +15,33 @@ public class VehicleEnrollmentManagementService : IVehicleEnrollmentManagementSe
{ {
private readonly ApplicationDbContext _dbContext; private readonly ApplicationDbContext _dbContext;
private readonly IMapper _mapper; private readonly IMapper _mapper;
private readonly ISortHelper<VehicleEnrollment> _enrollmentSortHelper; private readonly ISortHelper<ExpandoObject> _enrollmentSortHelper;
private readonly IDataShaper<VehicleEnrollment> _enrollmentDataShaper; private readonly IDataShaper<VehicleEnrollmentDto> _enrollmentDataShaper;
private readonly IPager<ExpandoObject> _pager;
public VehicleEnrollmentManagementService(ApplicationDbContext dbContext, public VehicleEnrollmentManagementService(ApplicationDbContext dbContext,
IMapper mapper, ISortHelper<VehicleEnrollment> enrollmentSortHelper, IMapper mapper, ISortHelper<ExpandoObject> enrollmentSortHelper,
IDataShaper<VehicleEnrollment> enrollmentDataShaper) IDataShaper<VehicleEnrollmentDto> enrollmentDataShaper, IPager<ExpandoObject> pager)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_mapper = mapper; _mapper = mapper;
_enrollmentSortHelper = enrollmentSortHelper; _enrollmentSortHelper = enrollmentSortHelper;
_enrollmentDataShaper = enrollmentDataShaper; _enrollmentDataShaper = enrollmentDataShaper;
_pager = pager;
} }
public async Task<(bool isSucceed, string message, VehicleEnrollmentDto enrollment)> AddEnrollment(CreateVehicleEnrollmentDto createEnrollmentDto) public async Task<(bool isSucceed, IActionResult? actionResult, VehicleEnrollmentDto enrollment)> AddEnrollment(CreateVehicleEnrollmentDto createEnrollmentDto)
{ {
var enrollment = _mapper.Map<VehicleEnrollment>(createEnrollmentDto); var enrollment = _mapper.Map<VehicleEnrollment>(createEnrollmentDto);
await _dbContext.VehicleEnrollments.AddAsync(enrollment); await _dbContext.VehicleEnrollments.AddAsync(enrollment);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty, _mapper.Map<VehicleEnrollmentDto>(enrollment)); return (true, null, _mapper.Map<VehicleEnrollmentDto>(enrollment));
} }
public async Task<(bool isSucceed, string message, IEnumerable<VehicleEnrollmentDto> enrollments, public async Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> enrollments,
PagingMetadata<VehicleEnrollment> pagingMetadata)> GetEnrollments(VehicleEnrollmentParameters parameters) PagingMetadata<ExpandoObject> pagingMetadata)> GetEnrollments(VehicleEnrollmentParameters parameters)
{ {
var dbEnrollments = _dbContext.VehicleEnrollments var dbEnrollments = _dbContext.VehicleEnrollments
.AsQueryable(); .AsQueryable();
@ -50,26 +54,22 @@ public class VehicleEnrollmentManagementService : IVehicleEnrollmentManagementSe
FilterByEnrollmentDelayedValue(ref dbEnrollments, parameters.IsDelayed); FilterByEnrollmentDelayedValue(ref dbEnrollments, parameters.IsDelayed);
FilterByEnrollmentCancelledValue(ref dbEnrollments, parameters.IsCanceled); FilterByEnrollmentCancelledValue(ref dbEnrollments, parameters.IsCanceled);
var enrollmentDtos = _mapper.ProjectTo<VehicleEnrollmentDto>(dbEnrollments);
var shapedData = _enrollmentDataShaper.ShapeData(enrollmentDtos, parameters.Fields).AsQueryable();
try try
{ {
dbEnrollments = _enrollmentSortHelper.ApplySort(dbEnrollments, parameters.Sort); shapedData = _enrollmentSortHelper.ApplySort(shapedData, parameters.Sort);
// By calling Any() we will check if LINQ to Entities Query will be
// executed. If not it will throw an InvalidOperationException exception
var isExecuted = dbEnrollments.Any();
} }
catch (Exception e) catch (Exception)
{ {
return (false, "Invalid sorting string", null, null)!; return (false, new BadRequestObjectResult("Invalid sorting string"), null!, null!);
} }
var pagingMetadata = ApplyPaging(ref dbEnrollments, parameters.PageNumber,
parameters.PageSize);
var shapedEnrollmentsData = _enrollmentDataShaper.ShapeData(dbEnrollments, parameters.Fields);
var enrollmentDtos = shapedEnrollmentsData.ToList().ConvertAll(e => _mapper.Map<VehicleEnrollmentDto>(e));
return (true, "", enrollmentDtos, pagingMetadata); var pagingMetadata = _pager.ApplyPaging(ref shapedData, parameters.PageNumber,
parameters.PageSize);
return (true, null, shapedData, pagingMetadata);
void SearchByAllEnrollmentFields(ref IQueryable<VehicleEnrollment> enrollment, void SearchByAllEnrollmentFields(ref IQueryable<VehicleEnrollment> enrollment,
string? search) string? search)
@ -141,43 +141,30 @@ public class VehicleEnrollmentManagementService : IVehicleEnrollmentManagementSe
enrollments = enrollments.Where(e => e.IsCanceled == isCancelled); enrollments = enrollments.Where(e => e.IsCanceled == isCancelled);
} }
PagingMetadata<VehicleEnrollment> ApplyPaging(ref IQueryable<VehicleEnrollment> enrollments,
int pageNumber, int pageSize)
{
var metadata = new PagingMetadata<VehicleEnrollment>(enrollments,
pageNumber, pageSize);
enrollments = enrollments
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
return metadata;
}
} }
public async Task<(bool isSucceed, string message, VehicleEnrollmentDto enrollment)> GetEnrollment(int id, string? fields) public async Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject enrollment)> GetEnrollment(int id, string? fields)
{ {
var dbEnrollment = await _dbContext.VehicleEnrollments.Where(e => e.Id == id) if (!await IsEnrollmentExists(id))
.FirstOrDefaultAsync();
if (dbEnrollment == null)
{ {
return (false, $"Enrollment doesn't exist", null)!; return (false, new NotFoundResult(), null!);
} }
var dbEnrollment = await _dbContext.VehicleEnrollments.Where(e => e.Id == id)
.FirstAsync();
if (String.IsNullOrWhiteSpace(fields)) if (String.IsNullOrWhiteSpace(fields))
{ {
fields = VehicleEnrollmentParameters.DefaultFields; fields = VehicleEnrollmentParameters.DefaultFields;
} }
var shapedEnrollmentData = _enrollmentDataShaper.ShapeData(dbEnrollment, fields); var enrollmentDto = _mapper.Map<VehicleEnrollmentDto>(dbEnrollment);
var enrollmentDto = _mapper.Map<VehicleEnrollmentDto>(shapedEnrollmentData); var shapedData = _enrollmentDataShaper.ShapeData(enrollmentDto, fields);
return (true, "", enrollmentDto); return (true, null, shapedData);
} }
public async Task<(bool isSucceed, string message, UpdateVehicleEnrollmentDto enrollment)> UpdateEnrollment(UpdateVehicleEnrollmentDto updateEnrollmentDto) public async Task<(bool isSucceed, IActionResult? actionResult, VehicleEnrollmentDto enrollment)> UpdateEnrollment(UpdateVehicleEnrollmentDto updateEnrollmentDto)
{ {
var enrollment = _mapper.Map<VehicleEnrollment>(updateEnrollmentDto); var enrollment = _mapper.Map<VehicleEnrollment>(updateEnrollmentDto);
_dbContext.Entry(enrollment).State = EntityState.Modified; _dbContext.Entry(enrollment).State = EntityState.Modified;
@ -190,30 +177,30 @@ public class VehicleEnrollmentManagementService : IVehicleEnrollmentManagementSe
{ {
if (!await IsEnrollmentExists(updateEnrollmentDto.Id)) if (!await IsEnrollmentExists(updateEnrollmentDto.Id))
{ {
return (false, $"Enrollment with id:{updateEnrollmentDto.Id} doesn't exist", null)!; return (false, new NotFoundResult(), null!);
} }
throw; throw;
} }
var dbEnrollment = await _dbContext.VehicleEnrollments.FirstOrDefaultAsync(e => e.Id == enrollment.Id); var dbEnrollment = await _dbContext.VehicleEnrollments.FirstAsync(e => e.Id == enrollment.Id);
return (true, String.Empty, _mapper.Map<UpdateVehicleEnrollmentDto>(dbEnrollment)); return (true, null, _mapper.Map<VehicleEnrollmentDto>(dbEnrollment));
} }
public async Task<(bool isSucceed, string message)> DeleteEnrollment(int id) public async Task<(bool isSucceed, IActionResult? actionResult)> DeleteEnrollment(int id)
{ {
var dbEnrollment = await _dbContext.VehicleEnrollments.FirstOrDefaultAsync(e => e.Id == id); var dbEnrollment = await _dbContext.VehicleEnrollments.FirstOrDefaultAsync(e => e.Id == id);
if (dbEnrollment == null) if (dbEnrollment == null)
{ {
return (false, $"Enrollment with id:{id} doesn't exist"); return (false, new NotFoundResult());
} }
_dbContext.VehicleEnrollments.Remove(dbEnrollment); _dbContext.VehicleEnrollments.Remove(dbEnrollment);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty); return (true, null);
} }
public async Task<bool> IsEnrollmentExists(int id) public async Task<bool> IsEnrollmentExists(int id)

View File

@ -1,4 +1,6 @@
using System.Dynamic;
using AutoMapper; using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Server.Data; using Server.Data;
using Server.Helpers; using Server.Helpers;
@ -13,83 +15,53 @@ public class VehicleManagementService : IVehicleManagementService
{ {
private readonly ApplicationDbContext _dbContext; private readonly ApplicationDbContext _dbContext;
private readonly IMapper _mapper; private readonly IMapper _mapper;
private readonly ISortHelper<Vehicle> _vehicleSortHelper; private readonly ISortHelper<ExpandoObject> _vehicleSortHelper;
private readonly IDataShaper<Vehicle> _vehicleDataShaper; private readonly IDataShaper<VehicleDto> _vehicleDataShaper;
private readonly IPager<ExpandoObject> _pager;
public VehicleManagementService(ApplicationDbContext dbContext, public VehicleManagementService(ApplicationDbContext dbContext,
IMapper mapper, ISortHelper<Vehicle> vehicleSortHelper, IMapper mapper, ISortHelper<ExpandoObject> vehicleSortHelper,
IDataShaper<Vehicle> vehicleDataShaper) IDataShaper<VehicleDto> vehicleDataShaper, IPager<ExpandoObject> pager)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_mapper = mapper; _mapper = mapper;
_vehicleSortHelper = vehicleSortHelper; _vehicleSortHelper = vehicleSortHelper;
_vehicleDataShaper = vehicleDataShaper; _vehicleDataShaper = vehicleDataShaper;
_pager = pager;
} }
public async Task<(bool isSucceed, string message, VehicleDto vehicle)> AddVehicle(CreateVehicleDto createVehicleDto) public async Task<(bool isSucceed, IActionResult? actionResult, VehicleDto vehicle)> AddVehicle(CreateVehicleDto createVehicleDto)
{ {
var vehicle = _mapper.Map<Vehicle>(createVehicleDto); var vehicle = _mapper.Map<Vehicle>(createVehicleDto);
await _dbContext.Vehicles.AddAsync(vehicle); await _dbContext.Vehicles.AddAsync(vehicle);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty, _mapper.Map<VehicleDto>(vehicle)); return (true, null, _mapper.Map<VehicleDto>(vehicle));
} }
public async Task<(bool isSucceed, string message, IEnumerable<VehicleDto> vehicles, public async Task<(bool isSucceed, IActionResult? actionResult, IEnumerable<ExpandoObject> vehicles,
PagingMetadata<Vehicle> pagingMetadata)> GetVehicles(VehicleParameters parameters) PagingMetadata<ExpandoObject> pagingMetadata)> GetVehicles(VehicleParameters parameters)
{ {
var dbVehicles = _dbContext.Vehicles var dbVehicles = _dbContext.Vehicles
.AsQueryable(); .AsQueryable();
bool a = dbVehicles.Any(); var vehicleDtos = _mapper.ProjectTo<VehicleDto>(dbVehicles);
var shapedData = _vehicleDataShaper.ShapeData(vehicleDtos, parameters.Fields).AsQueryable();
SearchByAllVehicleFields(ref dbVehicles, parameters.Search);
a = dbVehicles.Any();
FilterByVehicleNumber(ref dbVehicles, parameters.Number);
a = dbVehicles.Any();
FilterByVehicleType(ref dbVehicles, parameters.Type);
a = dbVehicles.Any();
FilterByVehicleCapacity(ref dbVehicles, parameters.FromCapacity,
parameters.ToCapacity);
a = dbVehicles.Any();
FilterByVehicleClimateControlAvailability(ref dbVehicles, parameters.HasClimateControl);
a = dbVehicles.Any();
FilterByVehicleWiFiAvailability(ref dbVehicles, parameters.HasWiFi);
a = dbVehicles.Any();
FilterByVehicleWCAvailability(ref dbVehicles, parameters.HasWC);
a = dbVehicles.Any();
FilterByStewardessAvailability(ref dbVehicles, parameters.HasStewardess);
a = dbVehicles.Any();
FilterByVehicleTVAvailability(ref dbVehicles, parameters.HasTV);
a = dbVehicles.Any();
FilterByVehicleOutletAvailability(ref dbVehicles, parameters.HasOutlet);
a = dbVehicles.Any();
FilterByVehicleBeltsAvailability(ref dbVehicles, parameters.HasBelts);
a = dbVehicles.Any();
FilterByVehicleCompanyId(ref dbVehicles, parameters.CompanyId);
a = dbVehicles.Any();
try try
{ {
dbVehicles = _vehicleSortHelper.ApplySort(dbVehicles, parameters.Sort); shapedData = _vehicleSortHelper.ApplySort(shapedData, parameters.Sort);
// By calling Any() we will check if LINQ to Entities Query will be
// executed. If not it will throw an InvalidOperationException exception
var isExecuted = dbVehicles.Any();
} }
catch (Exception e) catch (Exception)
{ {
return (false, "Invalid sorting string", null, null)!; return (false, new BadRequestObjectResult("Invalid sorting string"), null!, null!);
} }
var pagingMetadata = ApplyPaging(ref dbVehicles, parameters.PageNumber,
parameters.PageSize);
var shapedVehiclesData = _vehicleDataShaper.ShapeData(dbVehicles, parameters.Fields);
var vehicleDtos = shapedVehiclesData.ToList().ConvertAll(v => _mapper.Map<VehicleDto>(v));
return (true, "", vehicleDtos, pagingMetadata); var pagingMetadata = _pager.ApplyPaging(ref shapedData, parameters.PageNumber,
parameters.PageSize);
return (true, null, shapedData, pagingMetadata);
void SearchByAllVehicleFields(ref IQueryable<Vehicle> vehicle, void SearchByAllVehicleFields(ref IQueryable<Vehicle> vehicle,
string? search) string? search)
@ -225,43 +197,31 @@ public class VehicleManagementService : IVehicleManagementService
vehicles = vehicles.Where(v => v.CompanyId == companyId); vehicles = vehicles.Where(v => v.CompanyId == companyId);
} }
PagingMetadata<Vehicle> ApplyPaging(ref IQueryable<Vehicle> vehicles,
int pageNumber, int pageSize)
{
var metadata = new PagingMetadata<Vehicle>(vehicles,
pageNumber, pageSize);
vehicles = vehicles
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
return metadata;
}
} }
public async Task<(bool isSucceed, string message, VehicleDto vehicle)> GetVehicle(int id, string? fields) public async Task<(bool isSucceed, IActionResult? actionResult, ExpandoObject vehicle)> GetVehicle(int id, string? fields)
{ {
var dbVehicle = await _dbContext.Vehicles.Where(v => v.Id == id) if (!await IsVehicleExists(id))
.FirstOrDefaultAsync();
if (dbVehicle == null)
{ {
return (false, $"Vehicle doesn't exist", null)!; return (false, new NotFoundResult(), null!);
} }
var dbVehicle = await _dbContext.Vehicles.Where(v => v.Id == id)
.FirstAsync();
if (String.IsNullOrWhiteSpace(fields)) if (String.IsNullOrWhiteSpace(fields))
{ {
fields = VehicleParameters.DefaultFields; fields = VehicleParameters.DefaultFields;
} }
var shapedVehicleData = _vehicleDataShaper.ShapeData(dbVehicle, fields); var vehicleDto = _mapper.Map<VehicleDto>(dbVehicle);
var vehicleDto = _mapper.Map<VehicleDto>(shapedVehicleData); var shapedData = _vehicleDataShaper.ShapeData(vehicleDto, fields);
return (true, "", vehicleDto); return (true, null, shapedData);
} }
public async Task<(bool isSucceed, string message, UpdateVehicleDto vehicle)> UpdateVehicle(UpdateVehicleDto updateVehicleDto) public async Task<(bool isSucceed, IActionResult? actionResult, VehicleDto vehicle)> UpdateVehicle(UpdateVehicleDto updateVehicleDto)
{ {
var vehicle = _mapper.Map<Vehicle>(updateVehicleDto); var vehicle = _mapper.Map<Vehicle>(updateVehicleDto);
_dbContext.Entry(vehicle).State = EntityState.Modified; _dbContext.Entry(vehicle).State = EntityState.Modified;
@ -274,30 +234,30 @@ public class VehicleManagementService : IVehicleManagementService
{ {
if (!await IsVehicleExists(updateVehicleDto.Id)) if (!await IsVehicleExists(updateVehicleDto.Id))
{ {
return (false, $"Vehicle with id:{updateVehicleDto.Id} doesn't exist", null)!; return (false, new NotFoundResult(), null!);
} }
throw; throw;
} }
var dbVehicle = await _dbContext.Vehicles.FirstOrDefaultAsync(v => v.Id == vehicle.Id); var dbVehicle = await _dbContext.Vehicles.FirstAsync(v => v.Id == vehicle.Id);
return (true, String.Empty, _mapper.Map<UpdateVehicleDto>(dbVehicle)); return (true, null, _mapper.Map<VehicleDto>(dbVehicle));
} }
public async Task<(bool isSucceed, string message)> DeleteVehicle(int id) public async Task<(bool isSucceed, IActionResult? actionResult)> DeleteVehicle(int id)
{ {
var dbVehicle = await _dbContext.Vehicles.FirstOrDefaultAsync(v => v.Id == id); var dbVehicle = await _dbContext.Vehicles.FirstOrDefaultAsync(v => v.Id == id);
if (dbVehicle == null) if (dbVehicle == null)
{ {
return (false, $"Vehicle with id:{id} doesn't exist"); return (false, new NotFoundResult());
} }
_dbContext.Vehicles.Remove(dbVehicle); _dbContext.Vehicles.Remove(dbVehicle);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return (true, String.Empty); return (true, null);
} }
public async Task<bool> IsVehicleExists(int id) public async Task<bool> IsVehicleExists(int id)

View File

@ -6,7 +6,6 @@ public class AddressParameters : ParametersBase
public AddressParameters() public AddressParameters()
{ {
Sort = "id";
Fields = DefaultFields; Fields = DefaultFields;
} }

View File

@ -6,7 +6,6 @@ public class CityParameters : ParametersBase
public CityParameters() public CityParameters()
{ {
Sort = "id";
Fields = DefaultFields; Fields = DefaultFields;
} }

View File

@ -6,7 +6,6 @@ public class CompanyParameters : ParametersBase
public CompanyParameters() public CompanyParameters()
{ {
Sort = "id";
Fields = DefaultFields; Fields = DefaultFields;
} }

View File

@ -6,7 +6,6 @@ public class CountryParameters : ParametersBase
public CountryParameters() public CountryParameters()
{ {
Sort = "id";
Fields = DefaultFields; Fields = DefaultFields;
} }

View File

@ -6,7 +6,6 @@ public class ReviewParameters : ParametersBase
public ReviewParameters() public ReviewParameters()
{ {
Sort = "id";
Fields = DefaultFields; Fields = DefaultFields;
} }

View File

@ -7,7 +7,6 @@ public class RouteAddressParameters : ParametersBase
public RouteAddressParameters() public RouteAddressParameters()
{ {
Sort = "id";
Fields = DefaultFields; Fields = DefaultFields;
} }

View File

@ -6,7 +6,6 @@ public class RouteParameters : ParametersBase
public RouteParameters() public RouteParameters()
{ {
Sort = "id";
Fields = DefaultFields; Fields = DefaultFields;
} }

View File

@ -6,7 +6,6 @@ public class StateParameters : ParametersBase
public StateParameters() public StateParameters()
{ {
Sort = "id";
Fields = DefaultFields; Fields = DefaultFields;
} }

View File

@ -6,7 +6,6 @@ public class TicketParameters : ParametersBase
public TicketParameters() public TicketParameters()
{ {
Sort = "id";
Fields = DefaultFields; Fields = DefaultFields;
} }

View File

@ -7,7 +7,6 @@ public class VehicleEnrollmentParameters : ParametersBase
public VehicleEnrollmentParameters() public VehicleEnrollmentParameters()
{ {
Sort = "id";
Fields = DefaultFields; Fields = DefaultFields;
} }

View File

@ -7,7 +7,6 @@ public class VehicleParameters : ParametersBase
public VehicleParameters() public VehicleParameters()
{ {
Sort = "id";
Fields = DefaultFields; Fields = DefaultFields;
} }