Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Articles management #5

Merged
merged 6 commits into from
Jan 19, 2024
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
52 changes: 50 additions & 2 deletions Domus.Api/Controllers/ArticlesController.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
using Domus.Api.Controllers.Base;
using Domus.Service.Constants;
using Domus.Service.Interfaces;
using Domus.Service.Models.Requests.Articles;
using Domus.Service.Models.Requests.Base;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Domus.Api.Controllers;
namespace Domus.Api.Controllers;

[Authorize(Roles = $"{UserRoleConstants.ADMIN},{UserRoleConstants.STAFF}", AuthenticationSchemes = "Bearer")]
[Route("api/[controller]")]
public class ArticlesController : BaseApiController
{
Expand All @@ -14,11 +19,54 @@ public ArticlesController(IArticleService articleService)
_articleService = articleService;
}

[AllowAnonymous]
[HttpGet]
public async Task<IActionResult> GetPaginatedArticles([FromQuery] BasePaginatedRequest request)
{
return await ExecuteServiceLogic(
async () => await _articleService.GetPaginatedArticles(request).ConfigureAwait(false)
).ConfigureAwait(false);
}

[AllowAnonymous]
[HttpGet("all")]
public async Task<IActionResult> GetAllArticles()
{
return await ExecuteServiceLogic(
async () => await _articleService.GetAllArticles().ConfigureAwait(false)
async () => await _articleService.GetAllArticles().ConfigureAwait(false)
).ConfigureAwait(false);
}

[AllowAnonymous]
[HttpGet("{id:guid}")]
public async Task<IActionResult> GetArticle(Guid id)
{
return await ExecuteServiceLogic(
async () => await _articleService.GetArticle(id).ConfigureAwait(false)
).ConfigureAwait(false);
}

[HttpPost]
public async Task<IActionResult> CreateArticle(CreateArticleRequest request)
{
return await ExecuteServiceLogic(
async () => await _articleService.CreateArticle(request).ConfigureAwait(false)
).ConfigureAwait(false);
}

[HttpPut("{id:guid}")]
public async Task<IActionResult> UpdateArticle(UpdateArticleRequest request, Guid articleId)
{
return await ExecuteServiceLogic(
async () => await _articleService.UpdateArticle(request, articleId).ConfigureAwait(false)
).ConfigureAwait(false);
}

[HttpDelete("{id:guid}")]
public async Task<IActionResult> DeleteArticle(Guid id)
{
return await ExecuteServiceLogic(
async () => await _articleService.DeleteArticle(id).ConfigureAwait(false)
).ConfigureAwait(false);
}
}
32 changes: 19 additions & 13 deletions Domus.Api/Controllers/Base/BaseApiController.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using System.Runtime.CompilerServices;
using Domus.Api.Models.Common;
using Domus.Api.Constants;
using Domus.Common.Exceptions;
using Domus.Common.Helpers;
using Domus.Service.Models;
using Domus.Service.Models.Common;
using Microsoft.AspNetCore.Mvc;
using NLog;
using ILogger = NLog.ILogger;
Expand All @@ -17,22 +17,28 @@ private IActionResult BuildSuccessResult(ServiceActionResult result)
{
var successResult = new ApiResponse(true)
{
Data = result.Data
Data = result.Data,
StatusCode = StatusCodes.Status200OK
};

var detail = result.Detail ?? string.Empty;
var detail = result.Detail ?? ApiMessageConstants.SUCCESS;
successResult.AddSuccessMessage(detail);
return base.Ok(successResult);
}

private IActionResult BuildErrorResult(string detail)
private IActionResult BuildErrorResult(Exception ex)
{
var errorResult = new ApiResponse(false)
{
};
errorResult.AddErrorMessage(detail);
var errorResult = new ApiResponse(false);
errorResult.AddErrorMessage(ex.Message);

var statusCode = StatusCodes.Status500InternalServerError;
if (ex.GetType().IsAssignableTo(typeof(INotFoundException)))
statusCode = StatusCodes.Status404NotFound;
else if (ex.GetType().IsAssignableTo(typeof(IBusinessException)))
statusCode = StatusCodes.Status409Conflict;

return StatusCode(StatusCodes.Status409Conflict, errorResult);
errorResult.StatusCode = statusCode;
return base.Ok(errorResult);
}

