diff --git a/backend/src/Helpdesk.Api/Controllers/ProposalsController.cs b/backend/src/Helpdesk.Api/Controllers/ProposalsController.cs new file mode 100644 index 0000000..5b9bebf --- /dev/null +++ b/backend/src/Helpdesk.Api/Controllers/ProposalsController.cs @@ -0,0 +1,63 @@ +using Helpdesk.Api.Infrastructure; +using Helpdesk.Application.Common; +using Helpdesk.Application.Proposals; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Helpdesk.Api.Controllers; + +[ApiController] +[Authorize] +[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] +[Route("api/proposals")] +[ProducesResponseType(StatusCodes.Status400BadRequest)] +[ProducesResponseType(StatusCodes.Status401Unauthorized)] +[ProducesResponseType(StatusCodes.Status403Forbidden)] +[ProducesResponseType(StatusCodes.Status404NotFound)] +[ProducesResponseType(StatusCodes.Status409Conflict)] +public sealed class ProposalsController(ProposalService proposals) : ControllerBase +{ + [HttpGet] + public Task> List([FromQuery] ProposalQuery query, CancellationToken ct) => + proposals.ListAsync(query, ct); + + [HttpGet("{id:int}")] + public Task Get(int id, CancellationToken ct) => proposals.GetAsync(id, ct); + + [HttpPost] + [RequestSizeLimit(1024 * 1024)] + [ProducesResponseType(StatusCodes.Status201Created)] + public async Task> Create(SaveProposalRequest request, CancellationToken ct) + { + var proposal = await proposals.CreateAsync(request, ct); + return CreatedAtAction(nameof(Get), new { id = proposal.Id }, proposal); + } + + [HttpPut("{id:int}")] + [RequestSizeLimit(1024 * 1024)] + public Task Edit(int id, SaveProposalRequest request, CancellationToken ct) => + proposals.EditAsync(id, request, ct); + + [HttpPut("{id:int}/vote")] + [RequestSizeLimit(1024 * 1024)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task SetVote(int id, VoteRequest request, CancellationToken ct) + { + await proposals.SetVoteAsync(id, request.Value, ct); + return NoContent(); + } + + [HttpDelete("{id:int}/vote")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task RemoveVote(int id, CancellationToken ct) + { + await proposals.RemoveVoteAsync(id, ct); + return NoContent(); + } + + [HttpPost("{id:int}/status")] + [Authorize(Roles = Roles.Management)] + [RequestSizeLimit(1024 * 1024)] + public Task ChangeStatus(int id, ChangeProposalStatusRequest request, CancellationToken ct) => + proposals.ChangeStatusAsync(id, request, ct); +} diff --git a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs index 9da6dcb..81f767d 100644 --- a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs +++ b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs @@ -1,8 +1,11 @@ using Helpdesk.Domain.Auth; using Helpdesk.Domain.Catalogs; using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Notifications; +using Helpdesk.Domain.Proposals; using Helpdesk.Domain.Users; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; namespace Helpdesk.Application.Abstractions; @@ -16,11 +19,17 @@ public interface IAppDbContext DbSet Issues { get; } DbSet IssueEvents { get; } DbSet Attachments { get; } - DbSet IssueNotifications { get; } + DbSet Proposals { get; } + DbSet ProposalEvents { get; } + DbSet ProposalVotes { get; } + DbSet ProposalScores { get; } + DbSet Notifications { get; } DbSet NotificationDeliveries { get; } DbSet PushDevices { get; } Task SaveChangesAsync(CancellationToken cancellationToken = default); + Task BeginProposalWriteAsync(CancellationToken ct); + Task LockProposalAsync(int id, CancellationToken ct); } public interface IPasswordHasher diff --git a/backend/src/Helpdesk.Application/DependencyInjection.cs b/backend/src/Helpdesk.Application/DependencyInjection.cs index e16c834..462c29b 100644 --- a/backend/src/Helpdesk.Application/DependencyInjection.cs +++ b/backend/src/Helpdesk.Application/DependencyInjection.cs @@ -3,6 +3,7 @@ using Helpdesk.Application.Auth; using Helpdesk.Application.Catalogs; using Helpdesk.Application.Issues; using Helpdesk.Application.Notifications; +using Helpdesk.Application.Proposals; using Helpdesk.Application.Users; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -22,6 +23,8 @@ public static class DependencyInjection services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); return services; } } diff --git a/backend/src/Helpdesk.Application/Issues/IssueService.cs b/backend/src/Helpdesk.Application/Issues/IssueService.cs index 2983c19..8752382 100644 --- a/backend/src/Helpdesk.Application/Issues/IssueService.cs +++ b/backend/src/Helpdesk.Application/Issues/IssueService.cs @@ -1,14 +1,17 @@ using System.Text; using Helpdesk.Application.Abstractions; using Helpdesk.Application.Common; +using Helpdesk.Application.Notifications; using Helpdesk.Domain; using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Notifications; using Helpdesk.Domain.Users; using Microsoft.EntityFrameworkCore; namespace Helpdesk.Application.Issues; -public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentUser, IAttachmentStore files, TimeProvider clock) +public sealed partial class IssueService( + IAppDbContext db, ICurrentUser currentUser, IAttachmentStore files, TimeProvider clock, NotificationWriter notificationWriter) { public async Task CreateAsync(CreateIssueRequest request, IReadOnlyList uploads, CancellationToken ct) { @@ -19,7 +22,7 @@ public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentU AddEvent(issue, IssueEventType.Created, null, actor, null); var managementIds = await db.Users.Where(u => u.IsActive && u.Role == UserRole.Management) .Select(u => u.Id).ToArrayAsync(ct); - await NotifyAsync(issue, actor.Id, managementIds, NotificationType.IssueCreated, "Nové hlášení závady", ct); + await notificationWriter.ForIssueAsync(issue, actor.Id, managementIds, NotificationType.IssueCreated, "Nové hlášení závady", ct); var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct); return ToDetail(issue, actor, attachments.Select(AttachmentDto.From).ToArray()); } @@ -49,9 +52,9 @@ public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentU var from = issue.Status; issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority); AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName); - await NotifyAsync(issue, actor.Id, [assignee.Id], NotificationType.IssueAssigned, "Závada byla přiřazena", ct); + await notificationWriter.ForIssueAsync(issue, actor.Id, [assignee.Id], NotificationType.IssueAssigned, "Závada byla přiřazena", ct); if (from == IssueStatus.Received && issue.ReporterId != assignee.Id) - await NotifyAsync(issue, actor.Id, [issue.ReporterId], NotificationType.IssueStatusChanged, "Závada byla přiřazena", ct); + await notificationWriter.ForIssueAsync(issue, actor.Id, [issue.ReporterId], NotificationType.IssueStatusChanged, "Závada byla přiřazena", ct); await SaveAsync(ct); return await LoadDetailAsync(issue, actor, ct); @@ -74,7 +77,7 @@ public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentU var (type, title) = action == IssueAction.Reopen ? (NotificationType.IssueReopened, "Závada byla znovu otevřena") : (NotificationType.IssueStatusChanged, "Stav závady se změnil"); - await NotifyAsync(issue, actor.Id, [recipientId], type, title, ct); + await notificationWriter.ForIssueAsync(issue, actor.Id, [recipientId], type, title, ct); } await SaveAsync(ct); @@ -88,7 +91,7 @@ public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentU issue.RecordParticipation(IssueAction.Comment, actor.Id, actor.Role); var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text); int[] recipients = issue.AssigneeId is int assignee ? [issue.ReporterId, assignee] : [issue.ReporterId]; - await NotifyAsync(issue, actor.Id, recipients, NotificationType.IssueCommentAdded, "Nový komentář k závadě", ct); + await notificationWriter.ForIssueAsync(issue, actor.Id, recipients, NotificationType.IssueCommentAdded, "Nový komentář k závadě", ct); await SaveAsync(ct); return ToEvent(entry, actor.FullName); } @@ -190,33 +193,6 @@ public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentU return entry; } - private async Task NotifyAsync(Issue issue, int actorId, int[] recipientIds, NotificationType type, string title, CancellationToken ct) - { - var ids = recipientIds.Where(id => id != actorId).Distinct().ToArray(); - if (ids.Length == 0) - return; - - var reporterId = issue.ReporterId; - var recipients = await db.Users.Where(u => u.IsActive && ids.Contains(u.Id) && - (u.Id == reporterId || u.Role == UserRole.FacilityManager || u.Role == UserRole.Management)) - .Select(u => new - { - u.Id, - Email = u.EmailNotificationsEnabled && u.EmailConfirmed, - Push = db.PushDevices.Any(device => device.UserId == u.Id), - }).ToListAsync(ct); - - var now = clock.GetUtcNow().UtcDateTime; - foreach (var recipient in recipients) - { - var notification = new IssueNotification(issue, recipient.Id, type, title, issue.Title); - db.IssueNotifications.Add(notification); - db.NotificationDeliveries.AddRange( - new NotificationDelivery(notification, DeliveryChannel.Email, recipient.Email, now), - new NotificationDelivery(notification, DeliveryChannel.Push, recipient.Push, now)); - } - } - private async Task SaveAsync(CancellationToken ct) { try diff --git a/backend/src/Helpdesk.Application/Notifications/NotificationService.cs b/backend/src/Helpdesk.Application/Notifications/NotificationService.cs index 50ac01f..7299ed3 100644 --- a/backend/src/Helpdesk.Application/Notifications/NotificationService.cs +++ b/backend/src/Helpdesk.Application/Notifications/NotificationService.cs @@ -1,7 +1,7 @@ using Helpdesk.Application.Abstractions; using Helpdesk.Application.Common; using Helpdesk.Domain; -using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Notifications; using Microsoft.EntityFrameworkCore; namespace Helpdesk.Application.Notifications; @@ -46,13 +46,13 @@ public sealed class NotificationService(IAppDbContext db, ICurrentUser currentUs public async Task MarkAllReadAsync(CancellationToken ct) => await MarkUnreadRowsAsync(Inbox(), ct); - private IQueryable Inbox() + private IQueryable Inbox() { var userId = currentUser.Id; - return db.IssueNotifications.Where(n => n.UserId == userId); + return db.Notifications.Where(n => n.UserId == userId); } - private Task MarkUnreadRowsAsync(IQueryable query, CancellationToken ct) + private Task MarkUnreadRowsAsync(IQueryable query, CancellationToken ct) { var now = clock.GetUtcNow().UtcDateTime; return query.Where(n => n.ReadAt == null) diff --git a/backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs b/backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs new file mode 100644 index 0000000..1f14be6 --- /dev/null +++ b/backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs @@ -0,0 +1,52 @@ +using Helpdesk.Application.Abstractions; +using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Notifications; +using Helpdesk.Domain.Proposals; +using Helpdesk.Domain.Users; +using Microsoft.EntityFrameworkCore; + +namespace Helpdesk.Application.Notifications; + +/// Připraví notifikace a záznamy outboxu pro uložení spolu s událostí. +public sealed class NotificationWriter(IAppDbContext db, TimeProvider clock) +{ + public Task ForIssueAsync(Issue issue, int actorId, int[] recipientIds, NotificationType type, string title, + CancellationToken ct) + { + var reporterId = issue.ReporterId; + var eligibleUsers = db.Users.Where(u => + u.Id == reporterId || u.Role == UserRole.FacilityManager || u.Role == UserRole.Management); + return QueueAsync(eligibleUsers, actorId, recipientIds, + id => new Notification(issue, id, type, title, issue.Title), ct); + } + + public Task ForProposalStatusAsync(Proposal proposal, int actorId, CancellationToken ct) => + QueueAsync(db.Users, actorId, [proposal.AuthorId], + id => new Notification(proposal, id, "Stav návrhu se změnil"), ct); + + private async Task QueueAsync(IQueryable eligibleUsers, int actorId, int[] recipientIds, + Func create, CancellationToken ct) + { + var ids = recipientIds.Where(id => id != actorId).Distinct().ToArray(); + if (ids.Length == 0) + return; + + var recipients = await eligibleUsers.Where(u => u.IsActive && ids.Contains(u.Id)) + .Select(u => new + { + u.Id, + Email = u.EmailNotificationsEnabled && u.EmailConfirmed, + Push = db.PushDevices.Any(device => device.UserId == u.Id), + }).ToListAsync(ct); + + var now = clock.GetUtcNow().UtcDateTime; + foreach (var recipient in recipients) + { + var notification = create(recipient.Id); + db.Notifications.Add(notification); + db.NotificationDeliveries.AddRange( + new NotificationDelivery(notification, DeliveryChannel.Email, recipient.Email, now), + new NotificationDelivery(notification, DeliveryChannel.Push, recipient.Push, now)); + } + } +} diff --git a/backend/src/Helpdesk.Application/Proposals/ProposalDtos.cs b/backend/src/Helpdesk.Application/Proposals/ProposalDtos.cs new file mode 100644 index 0000000..19a3114 --- /dev/null +++ b/backend/src/Helpdesk.Application/Proposals/ProposalDtos.cs @@ -0,0 +1,29 @@ +namespace Helpdesk.Application.Proposals; + +public sealed record SaveProposalRequest(string Title, string Description, int CategoryId); +public sealed record ChangeProposalStatusRequest(string Status, string? Note); +public sealed record VoteRequest(int Value); + +public sealed class ProposalQuery +{ + public string? Status { get; init; } + public int? CategoryId { get; init; } + public int? AuthorId { get; init; } + public string? Q { get; init; } + public string? Sort { get; init; } + public int Page { get; init; } = 1; + public int PageSize { get; init; } = 20; +} + +public record ProposalSummary( + int Id, string Title, int CategoryId, int AuthorId, string Status, DateTime CreatedAt, + long VotesFor, long VotesAgainst, long Score, int? MyVote); + +public sealed record ProposalDetail( + int Id, string Title, int CategoryId, int AuthorId, string Status, DateTime CreatedAt, + long VotesFor, long VotesAgainst, long Score, int? MyVote, string Description, IReadOnlyList Events) + : ProposalSummary(Id, Title, CategoryId, AuthorId, Status, CreatedAt, VotesFor, VotesAgainst, Score, MyVote); + +public sealed record ProposalEventDto( + int Id, string EventType, string? FromStatus, string ToStatus, int ActorId, string ActorName, string? Note, + DateTime OccurredAt); diff --git a/backend/src/Helpdesk.Application/Proposals/ProposalService.Reads.cs b/backend/src/Helpdesk.Application/Proposals/ProposalService.Reads.cs new file mode 100644 index 0000000..577243d --- /dev/null +++ b/backend/src/Helpdesk.Application/Proposals/ProposalService.Reads.cs @@ -0,0 +1,104 @@ +using Helpdesk.Application.Common; +using Helpdesk.Domain; +using Helpdesk.Domain.Proposals; +using Microsoft.EntityFrameworkCore; + +namespace Helpdesk.Application.Proposals; + +public sealed partial class ProposalService +{ + public async Task> ListAsync(ProposalQuery filters, CancellationToken ct) + { + await GetActorRoleAsync(ct); + var proposals = db.Proposals.AsNoTracking(); + if (filters.Status is { } code) + { + var status = ParseStatus(code); + proposals = proposals.Where(p => p.Status == status); + } + if (filters.CategoryId is int categoryId) + proposals = proposals.Where(p => p.CategoryId == categoryId); + if (filters.AuthorId is int authorId) + proposals = proposals.Where(p => p.AuthorId == authorId); + if (!string.IsNullOrWhiteSpace(filters.Q)) + { + var term = filters.Q.Trim(); + proposals = proposals.Where(p => p.Title.Contains(term) || p.Description.Contains(term)); + } + + var rows = WithScores(proposals); + var ordered = filters.Sort switch + { + null or "newest" => rows.OrderByDescending(r => r.Proposal.CreatedAt).ThenByDescending(r => r.Proposal.Id), + "score" => rows.OrderByDescending(r => r.Score).ThenByDescending(r => r.Proposal.CreatedAt) + .ThenByDescending(r => r.Proposal.Id), + _ => throw new BadRequestException("Řazení musí být newest nebo score."), + }; + + var page = Math.Max(1, filters.Page); + var pageSize = Math.Clamp(filters.PageSize, 1, 100); + var total = await proposals.CountAsync(ct); + var offset = (long)(page - 1) * pageSize; + if (offset >= total) + return new PagedResult([], total, page, pageSize); + + var pageRows = await ordered.Skip((int)offset).Take(pageSize).ToListAsync(ct); + return new PagedResult(pageRows.Select(ToSummary).ToArray(), total, page, pageSize); + } + + public async Task GetAsync(int id, CancellationToken ct) + { + await GetActorRoleAsync(ct); + return await LoadDetailAsync(id, ct); + } + + private async Task LoadDetailAsync(int id, CancellationToken ct) + { + var row = await WithScores(db.Proposals.AsNoTracking().Where(p => p.Id == id)).SingleOrDefaultAsync(ct) + ?? throw new NotFoundException("Návrh neexistuje."); + var entries = await ( + from entry in db.ProposalEvents.AsNoTracking() + join actor in db.Users on entry.ActorId equals actor.Id + where entry.ProposalId == id + orderby entry.OccurredAt, entry.Id + select new { Entry = entry, actor.FirstName, actor.LastName }).ToListAsync(ct); + var events = entries.Select(e => new ProposalEventDto( + e.Entry.Id, e.Entry.EventType.ToCode(), e.Entry.FromStatus?.ToCode(), e.Entry.ToStatus.ToCode(), + e.Entry.ActorId, $"{e.FirstName} {e.LastName}", e.Entry.Note, e.Entry.OccurredAt)).ToArray(); + var summary = ToSummary(row); + return new ProposalDetail(summary.Id, summary.Title, summary.CategoryId, summary.AuthorId, summary.Status, + summary.CreatedAt, summary.VotesFor, summary.VotesAgainst, summary.Score, summary.MyVote, row.Proposal.Description, events); + } + + private IQueryable WithScores(IQueryable proposals) + { + var actorId = currentUser.Id; + return from proposal in proposals + join score in db.ProposalScores on proposal.Id equals score.ProposalId + select new ScoredProposal + { + Proposal = proposal, + VotesFor = score.VotesFor, + VotesAgainst = score.VotesAgainst, + Score = score.Score, + MyVote = db.ProposalVotes.Where(v => v.ProposalId == proposal.Id && v.UserId == actorId) + .Select(v => (sbyte?)v.Value).FirstOrDefault(), + }; + } + + private static ProposalSummary ToSummary(ScoredProposal row) + { + var proposal = row.Proposal; + return new ProposalSummary(proposal.Id, proposal.Title, proposal.CategoryId, proposal.AuthorId, + proposal.Status.ToCode(), proposal.CreatedAt, (long)row.VotesFor, (long)row.VotesAgainst, (long)row.Score, row.MyVote); + } + + private sealed class ScoredProposal + { + public required Proposal Proposal { get; init; } + public decimal VotesFor { get; init; } + public decimal VotesAgainst { get; init; } + public decimal Score { get; init; } + public sbyte? MyVote { get; init; } + } +} diff --git a/backend/src/Helpdesk.Application/Proposals/ProposalService.cs b/backend/src/Helpdesk.Application/Proposals/ProposalService.cs new file mode 100644 index 0000000..233ee95 --- /dev/null +++ b/backend/src/Helpdesk.Application/Proposals/ProposalService.cs @@ -0,0 +1,156 @@ +using System.Text; +using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Common; +using Helpdesk.Application.Notifications; +using Helpdesk.Domain; +using Helpdesk.Domain.Proposals; +using Helpdesk.Domain.Users; +using Microsoft.EntityFrameworkCore; + +namespace Helpdesk.Application.Proposals; + +public sealed partial class ProposalService( + IAppDbContext db, ICurrentUser currentUser, NotificationWriter notifications, TimeProvider clock) +{ + private const int MaxTextBytes = 65_535; + + public async Task CreateAsync(SaveProposalRequest request, CancellationToken ct) + { + await GetActorRoleAsync(ct); + var (title, description) = ValidateDetails(request); + await RequireActiveCategoryAsync(request.CategoryId, ct); + var proposal = new Proposal(currentUser.Id, title, description, request.CategoryId); + db.Proposals.Add(proposal); + AddEvent(proposal, ProposalEventType.Created); + await db.SaveChangesAsync(ct); + return await LoadDetailAsync(proposal.Id, ct); + } + + public async Task EditAsync(int id, SaveProposalRequest request, CancellationToken ct) + { + await GetActorRoleAsync(ct); + var (title, description) = ValidateDetails(request); + await using (var transaction = await db.BeginProposalWriteAsync(ct)) + { + var proposal = await LockProposalAsync(id, ct); + if (!proposal.IsAuthor(currentUser.Id)) + throw new ForbiddenException("Návrh může upravit jen jeho autor."); + if (!proposal.IsEditable) + throw new ConflictException("Návrh lze upravit jen ve stavu Podán."); + + if (proposal.CategoryId != request.CategoryId) + await RequireActiveCategoryAsync(request.CategoryId, ct); + + proposal.Edit(currentUser.Id, title, description, request.CategoryId); + AddEvent(proposal, ProposalEventType.Updated); + await db.SaveChangesAsync(ct); + await transaction.CommitAsync(ct); + } + + return await LoadDetailAsync(id, ct); + } + + public async Task ChangeStatusAsync(int id, ChangeProposalStatusRequest request, CancellationToken ct) + { + var role = await GetActorRoleAsync(ct); + if (role != UserRole.Management) + throw new ForbiddenException("Stav návrhu může změnit jen vedení školy."); + + var target = ParseStatus(request.Status); + var note = string.IsNullOrWhiteSpace(request.Note) ? null : request.Note.Trim(); + if (target == ProposalStatus.Rejected && note is null) + throw new BadRequestException("Zamítnutí vyžaduje vyjádření."); + if (note is not null && Encoding.UTF8.GetByteCount(note) > MaxTextBytes) + throw new BadRequestException("Vyjádření je příliš dlouhé."); + + await using (var transaction = await db.BeginProposalWriteAsync(ct)) + { + var proposal = await LockProposalAsync(id, ct); + var previous = proposal.Status; + if (!proposal.CanTransitionTo(target)) + throw new ConflictException("Přechod do požadovaného stavu není povolen."); + + proposal.ChangeStatus(target, role, note); + AddEvent(proposal, ProposalEventType.StatusChanged, previous, note); + await notifications.ForProposalStatusAsync(proposal, currentUser.Id, ct); + await db.SaveChangesAsync(ct); + await transaction.CommitAsync(ct); + } + + return await LoadDetailAsync(id, ct); + } + + public Task SetVoteAsync(int id, int value, CancellationToken ct) + { + if (value is not (1 or -1)) + throw new BadRequestException("Hlas musí mít hodnotu 1 nebo -1."); + + return ChangeVoteAsync(id, (sbyte)value, ct); + } + + public Task RemoveVoteAsync(int id, CancellationToken ct) => ChangeVoteAsync(id, null, ct); + + private async Task ChangeVoteAsync(int id, sbyte? value, CancellationToken ct) + { + await GetActorRoleAsync(ct); + var actorId = currentUser.Id; + await using var transaction = await db.BeginProposalWriteAsync(ct); + var proposal = await LockProposalAsync(id, ct); + if (proposal.IsAuthor(actorId)) + throw new ForbiddenException("Autor nemůže hlasovat o vlastním návrhu."); + if (!proposal.IsVotingOpen) + throw new ConflictException("Hlasování je uzavřeno."); + + var vote = await db.ProposalVotes.SingleOrDefaultAsync(v => v.ProposalId == id && v.UserId == actorId, ct); + if (value is sbyte newValue) + { + var now = clock.GetUtcNow().UtcDateTime; + if (vote is null) + db.ProposalVotes.Add(new ProposalVote(proposal, actorId, newValue, now)); + else + vote.SetValue(proposal, newValue, now); + } + else if (vote is not null) + { + db.ProposalVotes.Remove(vote); + } + + await db.SaveChangesAsync(ct); + await transaction.CommitAsync(ct); + } + + private async Task GetActorRoleAsync(CancellationToken ct) + { + var id = currentUser.Id; + return await db.Users.Where(u => u.Id == id && u.IsActive).Select(u => (UserRole?)u.Role).SingleOrDefaultAsync(ct) + ?? throw new UnauthorizedException("Účet není aktivní."); + } + + private async Task LockProposalAsync(int id, CancellationToken ct) => + await db.LockProposalAsync(id, ct) ?? throw new NotFoundException("Návrh neexistuje."); + + private async Task RequireActiveCategoryAsync(int id, CancellationToken ct) + { + if (!await db.ProposalCategories.AnyAsync(c => c.Id == id && c.IsActive, ct)) + throw new BadRequestException("Vyberte aktivní oblast návrhu."); + } + + private static (string Title, string Description) ValidateDetails(SaveProposalRequest request) + { + var title = request.Title?.Trim(); + var description = request.Description?.Trim(); + if (string.IsNullOrEmpty(title) || title.Length > 200) + throw new BadRequestException("Název návrhu musí mít 1 až 200 znaků."); + if (string.IsNullOrEmpty(description) || Encoding.UTF8.GetByteCount(description) > MaxTextBytes) + throw new BadRequestException("Vyplňte popis návrhu v povolené délce."); + return (title, description); + } + + private void AddEvent(Proposal proposal, ProposalEventType type, ProposalStatus? previous = null, string? note = null) => + db.ProposalEvents.Add(new ProposalEvent(proposal, type, previous, currentUser.Id, note, clock.GetUtcNow().UtcDateTime)); + + private static ProposalStatus ParseStatus(string status) => + EnumCode.TryParse(status, out var value) + ? value + : throw new BadRequestException("Neplatný stav návrhu."); +} diff --git a/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs b/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs deleted file mode 100644 index 144c935..0000000 --- a/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs +++ /dev/null @@ -1,41 +0,0 @@ -namespace Helpdesk.Domain.Issues; - -public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged } -public enum DeliveryChannel { Email, Push } -public enum DeliveryStatus { Pending, Skipped } - -public sealed class IssueNotification( - Issue issue, int userId, NotificationType type, string title, string message) : IHasCreatedAt -{ - private IssueNotification() : this(null!, 0, default, null!, null!) { } - - public int Id { get; private set; } - public int? IssueId { get; private set; } - public int? ProposalId { get; private set; } - public Issue Issue { get; private set; } = issue; - public int UserId { get; private set; } = userId; - public NotificationType Type { get; private set; } = type; - public string Title { get; private set; } = title; - public string Message { get; private set; } = message; - public DateTime CreatedAt { get; set; } - public DateTime? ReadAt { get; private set; } -} - -public sealed class NotificationDelivery( - IssueNotification notification, DeliveryChannel channel, bool enabled, DateTime now) -{ - private NotificationDelivery() : this(null!, default, false, default) { } - - public int Id { get; private set; } - public int NotificationId { get; private set; } - public IssueNotification Notification { get; private set; } = notification; - public DeliveryChannel Channel { get; private set; } = channel; - public DeliveryStatus Status { get; private set; } = enabled ? DeliveryStatus.Pending : DeliveryStatus.Skipped; - public DateTime? NextAttemptAt { get; private set; } = enabled ? now : null; -} - -public sealed class PushDevice -{ - public int Id { get; private set; } - public int UserId { get; private set; } -} diff --git a/backend/src/Helpdesk.Domain/Notifications/Notification.cs b/backend/src/Helpdesk.Domain/Notifications/Notification.cs new file mode 100644 index 0000000..53b1b46 --- /dev/null +++ b/backend/src/Helpdesk.Domain/Notifications/Notification.cs @@ -0,0 +1,63 @@ +using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Proposals; + +namespace Helpdesk.Domain.Notifications; + +public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged } +public enum DeliveryChannel { Email, Push } +public enum DeliveryStatus { Pending, Skipped } + +public sealed class Notification : IHasCreatedAt +{ + private Notification() { } + + public Notification(Issue issue, int userId, NotificationType type, string title, string message) + : this(userId, type, title, message) + { + Issue = issue; + } + + public Notification(Proposal proposal, int userId, string title) + : this(userId, NotificationType.ProposalStatusChanged, title, proposal.Title) + { + ProposalId = proposal.Id; + } + + private Notification(int userId, NotificationType type, string title, string message) + { + UserId = userId; + Type = type; + Title = title; + Message = message; + } + + public int Id { get; private set; } + public int? IssueId { get; private set; } + public int? ProposalId { get; private set; } + public Issue? Issue { get; private set; } + public int UserId { get; private set; } + public NotificationType Type { get; private set; } + public string Title { get; private set; } = null!; + public string Message { get; private set; } = null!; + public DateTime CreatedAt { get; set; } + public DateTime? ReadAt { get; private set; } +} + +public sealed class NotificationDelivery( + Notification notification, DeliveryChannel channel, bool enabled, DateTime now) +{ + private NotificationDelivery() : this(null!, default, false, default) { } + + public int Id { get; private set; } + public int NotificationId { get; private set; } + public Notification Notification { get; private set; } = notification; + public DeliveryChannel Channel { get; private set; } = channel; + public DeliveryStatus Status { get; private set; } = enabled ? DeliveryStatus.Pending : DeliveryStatus.Skipped; + public DateTime? NextAttemptAt { get; private set; } = enabled ? now : null; +} + +public sealed class PushDevice +{ + public int Id { get; private set; } + public int UserId { get; private set; } +} diff --git a/backend/src/Helpdesk.Domain/Proposals/Proposal.cs b/backend/src/Helpdesk.Domain/Proposals/Proposal.cs new file mode 100644 index 0000000..1c17a07 --- /dev/null +++ b/backend/src/Helpdesk.Domain/Proposals/Proposal.cs @@ -0,0 +1,64 @@ +using Helpdesk.Domain.Users; + +namespace Helpdesk.Domain.Proposals; + +public enum ProposalStatus { Submitted, UnderReview, Accepted, Rejected, Implemented } +public enum ProposalEventType { Created, Updated, StatusChanged } + +public sealed class Proposal : IHasCreatedAt +{ + private Proposal() { } + + public Proposal(int authorId, string title, string description, int categoryId) + { + AuthorId = authorId; + SetDetails(title, description, categoryId); + } + + public int Id { get; private set; } + public int AuthorId { get; private set; } + public string Title { get; private set; } = null!; + public string Description { get; private set; } = null!; + public int CategoryId { get; private set; } + public ProposalStatus Status { get; private set; } = ProposalStatus.Submitted; + public DateTime CreatedAt { get; set; } + + public bool IsAuthor(int userId) => AuthorId == userId; + public bool IsEditable => Status == ProposalStatus.Submitted; + public bool IsVotingOpen => Status is ProposalStatus.Submitted or ProposalStatus.UnderReview; + public bool CanEdit(int userId) => IsAuthor(userId) && IsEditable; + public bool CanVote(int userId) => !IsAuthor(userId) && IsVotingOpen; + + public bool CanTransitionTo(ProposalStatus target) => Status switch + { + ProposalStatus.Submitted => target is ProposalStatus.UnderReview or ProposalStatus.Accepted or ProposalStatus.Rejected, + ProposalStatus.UnderReview => target is ProposalStatus.Accepted or ProposalStatus.Rejected, + ProposalStatus.Accepted => target == ProposalStatus.Implemented, + _ => false, + }; + + public void Edit(int actorId, string title, string description, int categoryId) + { + if (!CanEdit(actorId)) + throw new InvalidOperationException("Návrh nelze upravit."); + + SetDetails(title, description, categoryId); + } + + public void ChangeStatus(ProposalStatus target, UserRole role, string? note) + { + if (role != UserRole.Management || !CanTransitionTo(target)) + throw new InvalidOperationException("Stav návrhu nelze změnit."); + if (target == ProposalStatus.Rejected && string.IsNullOrWhiteSpace(note)) + throw new ArgumentException("Zamítnutí vyžaduje vyjádření.", nameof(note)); + + Status = target; + } + + private void SetDetails(string title, string description, int categoryId) + { + Title = title; + Description = description; + CategoryId = categoryId; + } +} diff --git a/backend/src/Helpdesk.Domain/Proposals/ProposalRecords.cs b/backend/src/Helpdesk.Domain/Proposals/ProposalRecords.cs new file mode 100644 index 0000000..aa6932e --- /dev/null +++ b/backend/src/Helpdesk.Domain/Proposals/ProposalRecords.cs @@ -0,0 +1,66 @@ +namespace Helpdesk.Domain.Proposals; + +public sealed class ProposalEvent +{ + private ProposalEvent() { } + + public ProposalEvent(Proposal proposal, ProposalEventType eventType, ProposalStatus? fromStatus, int actorId, + string? note, DateTime occurredAt) + { + Proposal = proposal; + EventType = eventType; + FromStatus = fromStatus; + ToStatus = proposal.Status; + ActorId = actorId; + Note = note; + OccurredAt = occurredAt; + } + + public int Id { get; private set; } + public int ProposalId { get; private set; } + public Proposal Proposal { get; private set; } = null!; + public ProposalEventType EventType { get; private set; } + public ProposalStatus? FromStatus { get; private set; } + public ProposalStatus ToStatus { get; private set; } + public int ActorId { get; private set; } + public string? Note { get; private set; } + public DateTime OccurredAt { get; private set; } +} + +public sealed class ProposalVote +{ + private ProposalVote() { } + + public ProposalVote(Proposal proposal, int userId, sbyte value, DateTime now) + { + ProposalId = proposal.Id; + UserId = userId; + SetValue(proposal, value, now); + } + + public int ProposalId { get; private set; } + public int UserId { get; private set; } + public sbyte Value { get; private set; } + public DateTime VotedAt { get; private set; } + + public void SetValue(Proposal proposal, sbyte value, DateTime now) + { + if (proposal.Id != ProposalId || !proposal.CanVote(UserId)) + throw new InvalidOperationException("O návrhu nelze hlasovat."); + if (value is not (1 or -1)) + throw new ArgumentOutOfRangeException(nameof(value)); + if (Value == value) + return; + + Value = value; + VotedAt = now; + } +} + +public sealed class ProposalScore +{ + public int ProposalId { get; private set; } + public decimal VotesFor { get; private set; } + public decimal VotesAgainst { get; private set; } + public decimal Score { get; private set; } +} diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs index d964065..2645811 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs @@ -1,10 +1,14 @@ +using System.Data; using Helpdesk.Application.Abstractions; using Helpdesk.Domain.Auth; using Helpdesk.Domain.Catalogs; using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Notifications; +using Helpdesk.Domain.Proposals; using Helpdesk.Domain.Users; using Helpdesk.Infrastructure.Security; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Helpdesk.Infrastructure.Persistence; @@ -24,10 +28,24 @@ public sealed class HelpdeskDbContext(DbContextOptions option public DbSet Issues => Set(); public DbSet IssueEvents => Set(); public DbSet Attachments => Set(); - public DbSet IssueNotifications => Set(); + public DbSet Proposals => Set(); + public DbSet ProposalEvents => Set(); + public DbSet ProposalVotes => Set(); + public DbSet ProposalScores => Set(); + public DbSet Notifications => Set(); public DbSet NotificationDeliveries => Set(); public DbSet PushDevices => Set(); + public Task BeginProposalWriteAsync(CancellationToken ct) => + Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct); + + public async Task LockProposalAsync(int id, CancellationToken ct) + { + // Všechny zápisy nad návrhem zamykají stejný řádek před čtením stavu a hlasů. + var rows = await Proposals.FromSql($"SELECT * FROM proposal WHERE id = {id} FOR UPDATE").ToListAsync(ct); + return rows.SingleOrDefault(); + } + protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new UserConfiguration(encryptor)); @@ -38,7 +56,11 @@ public sealed class HelpdeskDbContext(DbContextOptions option modelBuilder.ApplyConfiguration(new IssueConfiguration()); modelBuilder.ApplyConfiguration(new IssueEventConfiguration()); modelBuilder.ApplyConfiguration(new AttachmentConfiguration()); - modelBuilder.ApplyConfiguration(new IssueNotificationConfiguration()); + modelBuilder.ApplyConfiguration(new ProposalConfiguration()); + modelBuilder.ApplyConfiguration(new ProposalEventConfiguration()); + modelBuilder.ApplyConfiguration(new ProposalVoteConfiguration()); + modelBuilder.Entity().HasNoKey().ToView("v_proposal_score"); + modelBuilder.ApplyConfiguration(new NotificationConfiguration()); modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration()); modelBuilder.Entity().ToTable("push_device"); } diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs b/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs index 6394776..6186dcd 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs @@ -1,5 +1,7 @@ using Helpdesk.Domain.Catalogs; using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Notifications; +using Helpdesk.Domain.Proposals; using Helpdesk.Domain.Users; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; @@ -50,15 +52,16 @@ internal sealed class AttachmentConfiguration : IEntityTypeConfiguration +internal sealed class NotificationConfiguration : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder b) + public void Configure(EntityTypeBuilder b) { b.ToTable("notification"); b.Property(x => x.Type).HasConversion>().HasMaxLength(40); b.Property(x => x.Title).HasMaxLength(200); b.Property(x => x.Message).HasMaxLength(1000); b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId).IsRequired(false); + b.HasOne().WithMany().HasForeignKey(x => x.ProposalId); b.HasOne().WithMany().HasForeignKey(x => x.UserId); } } diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/ProposalConfigurations.cs b/backend/src/Helpdesk.Infrastructure/Persistence/ProposalConfigurations.cs new file mode 100644 index 0000000..1394d9e --- /dev/null +++ b/backend/src/Helpdesk.Infrastructure/Persistence/ProposalConfigurations.cs @@ -0,0 +1,46 @@ +using Helpdesk.Domain.Catalogs; +using Helpdesk.Domain.Proposals; +using Helpdesk.Domain.Users; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Helpdesk.Infrastructure.Persistence; + +internal sealed class ProposalConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("proposal"); + b.Property(x => x.Title).HasMaxLength(200); + b.Property(x => x.Description).HasColumnType("text"); + b.Property(x => x.Status).HasConversion>().HasMaxLength(30); + b.HasOne().WithMany().HasForeignKey(x => x.CategoryId); + b.HasOne().WithMany().HasForeignKey(x => x.AuthorId); + } +} + +internal sealed class ProposalEventConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("proposal_event"); + b.Property(x => x.EventType).HasConversion>().HasMaxLength(20); + b.Property(x => x.FromStatus).HasConversion>().HasMaxLength(30); + b.Property(x => x.ToStatus).HasConversion>().HasMaxLength(30); + b.Property(x => x.Note).HasColumnType("text"); + b.HasOne(x => x.Proposal).WithMany().HasForeignKey(x => x.ProposalId); + b.HasOne().WithMany().HasForeignKey(x => x.ActorId); + } +} + +internal sealed class ProposalVoteConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("proposal_vote"); + b.HasKey(x => new { x.ProposalId, x.UserId }); + b.Property(x => x.Value).HasColumnType("tinyint"); + b.HasOne().WithMany().HasForeignKey(x => x.ProposalId); + b.HasOne().WithMany().HasForeignKey(x => x.UserId); + } +} diff --git a/backend/tests/Helpdesk.UnitTests/ProposalTests.cs b/backend/tests/Helpdesk.UnitTests/ProposalTests.cs new file mode 100644 index 0000000..7fa42f5 --- /dev/null +++ b/backend/tests/Helpdesk.UnitTests/ProposalTests.cs @@ -0,0 +1,98 @@ +using Helpdesk.Domain.Proposals; +using Helpdesk.Domain.Users; + +namespace Helpdesk.UnitTests; + +public sealed class ProposalTests +{ + private const int Author = 1; + private const int Voter = 2; + + [Theory] + [InlineData(ProposalStatus.Submitted, ProposalStatus.UnderReview, ProposalStatus.Accepted, ProposalStatus.Rejected)] + [InlineData(ProposalStatus.UnderReview, ProposalStatus.Accepted, ProposalStatus.Rejected)] + [InlineData(ProposalStatus.Accepted, ProposalStatus.Implemented)] + [InlineData(ProposalStatus.Rejected)] + [InlineData(ProposalStatus.Implemented)] + public void EnforcesTransitionTable(ProposalStatus from, params ProposalStatus[] permitted) + { + foreach (var target in Enum.GetValues()) + { + var proposal = At(from); + var allowed = permitted.Contains(target); + Assert.Equal(allowed, proposal.CanTransitionTo(target)); + if (allowed) + { + proposal.ChangeStatus(target, UserRole.Management, "Vyjádření"); + Assert.Equal(target, proposal.Status); + } + else + { + Assert.Throws(() => proposal.ChangeStatus(target, UserRole.Management, null)); + Assert.Equal(from, proposal.Status); + } + } + } + + [Fact] + public void ReviewRequiresManagementAndRejectionRequiresNote() + { + var proposal = At(ProposalStatus.Submitted); + Assert.Throws(() => proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Admin, null)); + Assert.Throws(() => proposal.ChangeStatus(ProposalStatus.Rejected, UserRole.Management, " ")); + Assert.Equal(ProposalStatus.Submitted, proposal.Status); + } + + [Theory] + [InlineData(ProposalStatus.Submitted, true, true)] + [InlineData(ProposalStatus.UnderReview, false, true)] + [InlineData(ProposalStatus.Accepted, false, false)] + [InlineData(ProposalStatus.Rejected, false, false)] + [InlineData(ProposalStatus.Implemented, false, false)] + public void AuthorEditsAndOtherUserVotesOnlyInEligibleStates(ProposalStatus state, bool mayEdit, bool mayVote) + { + var proposal = At(state); + Assert.Equal(mayEdit, proposal.CanEdit(Author)); + Assert.False(proposal.CanEdit(Voter)); + Assert.False(proposal.CanVote(Author)); + Assert.Equal(mayVote, proposal.CanVote(Voter)); + Assert.Throws(() => proposal.Edit(Voter, "Změna", "Popis", 1)); + if (mayEdit) + { + proposal.Edit(Author, "Změna", "Popis", 1); + Assert.Equal("Změna", proposal.Title); + } + else + { + Assert.Throws(() => proposal.Edit(Author, "Změna", "Popis", 1)); + } + } + + [Fact] + public void RepeatingVotePreservesTimestampAndClosingPreventsChanges() + { + var proposal = At(ProposalStatus.Submitted); + var now = DateTime.UnixEpoch; + Assert.Throws(() => new ProposalVote(proposal, Author, 1, now)); + Assert.Throws(() => new ProposalVote(proposal, Voter, 0, now)); + + var vote = new ProposalVote(proposal, Voter, 1, now); + vote.SetValue(proposal, 1, now.AddMinutes(1)); + Assert.Equal(now, vote.VotedAt); + vote.SetValue(proposal, -1, now.AddMinutes(2)); + Assert.Equal((sbyte)-1, vote.Value); + Assert.Equal(now.AddMinutes(2), vote.VotedAt); + proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Management, null); + Assert.Throws(() => vote.SetValue(proposal, 1, now.AddMinutes(3))); + } + + private static Proposal At(ProposalStatus status) + { + var proposal = new Proposal(Author, "Návrh", "Popis", 1); + if (status == ProposalStatus.Implemented) + proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Management, null); + if (status != ProposalStatus.Submitted) + proposal.ChangeStatus(status, UserRole.Management, "Vyjádření"); + return proposal; + } +}