Merge pull request 'Add Tag CRUD' (#2) from feature/add-tag-crud into development

Reviewed-on: https://gitea.white-enciso.pro/AgileWebs/Core.Inventory.DAL/pulls/2
Reviewed-by: efrain_marin <efrain.marin@agilewebs.com>
Reviewed-by: Sergio Matías <sergio.matias@agilewebs.com>
This commit is contained in:
OscarMmtz 2025-08-01 22:12:26 +00:00
commit 1f9bae385c
6 changed files with 528 additions and 1 deletions

View File

@ -0,0 +1,190 @@
using Asp.Versioning;
using Core.Adapters.Lib;
using Core.Blueprint.Logging;
using Core.Blueprint.Mongo;
using Core.Inventory.Domain.Contexts.Inventory.Request;
using Core.Inventory.Provider.Contracts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Core.Inventory.DAL.API.Controllers
{
/// <summary>
/// Handles all requests for Tag authentication.
/// </summary>
[ApiVersion(MimeTypes.ApplicationVersion)]
[Route("api/v{api-version:apiVersion}/[controller]")]
[Produces(MimeTypes.ApplicationJson)]
[Consumes(MimeTypes.ApplicationJson)]
[ApiController]
[AllowAnonymous]
public class TagController(ITagProvider service) : ControllerBase
{
/// <summary>
/// Gets all the Tags.
/// </summary>
/// <returns>The <see cref="IEnumerable{TagAdapter}"/> found entities.</returns>
/// <response code="200">The Tags found.</response>
/// <response code="404">The Tags not found error.</response>
/// <response code="500">The service internal error.</response>
[HttpGet]
[Consumes(MimeTypes.ApplicationJson)]
[Produces(MimeTypes.ApplicationJson)]
[ProducesResponseType(typeof(IEnumerable<TagAdapter>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetAllTagsAsync(CancellationToken cancellationToken)
{
var result = await service.GetAllTags(cancellationToken).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Gets all the Tags by Tag identifiers.
/// </summary>
/// <param name="Tags">The list of Tag identifiers.</param>
/// <returns>The <see cref="IEnumerable{TagAdapter}"/> found entities.</returns>
/// <response code="200">The Tags found.</response>
/// <response code="404">The Tags not found error.</response>
/// <response code="500">The service internal error.</response>
[HttpPost]
[Route("GetTagList")]
[Consumes(MimeTypes.ApplicationJson)]
[Produces(MimeTypes.ApplicationJson)]
[ProducesResponseType(typeof(IEnumerable<TagAdapter>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetAllTagsByList([FromBody] string[] tags, CancellationToken cancellationToken)
{
if (tags == null || !tags.Any())
{
return BadRequest("Tag identifiers are required.");
}
var result = await service.GetAllTagsByList(tags, cancellationToken).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Gets the Tag by identifier.
/// </summary>
/// <param name="id">The Tag identifier.</param>
/// <returns>The <see cref="TagAdapter"/> found entity.</returns>
/// <response code="200">The Tag found.</response>
/// <response code="404">The Tag not found error.</response>
/// <response code="500">The service internal error.</response>
[HttpGet]
[Route("{id}")]
[Consumes(MimeTypes.ApplicationJson)]
[Produces(MimeTypes.ApplicationJson)]
[ProducesResponseType(typeof(TagAdapter), StatusCodes.Status200OK)]
public async Task<IActionResult> GetTagByIdAsync([FromRoute] string id, CancellationToken cancellationToken)
{
var result = await service.GetTagById(id, cancellationToken).ConfigureAwait(false);
if (result == null)
{
return NotFound("Entity not found");
}
return Ok(result);
}
/// <summary>
/// Creates a new Tag.
/// </summary>
/// <param name="newTag">The Tag to be added.</param>
/// <returns>The <see cref="TagAdapter"/> created entity.</returns>
/// <response code="201">The Tag created.</response>
/// <response code="422">The Tag could not be created.</response>
/// <response code="500">The service internal e|ror.</response>
[HttpPost]
[ProducesResponseType(typeof(TagAdapter), StatusCodes.Status201Created)]
public async Task<IActionResult> CreateTagAsync([FromBody] TagRequest newTag, CancellationToken cancellationToken)
{
var result = await service.CreateTag(newTag, cancellationToken).ConfigureAwait(false);
return Created("CreatedWithIdAsync", result);
}
/// <summary>
/// Updates a full Tag by identifier.
/// </summary>
/// <param name="entity">The Tag to update.</param>
/// <param name="id">The Tag identifier.</param>
/// <returns>The <see cref="TagAdapter"/> updated entity.</returns>
/// <response code="200">The Tag updated.</response>
/// <response code="404">The Tag not found.</response>
/// <response code="422">The Tag could not be updated.</response>
/// <response code="500">The service internal error.</response>
[HttpPut]
[Route("{id}")]
[Consumes(MimeTypes.ApplicationJson)]
[Produces(MimeTypes.ApplicationJson)]
[ProducesResponseType(typeof(TagAdapter), StatusCodes.Status200OK)]
public async Task<IActionResult> UpdateTagAsync([FromRoute] string id, TagAdapter entity, CancellationToken cancellationToken)
{
if (id != entity.Id?.ToString())
{
return BadRequest("Tag ID mismatch");
}
var result = await service.UpdateTag(entity, cancellationToken).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Changes the status of the Tag.
/// </summary>
/// <param name="id">The Tag identifier.</param>
/// <param name="newStatus">The new status of the Tag.</param>
/// <returns>The <see cref="TagAdapter"/> updated entity.</returns>
/// <response code="200">The Tag updates.</response>
/// <response code="404">The Tag not found.</response>
/// <response code="422">The Tag could not be deleted.</response>
/// <response code="500">The service internal error.</response>
[HttpPatch]
[Route("{id}/{newStatus}/ChangeStatus")]
[Consumes(MimeTypes.ApplicationJson)]
[Produces(MimeTypes.ApplicationJson)]
[ProducesResponseType(typeof(TagAdapter), StatusCodes.Status200OK)]
public async Task<IActionResult> ChangeTagStatus([FromRoute] string id, [FromRoute] StatusEnum newStatus, CancellationToken cancellationToken)
{
var result = await service.ChangeTagStatus(id, newStatus, cancellationToken).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Adds a parentTag to the tag.
/// </summary>
/// <param name="tagId">The tag identifier.</param>
/// <param name="parentTagId">The parentTag identifier to add.</param>
/// <returns>The updated <see cref="TagAdapter"/> entity.</returns>
/// <response code="200">The tag with the updated parentTags.</response>
/// <response code="404">The tag or parentTag not found.</response>
/// <response code="500">The service internal error.</response>
[HttpPost]
[Route("{tagId}/ParentTags/{parentTagId}/Add")]
[ProducesResponseType(typeof(TagAdapter), StatusCodes.Status200OK)]
public async Task<IActionResult> AddParentTagAsync([FromRoute] string tagId, [FromRoute] string parentTagId, CancellationToken cancellationToken)
{
var result = await service.AddParentTag(tagId, parentTagId, cancellationToken).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Remove a parentTag to the tag.
/// </summary>
/// <param name="tagId">The tag identifier.</param>
/// <param name="parentTagId">The parentTag identifier to remove.</param>
/// <returns>The updated <see cref="TagAdapter"/> entity.</returns>
/// <response code="200">The tag with the updated parentTags.</response>
/// <response code="404">The tag or parentTag not found.</response>
/// <response code="500">The service internal error.</response>
[HttpDelete]
[Route("{tagId}/ParentTags/{parentTagId}/Remove")]
[ProducesResponseType(typeof(TagAdapter), StatusCodes.Status200OK)]
public async Task<IActionResult> RemoveParentTagAsync([FromRoute] string tagId, [FromRoute] string parentTagId, CancellationToken cancellationToken)
{
var result = await service.RemoveParentTag(tagId, parentTagId, cancellationToken).ConfigureAwait(false); ;
return Ok(result);
}
}
}

View File

@ -0,0 +1,67 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System.Text.Json.Serialization;
namespace Core.Inventory.Domain.Contexts.Inventory.Request
{
/// <summary>
/// Data transfer object (DTO) for adding Tag.
/// </summary>
public class TagRequest
{
/// <summary>
/// Gets or sets the tenantId of the Tag.
/// </summary>
[BsonElement("tenantId")]
[BsonRepresentation(BsonType.String)]
[JsonPropertyName("tenantId")]
public string TenantId { get; set; } = null!;
/// <summary>
/// Gets or sets the name of the Tag.
/// </summary>
[BsonElement("tagName")]
[BsonRepresentation(BsonType.String)]
[JsonPropertyName("tagName")]
public string TagName { get; set; } = null!;
/// <summary>
/// Gets or sets the typeId of the Tag.
/// </summary>
[BsonElement("typeId")]
[BsonRepresentation(BsonType.String)]
[JsonPropertyName("typeId")]
public string TypeId { get; set; } = null!;
/// <summary>
/// Gets or sets the parentTagId of the Tag.
/// </summary>
[BsonElement("parentTagId")]
[JsonPropertyName("parentTagId")]
public string[] ParentTagId { get; set; } = null!;
/// <summary>
/// Gets or sets the slug of the Tag.
/// </summary>
[BsonElement("slug")]
[BsonRepresentation(BsonType.String)]
[JsonPropertyName("slug")]
public string Slug { get; set; } = null!;
/// <summary>
/// Gets or sets the displayOrder of the Tag.
/// </summary>
[BsonElement("displayOrder")]
[BsonRepresentation(BsonType.String)]
[JsonPropertyName("displayOrder")]
public int DisplayOrder { get; set; }
/// <summary>
/// Gets or sets the icon of the Tag.
/// </summary>
[BsonElement("icon")]
[BsonRepresentation(BsonType.String)]
[JsonPropertyName("icon")]
public string Icon { get; set; } = null!;
}
}

View File

@ -0,0 +1,75 @@
using Core.Adapters.Lib;
using Core.Blueprint.Mongo;
using Core.Inventory.Domain.Contexts.Inventory.Request;
namespace Core.Inventory.Provider.Contracts
{
public interface ITagProvider
{
/// <summary>
/// Creates a new Tag.
/// </summary>
/// <param name="entity">The Tag to be created.</param>
/// <returns>A <see cref="{Task{TagAdapter}}"/> representing
/// the asynchronous execution of the service.</returns>
ValueTask<TagAdapter> CreateTag(TagRequest newTag, CancellationToken cancellationToken);
/// <summary>
/// Gets an Tag by identifier.
/// </summary>
/// <param name="id">The Tag identifier.</param>
/// <returns>A <see cref="{Task{TagAdapter}}"/> representing
/// the asynchronous execution of the service.</returns>
ValueTask<TagAdapter> GetTagById(string _id, CancellationToken cancellationToken);
/// <summary>
/// Gets all the Tags.
/// </summary>
/// <returns>A <see cref="{Task{IEnumerbale{TagAdapter}}}"/> representing
/// the asynchronous execution of the service.</returns>
ValueTask<IEnumerable<TagAdapter>> GetAllTags(CancellationToken cancellationToken);
/// <summary>
/// Gets all the Tags by Tags identifier list.
/// </summary>
/// <param name="Tags">The list of Tags identifiers.</param>
/// <returns>A <see cref="Task{IEnumerable{TagAdapter}}"/> representing
/// the asynchronous execution of the service.</returns>
ValueTask<IEnumerable<TagAdapter>> GetAllTagsByList(string[] Tags, CancellationToken cancellationToken);
/// <summary>
/// Changes the status of the Tag.
/// </summary>
/// <param name="id">The Tag identifier.</param>
/// <param name="newStatus">The new status of the Tag.</param>
/// <returns>The <see cref="TagAdapter"/> updated entity.</returns>
/// <returns>A <see cref="{Task{TagAdapter}}"/> representing
/// the asynchronous execution of the service.</returns>
ValueTask<TagAdapter> ChangeTagStatus(string id, StatusEnum newStatus, CancellationToken cancellationToken);
/// <summary>
/// Updates a Tag by id.
/// </summary>
/// <param name="entity">The Tag to be updated.</param>
/// <param name="id">The Tag identifier.</param>
/// <returns>A <see cref="{Task{TagAdapter}}"/> representing
/// the asynchronous execution of the service.</returns>
ValueTask<TagAdapter> UpdateTag(TagAdapter entity, CancellationToken cancellationToken);
/// <summary>
/// Adds a parentTag to the tag.
/// </summary>
/// <param name="tagId">The identifier of the tag to whom the parentTag will be added.</param>
/// <param name="parentTagId">The identifier of the parentTag to add.</param>
/// <returns>A <see cref="Task{TagAdapter}"/> representing the asynchronous operation, with the updated tag object.</returns>
ValueTask<TagAdapter> AddParentTag(string tagId, string parentTagId, CancellationToken cancellationToken);
/// <summary>
/// Removes a parentTag from the tag.
/// </summary>
/// <param name="tagId">The identifier of the tag to whom the parentTag will be added.</param>
/// <param name="parentTagId">The identifier of the parentTag to add.</param>
/// <returns>A <see cref="Task{TagAdapter}"/> representing the asynchronous operation, with the updated tag object.</returns>
ValueTask<TagAdapter> RemoveParentTag(string tagId, string parentTagId, CancellationToken cancellationToken);
}
}

View File

@ -7,7 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Adapters.Lib" Version="1.0.9" />
<PackageReference Include="Adapters.Lib" Version="1.0.10" />
<PackageReference Include="Core.Blueprint.Mongo" Version="1.0.0" />
<PackageReference Include="Core.Blueprint.Redis" Version="1.0.2" />
<PackageReference Include="Mapster" Version="7.4.0" />

View File

@ -0,0 +1,192 @@
using Core.Adapters.Lib;
using Core.Blueprint.Mongo;
using Core.Blueprint.Redis;
using Core.Blueprint.Redis.Helpers;
using Core.Inventory.Domain.Contexts.Inventory.Request;
using Core.Inventory.Provider.Contracts;
using Mapster;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
namespace Core.Inventory.Provider.Providers.Inventory
{
/// <summary>
/// Handles all services and business rules related to <see cref="TagAdapter"/>.
/// </summary>
public class TagProvider : ITagProvider
{
private readonly CollectionRepository<TagAdapter> repository;
private readonly CacheSettings cacheSettings;
private readonly IRedisCacheProvider cacheProvider;
public TagProvider(CollectionRepository<TagAdapter> repository,
IRedisCacheProvider cacheProvider,
IOptions<CacheSettings> cacheSettings)
{
this.repository = repository;
this.repository.CollectionInitialization();
this.cacheSettings = cacheSettings.Value;
this.cacheProvider = cacheProvider;
}
/// <summary>
/// Creates a new Tag.
/// </summary>
/// <param name="entity">The Tag to be created.</param>
/// <returns>A <see cref="{Task{TagAdapter}}"/> representing
/// the asynchronous execution of the service.</returns>
public async ValueTask<TagAdapter> CreateTag(TagRequest newTag, CancellationToken cancellationToken)
{
var tagCollection = newTag.Adapt<TagAdapter>();
await repository.InsertOneAsync(tagCollection);
return tagCollection;
}
/// <summary>
/// Gets an Tag by identifier.
/// </summary>
/// <param name="id">The Tag identifier.</param>
/// <returns>A <see cref="{Task{TagAdapter}}"/> representing
/// the asynchronous execution of the service.</returns>0
public async ValueTask<TagAdapter> GetTagById(string _id, CancellationToken cancellationToken)
{
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetTagById", _id);
var cachedData = await cacheProvider.GetAsync<TagAdapter>(cacheKey);
if (cachedData is not null) { return cachedData; }
var tag = await repository.FindByIdAsync(_id);
await cacheProvider.SetAsync(cacheKey, tag);
return tag;
}
/// <summary>
/// Gets all the Tags.
/// </summary>
/// <returns>A <see cref="{Task{IEnumerbale{TagAdapter}}}"/> representing
/// the asynchronous execution of the service.</returns>
public async ValueTask<IEnumerable<TagAdapter>> GetAllTags(CancellationToken cancellationToken)
{
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetTags");
var cachedData = await cacheProvider.GetAsync<IEnumerable<TagAdapter>>(cacheKey) ?? [];
if (cachedData.Any()) return cachedData;
var tags = await repository.AsQueryable();
await cacheProvider.SetAsync(cacheKey, tags);
return tags;
}
/// <summary>
/// Gets all the Tags by Tags identifier list.
/// </summary>
/// <param name="Tags">The list of Tags identifiers.</param>
/// <returns>A <see cref="Task{IEnumerable{TagAdapter}}"/> representing
/// the asynchronous execution of the service.</returns>
public async ValueTask<IEnumerable<TagAdapter>> GetAllTagsByList(string[] tags, CancellationToken cancellationToken)
{
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllTagsByList", tags);
var cachedData = await cacheProvider.GetAsync<IEnumerable<TagAdapter>>(cacheKey) ?? [];
if (cachedData.Any()) return cachedData;
var builder = Builders<TagAdapter>.Filter;
var filters = new List<FilterDefinition<TagAdapter>>();
if (tags != null || !tags.Any())
{
filters.Add(builder.In(x => x._Id, tags));
}
var finalFilter = filters.Any() ? builder.And(filters) : builder.Empty;
var TagsList = await repository.FilterByMongoFilterAsync(finalFilter);
await cacheProvider.SetAsync(cacheKey, TagsList);
return TagsList;
}
/// <summary>
/// Changes the status of the Tag.
/// </summary>
/// <param name="id">The Tag identifier.</param>
/// <param name="newStatus">The new status of the Tag.</param>
/// <returns>A <see cref="{Task{TagAdapter}}"/> representing
/// the asynchronous execution of the service.</returns>
public async ValueTask<TagAdapter> ChangeTagStatus(string id, StatusEnum newStatus, CancellationToken cancellationToken)
{
var entity = await repository.FindByIdAsync(id);
entity.Status = newStatus;
await repository.ReplaceOneAsync(entity);
return entity;
}
/// <summary>
/// Updates a Tag by id.
/// </summary>
/// <param name="entity">The Tag to be updated.</param>
/// <param name="id">The Tag identifier.</param>
/// <returns>A <see cref="{Task{TagAdapter}}"/> representing
/// the asynchronous execution of the service.</returns>
public async ValueTask<TagAdapter> UpdateTag(TagAdapter entity, CancellationToken cancellationToken)
{
await repository.ReplaceOneAsync(entity);
return entity;
}
/// <summary>
/// Adds a parentTag to the tag.
/// </summary>
/// <param name="tagId">The identifier of the tag to whom the parentTag will be added.</param>
/// <param name="parentTagId">The identifier of the parentTag to add.</param>
/// <returns>A <see cref="Task{TagAdapter}"/> representing the asynchronous operation, with the updated tag object.</returns>
public async ValueTask<TagAdapter> AddParentTag(string tagId, string parentTagId, CancellationToken cancellationToken)
{
var tag = await repository.FindOneAsync(
u => u._Id == tagId &&
u.Status == StatusEnum.Active);
var updatedParentTags = tag.ParentTagId.Append(parentTagId).Distinct().ToArray();
tag.ParentTagId = updatedParentTags;
await repository.ReplaceOneAsync(tag);
return tag;
}
/// <summary>
/// Remove a parentTag to the tag.
/// </summary>
/// <param name="tagId">The identifier of the tag to whom the parentTag will be removed.</param>
/// <param name="parentTagId">The identifier of the parentTag to add.</param>
/// <returns>A <see cref="Task{TagAdapter}"/> representing the asynchronous operation, with the updated tag object.</returns>
public async ValueTask<TagAdapter> RemoveParentTag(string tagId, string parentTagId, CancellationToken cancellationToken)
{
var tag = await repository.FindOneAsync(
u => u._Id == tagId &&
u.Status == StatusEnum.Active);
var updatedParentTags = tag.ParentTagId
?.Where(c => c != parentTagId)
.ToArray();
tag.ParentTagId = updatedParentTags;
await repository.ReplaceOneAsync(tag);
return tag;
}
}
}

View File

@ -20,6 +20,9 @@ namespace Core.Inventory.Provider
services.AddScoped<ITagTypeProvider, TagTypeProvider>();
services.AddScoped<CollectionRepository<TagTypeAdapter>>();
services.AddScoped<ITagProvider, TagProvider>();
services.AddScoped<CollectionRepository<TagAdapter>>();
return services;
}