Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions API/Controllers/BookCopyController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using Application.Queries.BookQueries.GetBookCopyById;
using Application.Dtos.BookCopyDtos;
using Application.Commands.BookCopyCommands.AddBookCopy;

namespace API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BookCopyController(IMediator mediator, ILogger<BookController> logger) : ControllerBase
{
private readonly IMediator _mediator = mediator;
private readonly ILogger<BookController> _logger = logger;

[HttpGet]
[Route("GetAllBookCopies")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetAllBookCopies()
{
return Ok();
}

[Route("GetBookCopyById/{bookId}")]
[HttpGet]
[SwaggerOperation(Description = "Gets a book by Id")]
[SwaggerResponse(200, "Successfully retrieved Book.")]
[SwaggerResponse(400, "Invalid input data")]
[SwaggerResponse(404, "Book not found")]
public async Task<IActionResult> GetBook([FromRoute] Guid bookId)
{
try
{
var operationResult = await _mediator.Send(new GetBookCopyByIdQuery(bookId));
if (operationResult.IsSuccess)
{
return Ok(operationResult.Data);
}
return BadRequest(new { message = operationResult.Message, errors = operationResult.ErrorMessage });
}

catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while fetching Book with ID: {id} at {time}", bookId, DateTime.Now.ToString("MM/dd/yyyy hh:mm tt"));
return StatusCode(500, "An error occurred while processing your request.");
}
}

[HttpPost]
[Route("AddBookCopy")]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> AddBookCopy([FromBody] AddBookCopyDto dto)
{
try
{
var operationResult = await _mediator.Send(new AddBookCopyCommand(dto));
if (operationResult.IsSuccess)
{
return Ok(operationResult.Data);
}
return BadRequest(new { message = operationResult.Message, errors = operationResult.ErrorMessage });
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while creating a new BookCopy at {time}", DateTime.Now.ToString("MM/dd/yyyy hh:mm tt"));
return StatusCode(500, "An error occurred while processing your request.");
}
}

[HttpPut]
[Route("UpdateBookCopy")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> UpdateBookCopy()
{
return Ok();
}

[HttpDelete]
[Route("DeleteBookCopy")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> DeleteBookCopy(Guid id)
{
return Ok();
}
}
}
11 changes: 10 additions & 1 deletion API/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ public static void Main(string[] args)
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddCors(options =>
{
options.AddPolicy(
name: "LocalHostReactApp",
builder =>
{
builder.WithOrigins("http://localhost:3000").AllowAnyHeader().AllowAnyMethod();
});
});

var jwtSettings = builder.Configuration.GetSection("JwtSettings");
byte[] secretKey = Encoding.ASCII.GetBytes(jwtSettings["SecretKey"]!);
Expand Down Expand Up @@ -105,7 +114,7 @@ public static void Main(string[] args)
c.RoutePrefix = "swagger"; // Set Swagger UI at the app's root
});
}

app.UseCors("LocalHostReactApp");
app.UseHttpsRedirection();

app.UseAuthentication(); // Ensure this is added before UseAuthorization
Expand Down
4 changes: 4 additions & 0 deletions Application/Application.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,8 @@
<ProjectReference Include="..\Domain\Domain.csproj" />
</ItemGroup>

<ItemGroup>
<Folder Include="Queries\BookCopyQueries\GetAllBookCopies\" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Application.Dtos.BookCopyDtos;
using Application.Dtos.BookDtos;
using Application.Models;
using MediatR;

