Add category catalog management

This commit is contained in:
GonnaHetzMe committed 2026-11-19 13:07:48 +01:00
1 parent b1e0638979
commit 28fc49ea39
4 files changed
+185 -11

No files matched your search

@@ -17,12 +17,6 @@ public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
public Task<IReadOnlyList<BuildingDto>> GetBuildings([FromQuery] bool includeInactive = false, CancellationToken ct = default) => public Task<IReadOnlyList<BuildingDto>> GetBuildings([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
catalogs.GetBuildingsAsync(includeInactive && User.IsInRole(Roles.Admin), ct); catalogs.GetBuildingsAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
[HttpGet("issue-categories")]
public Task<IReadOnlyList<CategoryDto>> GetIssueCategories(CancellationToken ct) => catalogs.GetIssueCategoriesAsync(ct);
[HttpGet("proposal-categories")]
public Task<IReadOnlyList<CategoryDto>> GetProposalCategories(CancellationToken ct) => catalogs.GetProposalCategoriesAsync(ct);
[Authorize(Roles = Roles.Admin)] [Authorize(Roles = Roles.Admin)]
[HttpPost("buildings")] [HttpPost("buildings")]
[ProducesResponseType<BuildingDto>(StatusCodes.Status201Created)] [ProducesResponseType<BuildingDto>(StatusCodes.Status201Created)]
@@ -51,4 +45,76 @@ public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
await catalogs.DeactivateBuildingAsync(id, ct); await catalogs.DeactivateBuildingAsync(id, ct);
return NoContent(); return NoContent();
} }
/// <summary>Kategorie závad. Administrátor může zobrazit i deaktivované pomocí <c>includeInactive=true</c>.</summary>
[HttpGet("issue-categories")]
public Task<IReadOnlyList<CategoryDto>> GetIssueCategories([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
catalogs.GetIssueCategoriesAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
[Authorize(Roles = Roles.Admin)]
[HttpPost("issue-categories")]
[ProducesResponseType<CategoryDto>(StatusCodes.Status201Created)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public async Task<ActionResult<CategoryDto>> CreateIssueCategory(SaveCategoryRequest request, CancellationToken ct)
{
var category = await catalogs.CreateIssueCategoryAsync(request, ct);
return Created($"/api/issue-categories/{category.Id}", category);
}
[Authorize(Roles = Roles.Admin)]
[HttpPut("issue-categories/{id:int}")]
[ProducesResponseType<CategoryDto>(StatusCodes.Status200OK)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public Task<CategoryDto> UpdateIssueCategory(int id, SaveCategoryRequest request, CancellationToken ct) =>
catalogs.UpdateIssueCategoryAsync(id, request, ct);
/// <summary>Deaktivuje kategorii závad.</summary>
[Authorize(Roles = Roles.Admin)]
[HttpDelete("issue-categories/{id:int}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
public async Task<IActionResult> DeactivateIssueCategory(int id, CancellationToken ct)
{
await catalogs.DeactivateIssueCategoryAsync(id, ct);
return NoContent();
}
/// <summary>Kategorie návrhů. Administrátor může zobrazit i deaktivované pomocí <c>includeInactive=true</c>.</summary>
[HttpGet("proposal-categories")]
public Task<IReadOnlyList<CategoryDto>> GetProposalCategories([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
catalogs.GetProposalCategoriesAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
[Authorize(Roles = Roles.Admin)]
[HttpPost("proposal-categories")]
[ProducesResponseType<CategoryDto>(StatusCodes.Status201Created)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public async Task<ActionResult<CategoryDto>> CreateProposalCategory(SaveCategoryRequest request, CancellationToken ct)
{
var category = await catalogs.CreateProposalCategoryAsync(request, ct);
return Created($"/api/proposal-categories/{category.Id}", category);
}
[Authorize(Roles = Roles.Admin)]
[HttpPut("proposal-categories/{id:int}")]
[ProducesResponseType<CategoryDto>(StatusCodes.Status200OK)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public Task<CategoryDto> UpdateProposalCategory(int id, SaveCategoryRequest request, CancellationToken ct) =>
catalogs.UpdateProposalCategoryAsync(id, request, ct);
/// <summary>Deaktivuje kategorii návrhů.</summary>
[Authorize(Roles = Roles.Admin)]
[HttpDelete("proposal-categories/{id:int}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
public async Task<IActionResult> DeactivateProposalCategory(int id, CancellationToken ct)
{
await catalogs.DeactivateProposalCategoryAsync(id, ct);
return NoContent();
}
} }
@@ -12,6 +12,8 @@ public sealed record CategoryDto(int Id, string Name, string? Description, bool
public sealed record SaveBuildingRequest(string Code, string Name, string? Address); public sealed record SaveBuildingRequest(string Code, string Name, string? Address);
public sealed record SaveCategoryRequest(string Name, string? Description);
public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildingRequest> public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildingRequest>
{ {
public SaveBuildingRequestValidator() public SaveBuildingRequestValidator()
@@ -22,8 +24,18 @@ public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildin
} }
} }
public sealed class SaveCategoryRequestValidator : AbstractValidator<SaveCategoryRequest>
{
public SaveCategoryRequestValidator()
{
RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
RuleFor(x => x.Description).MaximumLength(500);
}
}
/// <summary>Číselníky pro formuláře a jejich správa administrátorem. Mazání = deaktivace.</summary> /// <summary>Číselníky pro formuláře a jejich správa administrátorem. Mazání = deaktivace.</summary>
public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequest> buildingValidator) public sealed class CatalogService(
IAppDbContext db, IValidator<SaveBuildingRequest> buildingValidator, IValidator<SaveCategoryRequest> categoryValidator)
{ {
public async Task<IReadOnlyList<BuildingDto>> GetBuildingsAsync(bool includeInactive, CancellationToken ct) => public async Task<IReadOnlyList<BuildingDto>> GetBuildingsAsync(bool includeInactive, CancellationToken ct) =>
await db.Buildings.AsNoTracking() await db.Buildings.AsNoTracking()
@@ -32,16 +44,16 @@ public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequ
.Select(b => new BuildingDto(b.Id, b.Code, b.Name, b.Address, b.IsActive)) .Select(b => new BuildingDto(b.Id, b.Code, b.Name, b.Address, b.IsActive))
.ToListAsync(ct); .ToListAsync(ct);
public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(CancellationToken ct) => public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(bool includeInactive, CancellationToken ct) =>
await db.IssueCategories.AsNoTracking() await db.IssueCategories.AsNoTracking()
.Where(c => c.IsActive) .Where(c => includeInactive || c.IsActive)
.OrderBy(c => c.Id) .OrderBy(c => c.Id)
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive)) .Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
.ToListAsync(ct); .ToListAsync(ct);
public async Task<IReadOnlyList<CategoryDto>> GetProposalCategoriesAsync(CancellationToken ct) => public async Task<IReadOnlyList<CategoryDto>> GetProposalCategoriesAsync(bool includeInactive, CancellationToken ct) =>
await db.ProposalCategories.AsNoTracking() await db.ProposalCategories.AsNoTracking()
.Where(c => c.IsActive) .Where(c => includeInactive || c.IsActive)
.OrderBy(c => c.Id) .OrderBy(c => c.Id)
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive)) .Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
.ToListAsync(ct); .ToListAsync(ct);
@@ -75,10 +87,68 @@ public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequ
await db.SaveChangesAsync(ct); await db.SaveChangesAsync(ct);
} }
public async Task<CategoryDto> CreateIssueCategoryAsync(SaveCategoryRequest request, CancellationToken ct)
{
await categoryValidator.ValidateAndThrowAsync(request, ct);
var category = new IssueCategory(request.Name, request.Description);
db.IssueCategories.Add(category);
await db.SaveChangesAsync(ct);
return ToDto(category);
}
public async Task<CategoryDto> UpdateIssueCategoryAsync(int id, SaveCategoryRequest request, CancellationToken ct)
{
await categoryValidator.ValidateAndThrowAsync(request, ct);
var category = await GetIssueCategoryAsync(id, ct);
category.Update(request.Name, request.Description);
await db.SaveChangesAsync(ct);
return ToDto(category);
}
public async Task DeactivateIssueCategoryAsync(int id, CancellationToken ct)
{
var category = await GetIssueCategoryAsync(id, ct);
category.Deactivate();
await db.SaveChangesAsync(ct);
}
public async Task<CategoryDto> CreateProposalCategoryAsync(SaveCategoryRequest request, CancellationToken ct)
{
await categoryValidator.ValidateAndThrowAsync(request, ct);
var category = new ProposalCategory(request.Name, request.Description);
db.ProposalCategories.Add(category);
await db.SaveChangesAsync(ct);
return ToDto(category);
}
public async Task<CategoryDto> UpdateProposalCategoryAsync(int id, SaveCategoryRequest request, CancellationToken ct)
{
await categoryValidator.ValidateAndThrowAsync(request, ct);
var category = await GetProposalCategoryAsync(id, ct);
category.Update(request.Name, request.Description);
await db.SaveChangesAsync(ct);
return ToDto(category);
}
public async Task DeactivateProposalCategoryAsync(int id, CancellationToken ct)
{
var category = await GetProposalCategoryAsync(id, ct);
category.Deactivate();
await db.SaveChangesAsync(ct);
}
private async Task<Building> GetBuildingAsync(int id, CancellationToken ct) => private async Task<Building> GetBuildingAsync(int id, CancellationToken ct) =>
await db.Buildings.SingleOrDefaultAsync(b => b.Id == id, ct) await db.Buildings.SingleOrDefaultAsync(b => b.Id == id, ct)
?? throw new NotFoundException($"Budova {id} neexistuje."); ?? throw new NotFoundException($"Budova {id} neexistuje.");
private async Task<IssueCategory> GetIssueCategoryAsync(int id, CancellationToken ct) =>
await db.IssueCategories.SingleOrDefaultAsync(c => c.Id == id, ct)
?? throw new NotFoundException($"Kategorie závad {id} neexistuje.");
private async Task<ProposalCategory> GetProposalCategoryAsync(int id, CancellationToken ct) =>
await db.ProposalCategories.SingleOrDefaultAsync(c => c.Id == id, ct)
?? throw new NotFoundException($"Kategorie návrhů {id} neexistuje.");
private async Task EnsureUniqueCodeAsync(string code, int? exceptId, CancellationToken ct) private async Task EnsureUniqueCodeAsync(string code, int? exceptId, CancellationToken ct)
{ {
var trimmed = code.Trim(); var trimmed = code.Trim();
@@ -87,4 +157,6 @@ public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequ
} }
private static BuildingDto ToDto(Building b) => new(b.Id, b.Code, b.Name, b.Address, b.IsActive); private static BuildingDto ToDto(Building b) => new(b.Id, b.Code, b.Name, b.Address, b.IsActive);
private static CategoryDto ToDto(IssueCategory c) => new(c.Id, c.Name, c.Description, c.IsActive);
private static CategoryDto ToDto(ProposalCategory c) => new(c.Id, c.Name, c.Description, c.IsActive);
} }
@@ -31,10 +31,20 @@ public sealed class IssueCategory
{ {
private IssueCategory() { } // EF Core private IssueCategory() { } // EF Core
public IssueCategory(string name, string? description) => Update(name, description);
public int Id { get; private set; } public int Id { get; private set; }
public string Name { get; private set; } = null!; public string Name { get; private set; } = null!;
public string? Description { get; private set; } public string? Description { get; private set; }
public bool IsActive { get; private set; } = true; public bool IsActive { get; private set; } = true;
public void Update(string name, string? description)
{
Name = name.Trim();
Description = string.IsNullOrWhiteSpace(description) ? null : description.Trim();
}
public void Deactivate() => IsActive = false;
} }
/// <summary>Oblast návrhu na zlepšení (tabulka <c>proposal_category</c>).</summary> /// <summary>Oblast návrhu na zlepšení (tabulka <c>proposal_category</c>).</summary>
@@ -42,8 +52,18 @@ public sealed class ProposalCategory
{ {
private ProposalCategory() { } // EF Core private ProposalCategory() { } // EF Core
public ProposalCategory(string name, string? description) => Update(name, description);
public int Id { get; private set; } public int Id { get; private set; }
public string Name { get; private set; } = null!; public string Name { get; private set; } = null!;
public string? Description { get; private set; } public string? Description { get; private set; }
public bool IsActive { get; private set; } = true; public bool IsActive { get; private set; } = true;
public void Update(string name, string? description)
{
Name = name.Trim();
Description = string.IsNullOrWhiteSpace(description) ? null : description.Trim();
}
public void Deactivate() => IsActive = false;
} }
@@ -1,5 +1,6 @@
using System.Data; using System.Data;
using Helpdesk.Application.Abstractions; using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Application.Statistics; using Helpdesk.Application.Statistics;
using Helpdesk.Domain.Auth; using Helpdesk.Domain.Auth;
using Helpdesk.Domain.Catalogs; using Helpdesk.Domain.Catalogs;
@@ -11,6 +12,7 @@ using Helpdesk.Infrastructure.Security;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using MySqlConnector;
namespace Helpdesk.Infrastructure.Persistence; namespace Helpdesk.Infrastructure.Persistence;
@@ -38,6 +40,20 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
public DbSet<NotificationDelivery> NotificationDeliveries => Set<NotificationDelivery>(); public DbSet<NotificationDelivery> NotificationDeliveries => Set<NotificationDelivery>();
public DbSet<PushDevice> PushDevices => Set<PushDevice>(); public DbSet<PushDevice> PushDevices => Set<PushDevice>();
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
try
{
return await base.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateException exception) when (
exception.InnerException is MySqlException { ErrorCode: MySqlErrorCode.DuplicateKeyEntry } &&
exception.Entries is [var entry] && entry.Entity is (IssueCategory or ProposalCategory))
{
throw new ConflictException("Kategorie se stejným názvem již existuje.");
}
}
public Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct) => public Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct) =>
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct); Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);