protected async Task<IActionResult> ExecuteServiceLogic(Func<Task<ServiceActionResult>> serviceLogicFunc)
Expand Down Expand Up @@ -60,7 +66,7 @@ protected async Task<IActionResult> ExecuteServiceLogic(Func<Task<ServiceActionR

return result.IsSuccess ? BuildSuccessResult(result) : Problem(result.Detail);
}
catch (Exception e)
catch (Exception ex)
{
if (errorHandler is not null)
await errorHandler();
Expand All @@ -69,10 +75,10 @@ protected async Task<IActionResult> ExecuteServiceLogic(Func<Task<ServiceActionR
StringInterpolationHelper.Append(methodInfo);
StringInterpolationHelper.Append($"]]. IsSuccess: false");
StringInterpolationHelper.Append(". Detail: ");
StringInterpolationHelper.Append(e.Message);
StringInterpolationHelper.Append(ex.Message);
logger.Info(StringInterpolationHelper.BuildAndClear());

return e.GetType().IsAssignableTo(typeof(IBusinessException)) ? BuildErrorResult(e.Message) : StatusCode(StatusCodes.Status500InternalServerError, e.Message);
return BuildErrorResult(ex);
}
finally
{
Expand Down
1 change: 1 addition & 0 deletions Domus.Api/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ public static IServiceCollection RegisterServices(this IServiceCollection servic
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IUserTokenRepository, UserTokenRepository>();
services.AddScoped<IArticleRepository, ArticleRepository>();
services.AddScoped<IArticleCategoryRepository, ArticleCategoryRepository>();
services.AddScoped<IAuthService, AuthService>();
services.AddScoped<IArticleService, ArticleService>();
services.AddScoped<IJwtService, JwtService>();
Expand Down
1 change: 0 additions & 1 deletion Domus.Api/Middlewares/GlobalExceptionHanlderMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using Domus.Api.Models.Common;
using Domus.Service.Enums;
using Domus.Service.Models.Common;
using NLog;
Expand Down
5 changes: 5 additions & 0 deletions Domus.Common/Exceptions/INotFoundException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
namespace Domus.Common.Exceptions;

public interface INotFoundException
{
}
31 changes: 16 additions & 15 deletions Domus.Common/Helpers/PaginationHelper.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using AutoMapper;
using Domus.Common.Models;

namespace NetCore.WebApiCommon.Core.Common.Helpers;
namespace Domus.Common.Helpers;

public static class PaginationHelper
{
Expand All @@ -14,7 +14,7 @@ public static PaginatedResult BuildPaginatedResult<T, TDto>(IMapper? mapper, IQu
{
PageIndex = 1,
PageSize = pageSize,
Data = new List<TDto>(),
Items = new List<TDto>(),
LastPage = 1,
IsLastPage = true,
Total = total
Expand All @@ -36,22 +36,23 @@ public static PaginatedResult BuildPaginatedResult<T, TDto>(IMapper? mapper, IQu
Total = total
};

if (pageIndex > lastPage / 2)
{
var mod = total % pageSize;
var skip = Math.Max((lastPage - pageIndex - 1) * pageSize + mod, 0);
var take = isLastPage ? mod : pageSize;
var reverse = source.Reverse();

var res = reverse.Skip(skip).Take(take);
paginatedResult.Data = mapper is null ? res.Reverse() : mapper.Map<TDto>(res.Reverse());
return paginatedResult;
}
// if (pageIndex > lastPage / 2)
// {
// var mod = total % pageSize;
// var skip = Math.Max((lastPage - pageIndex - 1) * pageSize + mod, 0);
// var take = isLastPage ? mod : pageSize;
// var reverse = source.Reverse();
//
// var res = reverse.Skip(skip).Take(take);
// var list = res.Reverse().AsEnumerable().ToList();
// paginatedResult.Items = mapper is null ? res.Reverse() : mapper.Map<IEnumerable<TDto>>(list);
// return paginatedResult;
// }

var results = source.Skip((pageIndex - 1) * pageSize)
.Take(pageSize);
paginatedResult.Data = results;
paginatedResult.Data = mapper is null ? results : mapper.Map<TDto>(results);
paginatedResult.Items = results;
paginatedResult.Items = mapper is null ? results : mapper.Map<IEnumerable<TDto>>(results.AsEnumerable());
return paginatedResult;
}

Expand Down
2 changes: 1 addition & 1 deletion Domus.Common/Models/PaginatedResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ public class PaginatedResult
public long LastPage { get; set; }
public bool IsLastPage { get; set; }
public long Total { get; set; }
public object? Data { get; set; }
public object? Items { get; set; }
}
11 changes: 11 additions & 0 deletions Domus.DAL/Implementations/ArticleCategoryRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Domus.DAL.Interfaces;
using Domus.Domain.Entities;

namespace Domus.DAL.Implementations;

public class ArticleCategoryRepository : GenericRepository<ArticleCategory>, IArticleCategoryRepository
{
public ArticleCategoryRepository(IAppDbContext dbContext) : base(dbContext)
{
}
}
7 changes: 7 additions & 0 deletions Domus.DAL/Interfaces/IArticleCategoryRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
using Domus.Domain.Entities;

namespace Domus.DAL.Interfaces;

public interface IArticleCategoryRepository : IGenericRepository<ArticleCategory>
{
}
2 changes: 1 addition & 1 deletion Domus.Domain/DatabaseMappings/ArticleImageModelMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable(nameof(ArticleImage));

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();

entity.HasOne(d => d.Article).WithMany(p => p.ArticleImages)
.HasForeignKey(d => d.ArticleId)
Expand Down
2 changes: 1 addition & 1 deletion Domus.Domain/DatabaseMappings/ArticleModelMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable(nameof(Article));

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt).HasColumnType("date");
entity.Property(e => e.CreatedBy).HasMaxLength(450);
entity.Property(e => e.IsDeleted).HasDefaultValueSql("((0))");
Expand Down
2 changes: 1 addition & 1 deletion Domus.Domain/DatabaseMappings/ContractModleMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable(nameof(Contract));

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt).HasColumnType("date");
entity.Property(e => e.CreatedBy).HasMaxLength(450);
entity.Property(e => e.EndDate).HasColumnType("date");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable(nameof(NegotiationMessage));

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.Property(e => e.SentAt).HasColumnType("date");

entity.HasOne(d => d.QuotationNegotiationLog)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable(nameof(ProductAttribute));

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.Property(e => e.AttributeName).HasMaxLength(256);
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable(nameof(ProductAttributeValue));

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.Property(e => e.Value).HasMaxLength(256);
entity.Property(e => e.ValueType).HasMaxLength(256);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable(nameof(ProductCategory));

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.Property(e => e.IsDeleted).HasDefaultValueSql("((0))");
entity.Property(e => e.Name).HasMaxLength(256);
});
Expand Down
2 changes: 1 addition & 1 deletion Domus.Domain/DatabaseMappings/ProductDetailModelMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable(nameof(ProductDetail));

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();