namespace Application.Commands.BookCopyCommands.AddBookCopy
{
public class AddBookCopyCommand(AddBookCopyDto dto) : IRequest<OperationResult<GetBookDto>>
{
public AddBookCopyDto Dto { get; set; } = dto;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using Application.Dtos.BookDtos;
using Application.Interfaces.RepositoryInterfaces;
using Application.Models;
using AutoMapper;
using Domain.Entities.Locations;
using MediatR;

namespace Application.Commands.BookCopyCommands.AddBookCopy
{
internal class AddBookCopyCommandHandler(IGenericRepository<BookCopy, Guid> repository, IMapper mapper) : IRequestHandler<AddBookCopyCommand, OperationResult<GetBookDto>>
{
private readonly IGenericRepository<BookCopy, Guid> _repository = repository;
public readonly IMapper _mapper = mapper;

public async Task<OperationResult<GetBookDto>> Handle(AddBookCopyCommand request, CancellationToken cancellationToken)
{
try
{
BookCopy bookCopyToCreate = new()
{
CopyId = Guid.NewGuid(),
BookId = request.Dto.BookId,
BranchId = request.Dto.BranchId,
Status = request.Dto.Status
};

var createdBookCopy = await _repository.AddAsync(bookCopyToCreate);
var mappedBookCopy = _mapper.Map<GetBookDto>(createdBookCopy);

return OperationResult<GetBookDto>.Success(mappedBookCopy);
}
catch (Exception ex)
{
throw new Exception("Book copy not added", ex);

}
}
}
}
4 changes: 4 additions & 0 deletions Application/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,16 @@ public static IServiceCollection AddApplication(this IServiceCollection services
var assembly = typeof(DependencyInjection).Assembly;
services.AddMediatR(configuration => configuration.RegisterServicesFromAssembly(assembly));
services.AddAutoMapper(assembly); // Specify the assembly to resolve ambiguity

// Register services
services.AddScoped<TokenHelper>();
services.AddScoped<IPasswordEncryptionService, PasswordEncryptionService>();
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));

// Mapping profiles
services.AddAutoMapper(typeof(UserMappingProfiles).Assembly);
services.AddAutoMapper(typeof(BookMappingProfiles).Assembly);
services.AddAutoMapper(typeof(BookCopyMappingProfiles).Assembly);

// Register validators
services.AddValidatorsFromAssemblyContaining<AddAuthorCommandValidator>();
Expand Down
17 changes: 17 additions & 0 deletions Application/Dtos/BookCopyDtos/AddBookCopyDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@

using Domain.Entities.Core;
using Domain.Entities.Locations;

namespace Application.Dtos.BookCopyDtos
{
public class AddBookCopyDto
{
public Guid BookId { get; set; }
public int BranchId { get; set; }
public string? Status { get; set; }

//// Navigation properties
//public Book Book { get; set; }
//public LibraryBranch Branch { get; set; }
}
}
11 changes: 11 additions & 0 deletions Application/Dtos/BookCopyDtos/GetBookCopyDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

namespace Application.Dtos.BookCopyDtos
{
public class GetBookCopyDto
{
public int BranchId { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public string? ContactInfo { get; set; }
}
}
14 changes: 14 additions & 0 deletions Application/Mappings/BookCopyMappingProfiles.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Application.Dtos.BookCopyDtos;
using AutoMapper;
using Domain.Entities.Core;

namespace Application.Mappings
{
public class BookCopyMappingProfiles : Profile
{
public BookCopyMappingProfiles()
{
CreateMap<Book, GetBookCopyDto>();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using MediatR;
using Application.Models;
using Application.Dtos.BookCopyDtos;

namespace Application.Queries.BookQueries.GetBookCopyById
{
public class GetBookCopyByIdQuery(Guid bookId) : IRequest<OperationResult<GetBookCopyDto>>
{
public Guid Id { get; } = bookId;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Application.Dtos.BookCopyDtos;
using Application.Interfaces.RepositoryInterfaces;
using Application.Models;
using Application.Queries.BookQueries.GetBookCopyById;
using AutoMapper;
using Domain.Entities.Locations;
using MediatR;

namespace Application.Queries.BookCopyQueries.GetBookCopyById
{
internal class GetBookCopyByIdQueryHandler(IGenericRepository<BookCopy, Guid> repository, IMapper mapper) : IRequestHandler<GetBookCopyByIdQuery, OperationResult<GetBookCopyDto>>
{
private readonly IGenericRepository<BookCopy, Guid> _repository = repository;
private readonly IMapper _mapper = mapper;

public async Task<OperationResult<GetBookCopyDto>> Handle(GetBookCopyByIdQuery request, CancellationToken cancellationToken)
{
try
{
BookCopy book = await _repository.GetByIdAsync(request.Id);
if (book is null)
{
return OperationResult<GetBookCopyDto>.Failure("The book was not found in the collection");
}

var mappedBook = _mapper.Map<GetBookCopyDto>(book);
return OperationResult<GetBookCopyDto>.Success(mappedBook, "Operation successful");
}
catch (Exception ex)
{
throw new ApplicationException("An error occurred while retrieving object from collection.", ex);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Application.Queries.BookQueries.GetBookCopyById;
using FluentValidation;


namespace Application.Queries.BookCopyQueries.GetBookCopyById
{
public class GetBookCopyByIdQueryValidator : AbstractValidator<GetBookCopyByIdQuery>
{
public GetBookCopyByIdQueryValidator()
{
RuleFor(x => x.Id)
.Must(id => id != System.Guid.Empty).WithMessage("Id is required, cannot be empty.");
}
}
}
10 changes: 8 additions & 2 deletions Domain/Entities/Locations/BookCopy.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using Domain.Entities.Core;
using Domain.Entities.Transactions;
using Domain.Interfaces;
using System.ComponentModel.DataAnnotations;

namespace Domain.Entities.Locations
{
public class BookCopy
public class BookCopy : IEntity<Guid>
{
[Key]
public Guid CopyId { get; set; }
Expand All @@ -17,6 +18,11 @@ public class BookCopy
public LibraryBranch Branch { get; set; }
public ICollection<Borrowing> Borrowings { get; set; }
public ICollection<Reservation> Reservations { get; set; }
}

Guid IEntity<Guid>.Id
{
get => CopyId;
set => CopyId = value;
}
}
}
Loading