entity.HasOne(d => d.Product).WithMany(p => p.ProductDetails)
.HasForeignKey(d => d.ProductId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable("ProductDetail_Quotation");

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.Property(e => e.MonetaryUnit).HasMaxLength(256);
entity.Property(e => e.QuantityType).HasMaxLength(256);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable("ProductDetail_QuotationRevision");

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.Property(e => e.Version).HasDefaultValueSql("((0))");

entity.HasOne(d => d.ProductDetailQuotation).WithMany(p => p.ProductDetailQuotationRevisions)
Expand Down
2 changes: 1 addition & 1 deletion Domus.Domain/DatabaseMappings/ProductImageModelMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable(nameof(ProductImage));

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();

entity.HasOne(d => d.ProductDetail).WithMany(p => p.ProductImages)
.HasForeignKey(d => d.ProductDetailId)
Expand Down
2 changes: 1 addition & 1 deletion Domus.Domain/DatabaseMappings/ProductModelMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable(nameof(Product));

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.Property(e => e.Brand).HasMaxLength(256);
entity.Property(e => e.Color).HasMaxLength(256);
entity.Property(e => e.IsDeleted).HasDefaultValueSql("((0))");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable(nameof(QuotationNegotiationLog));

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.Property(e => e.CloseAt).HasColumnType("date");
entity.Property(e => e.IsClosed).HasDefaultValueSql("((0))");
entity.Property(e => e.StartAt).HasColumnType("date");
Expand Down
4 changes: 2 additions & 2 deletions Domus.Domain/DatabaseMappings/QuotationStatusModelMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable(nameof(QuotationStatus));

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.Property(e => e.StatusType).HasMaxLength(256);
});
}
}
}
4 changes: 2 additions & 2 deletions Domus.Domain/DatabaseMappings/ServiceModelMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ public void Map(ModelBuilder modelBuilder)
{
entity.ToTable(nameof(Service));

entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.Property(e => e.MonetaryUnit).HasMaxLength(256);
entity.Property(e => e.Name).HasMaxLength(256);
});
}
}
}
14 changes: 14 additions & 0 deletions Domus.Domain/Dtos/DtoArticle.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace Domus.Domain.Dtos;

public class DtoArticle
{
public Guid Id { get; set; }

public string Title { get; set; } = null!;

public string Content { get; set; } = null!;

public DtoArticleCategory ArticleCategory { get; set; } = null!;

public ICollection<DtoArticleImage> ArticleImages { get; set; } = new List<DtoArticleImage>();
}
Loading
Loading