Add proposal workflow and voting API
This commit is contained in:
1 parent
9ca23a2c15
commit
1ff4a0a814
17 files changed
+796
-83
No files matched your search
@@ -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<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||||
|
public sealed class ProposalsController(ProposalService proposals) : ControllerBase
|
||||||
|
{
|
||||||
|
[HttpGet]
|
||||||
|
public Task<PagedResult<ProposalSummary>> List([FromQuery] ProposalQuery query, CancellationToken ct) =>
|
||||||
|
proposals.ListAsync(query, ct);
|
||||||
|
|
||||||
|
[HttpGet("{id:int}")]
|
||||||
|
public Task<ProposalDetail> Get(int id, CancellationToken ct) => proposals.GetAsync(id, ct);
|
||||||
|
|
||||||
|
[HttpPost]
|
||||||
|
[RequestSizeLimit(1024 * 1024)]
|
||||||
|
[ProducesResponseType<ProposalDetail>(StatusCodes.Status201Created)]
|
||||||
|
public async Task<ActionResult<ProposalDetail>> 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<ProposalDetail> 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<IActionResult> 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<IActionResult> 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<ProposalDetail> ChangeStatus(int id, ChangeProposalStatusRequest request, CancellationToken ct) =>
|
||||||
|
proposals.ChangeStatusAsync(id, request, ct);
|
||||||
|
}
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
using Helpdesk.Domain.Auth;
|
using Helpdesk.Domain.Auth;
|
||||||
using Helpdesk.Domain.Catalogs;
|
using Helpdesk.Domain.Catalogs;
|
||||||
using Helpdesk.Domain.Issues;
|
using Helpdesk.Domain.Issues;
|
||||||
|
using Helpdesk.Domain.Notifications;
|
||||||
|
using Helpdesk.Domain.Proposals;
|
||||||
using Helpdesk.Domain.Users;
|
using Helpdesk.Domain.Users;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage;
|
||||||
|
|
||||||
namespace Helpdesk.Application.Abstractions;
|
namespace Helpdesk.Application.Abstractions;
|
||||||
|
|
||||||
@@ -16,11 +19,17 @@ public interface IAppDbContext
|
|||||||
DbSet<Issue> Issues { get; }
|
DbSet<Issue> Issues { get; }
|
||||||
DbSet<IssueEvent> IssueEvents { get; }
|
DbSet<IssueEvent> IssueEvents { get; }
|
||||||
DbSet<Attachment> Attachments { get; }
|
DbSet<Attachment> Attachments { get; }
|
||||||
DbSet<IssueNotification> IssueNotifications { get; }
|
DbSet<Proposal> Proposals { get; }
|
||||||
|
DbSet<ProposalEvent> ProposalEvents { get; }
|
||||||
|
DbSet<ProposalVote> ProposalVotes { get; }
|
||||||
|
DbSet<ProposalScore> ProposalScores { get; }
|
||||||
|
DbSet<Notification> Notifications { get; }
|
||||||
DbSet<NotificationDelivery> NotificationDeliveries { get; }
|
DbSet<NotificationDelivery> NotificationDeliveries { get; }
|
||||||
DbSet<PushDevice> PushDevices { get; }
|
DbSet<PushDevice> PushDevices { get; }
|
||||||
|
|
||||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct);
|
||||||
|
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public interface IPasswordHasher
|
public interface IPasswordHasher
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ using Helpdesk.Application.Auth;
|
|||||||
using Helpdesk.Application.Catalogs;
|
using Helpdesk.Application.Catalogs;
|
||||||
using Helpdesk.Application.Issues;
|
using Helpdesk.Application.Issues;
|
||||||
using Helpdesk.Application.Notifications;
|
using Helpdesk.Application.Notifications;
|
||||||
|
using Helpdesk.Application.Proposals;
|
||||||
using Helpdesk.Application.Users;
|
using Helpdesk.Application.Users;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
@@ -22,6 +23,8 @@ public static class DependencyInjection
|
|||||||
services.AddScoped<CatalogService>();
|
services.AddScoped<CatalogService>();
|
||||||
services.AddScoped<IssueService>();
|
services.AddScoped<IssueService>();
|
||||||
services.AddScoped<NotificationService>();
|
services.AddScoped<NotificationService>();
|
||||||
|
services.AddScoped<NotificationWriter>();
|
||||||
|
services.AddScoped<ProposalService>();
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,17 @@
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Application.Common;
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Notifications;
|
||||||
using Helpdesk.Domain;
|
using Helpdesk.Domain;
|
||||||
using Helpdesk.Domain.Issues;
|
using Helpdesk.Domain.Issues;
|
||||||
|
using Helpdesk.Domain.Notifications;
|
||||||
using Helpdesk.Domain.Users;
|
using Helpdesk.Domain.Users;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace Helpdesk.Application.Issues;
|
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<IssueDetail> CreateAsync(CreateIssueRequest request, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
|
public async Task<IssueDetail> CreateAsync(CreateIssueRequest request, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
|
||||||
{
|
{
|
||||||
@@ -19,7 +22,7 @@ public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentU
|
|||||||
AddEvent(issue, IssueEventType.Created, null, actor, null);
|
AddEvent(issue, IssueEventType.Created, null, actor, null);
|
||||||
var managementIds = await db.Users.Where(u => u.IsActive && u.Role == UserRole.Management)
|
var managementIds = await db.Users.Where(u => u.IsActive && u.Role == UserRole.Management)
|
||||||
.Select(u => u.Id).ToArrayAsync(ct);
|
.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);
|
var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct);
|
||||||
return ToDetail(issue, actor, attachments.Select(AttachmentDto.From).ToArray());
|
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;
|
var from = issue.Status;
|
||||||
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
|
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
|
||||||
AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName);
|
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)
|
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);
|
await SaveAsync(ct);
|
||||||
return await LoadDetailAsync(issue, actor, 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
|
var (type, title) = action == IssueAction.Reopen
|
||||||
? (NotificationType.IssueReopened, "Závada byla znovu otevřena")
|
? (NotificationType.IssueReopened, "Závada byla znovu otevřena")
|
||||||
: (NotificationType.IssueStatusChanged, "Stav závady se změnil");
|
: (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);
|
await SaveAsync(ct);
|
||||||
@@ -88,7 +91,7 @@ public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentU
|
|||||||
issue.RecordParticipation(IssueAction.Comment, actor.Id, actor.Role);
|
issue.RecordParticipation(IssueAction.Comment, actor.Id, actor.Role);
|
||||||
var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text);
|
var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text);
|
||||||
int[] recipients = issue.AssigneeId is int assignee ? [issue.ReporterId, assignee] : [issue.ReporterId];
|
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);
|
await SaveAsync(ct);
|
||||||
return ToEvent(entry, actor.FullName);
|
return ToEvent(entry, actor.FullName);
|
||||||
}
|
}
|
||||||
@@ -190,33 +193,6 @@ public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentU
|
|||||||
return entry;
|
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)
|
private async Task SaveAsync(CancellationToken ct)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Application.Common;
|
using Helpdesk.Application.Common;
|
||||||
using Helpdesk.Domain;
|
using Helpdesk.Domain;
|
||||||
using Helpdesk.Domain.Issues;
|
using Helpdesk.Domain.Notifications;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace Helpdesk.Application.Notifications;
|
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);
|
public async Task MarkAllReadAsync(CancellationToken ct) => await MarkUnreadRowsAsync(Inbox(), ct);
|
||||||
|
|
||||||
private IQueryable<IssueNotification> Inbox()
|
private IQueryable<Notification> Inbox()
|
||||||
{
|
{
|
||||||
var userId = currentUser.Id;
|
var userId = currentUser.Id;
|
||||||
return db.IssueNotifications.Where(n => n.UserId == userId);
|
return db.Notifications.Where(n => n.UserId == userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Task<int> MarkUnreadRowsAsync(IQueryable<IssueNotification> query, CancellationToken ct)
|
private Task<int> MarkUnreadRowsAsync(IQueryable<Notification> query, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var now = clock.GetUtcNow().UtcDateTime;
|
var now = clock.GetUtcNow().UtcDateTime;
|
||||||
return query.Where(n => n.ReadAt == null)
|
return query.Where(n => n.ReadAt == null)
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>Připraví notifikace a záznamy outboxu pro uložení spolu s událostí.</summary>
|
||||||
|
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<User> eligibleUsers, int actorId, int[] recipientIds,
|
||||||
|
Func<int, Notification> 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<ProposalEventDto> 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);
|
||||||
@@ -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<PagedResult<ProposalSummary>> 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<ProposalSummary>([], total, page, pageSize);
|
||||||
|
|
||||||
|
var pageRows = await ordered.Skip((int)offset).Take(pageSize).ToListAsync(ct);
|
||||||
|
return new PagedResult<ProposalSummary>(pageRows.Select(ToSummary).ToArray(), total, page, pageSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ProposalDetail> GetAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await GetActorRoleAsync(ct);
|
||||||
|
return await LoadDetailAsync(id, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<ProposalDetail> 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<ScoredProposal> WithScores(IQueryable<Proposal> 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; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<ProposalDetail> 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<ProposalDetail> 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<ProposalDetail> 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<UserRole> 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<Proposal> 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<ProposalStatus>(status, out var value)
|
||||||
|
? value
|
||||||
|
: throw new BadRequestException("Neplatný stav návrhu.");
|
||||||
|
}
|
||||||
@@ -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; }
|
|
||||||
}
|
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
|
using System.Data;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Domain.Auth;
|
using Helpdesk.Domain.Auth;
|
||||||
using Helpdesk.Domain.Catalogs;
|
using Helpdesk.Domain.Catalogs;
|
||||||
using Helpdesk.Domain.Issues;
|
using Helpdesk.Domain.Issues;
|
||||||
|
using Helpdesk.Domain.Notifications;
|
||||||
|
using Helpdesk.Domain.Proposals;
|
||||||
using Helpdesk.Domain.Users;
|
using Helpdesk.Domain.Users;
|
||||||
using Helpdesk.Infrastructure.Security;
|
using Helpdesk.Infrastructure.Security;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage;
|
||||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Persistence;
|
namespace Helpdesk.Infrastructure.Persistence;
|
||||||
@@ -24,10 +28,24 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
public DbSet<Issue> Issues => Set<Issue>();
|
public DbSet<Issue> Issues => Set<Issue>();
|
||||||
public DbSet<IssueEvent> IssueEvents => Set<IssueEvent>();
|
public DbSet<IssueEvent> IssueEvents => Set<IssueEvent>();
|
||||||
public DbSet<Attachment> Attachments => Set<Attachment>();
|
public DbSet<Attachment> Attachments => Set<Attachment>();
|
||||||
public DbSet<IssueNotification> IssueNotifications => Set<IssueNotification>();
|
public DbSet<Proposal> Proposals => Set<Proposal>();
|
||||||
|
public DbSet<ProposalEvent> ProposalEvents => Set<ProposalEvent>();
|
||||||
|
public DbSet<ProposalVote> ProposalVotes => Set<ProposalVote>();
|
||||||
|
public DbSet<ProposalScore> ProposalScores => Set<ProposalScore>();
|
||||||
|
public DbSet<Notification> Notifications => Set<Notification>();
|
||||||
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 Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct) =>
|
||||||
|
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
||||||
|
|
||||||
|
public async Task<Proposal?> 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)
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
{
|
{
|
||||||
modelBuilder.ApplyConfiguration(new UserConfiguration(encryptor));
|
modelBuilder.ApplyConfiguration(new UserConfiguration(encryptor));
|
||||||
@@ -38,7 +56,11 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
modelBuilder.ApplyConfiguration(new IssueConfiguration());
|
modelBuilder.ApplyConfiguration(new IssueConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new IssueEventConfiguration());
|
modelBuilder.ApplyConfiguration(new IssueEventConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new AttachmentConfiguration());
|
modelBuilder.ApplyConfiguration(new AttachmentConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new IssueNotificationConfiguration());
|
modelBuilder.ApplyConfiguration(new ProposalConfiguration());
|
||||||
|
modelBuilder.ApplyConfiguration(new ProposalEventConfiguration());
|
||||||
|
modelBuilder.ApplyConfiguration(new ProposalVoteConfiguration());
|
||||||
|
modelBuilder.Entity<ProposalScore>().HasNoKey().ToView("v_proposal_score");
|
||||||
|
modelBuilder.ApplyConfiguration(new NotificationConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration());
|
modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration());
|
||||||
modelBuilder.Entity<PushDevice>().ToTable("push_device");
|
modelBuilder.Entity<PushDevice>().ToTable("push_device");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
using Helpdesk.Domain.Catalogs;
|
using Helpdesk.Domain.Catalogs;
|
||||||
using Helpdesk.Domain.Issues;
|
using Helpdesk.Domain.Issues;
|
||||||
|
using Helpdesk.Domain.Notifications;
|
||||||
|
using Helpdesk.Domain.Proposals;
|
||||||
using Helpdesk.Domain.Users;
|
using Helpdesk.Domain.Users;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||||
@@ -50,15 +52,16 @@ internal sealed class AttachmentConfiguration : IEntityTypeConfiguration<Attachm
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal sealed class IssueNotificationConfiguration : IEntityTypeConfiguration<IssueNotification>
|
internal sealed class NotificationConfiguration : IEntityTypeConfiguration<Notification>
|
||||||
{
|
{
|
||||||
public void Configure(EntityTypeBuilder<IssueNotification> b)
|
public void Configure(EntityTypeBuilder<Notification> b)
|
||||||
{
|
{
|
||||||
b.ToTable("notification");
|
b.ToTable("notification");
|
||||||
b.Property(x => x.Type).HasConversion<EnumCodeConverter<NotificationType>>().HasMaxLength(40);
|
b.Property(x => x.Type).HasConversion<EnumCodeConverter<NotificationType>>().HasMaxLength(40);
|
||||||
b.Property(x => x.Title).HasMaxLength(200);
|
b.Property(x => x.Title).HasMaxLength(200);
|
||||||
b.Property(x => x.Message).HasMaxLength(1000);
|
b.Property(x => x.Message).HasMaxLength(1000);
|
||||||
b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId).IsRequired(false);
|
b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId).IsRequired(false);
|
||||||
|
b.HasOne<Proposal>().WithMany().HasForeignKey(x => x.ProposalId);
|
||||||
b.HasOne<User>().WithMany().HasForeignKey(x => x.UserId);
|
b.HasOne<User>().WithMany().HasForeignKey(x => x.UserId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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<Proposal>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<Proposal> b)
|
||||||
|
{
|
||||||
|
b.ToTable("proposal");
|
||||||
|
b.Property(x => x.Title).HasMaxLength(200);
|
||||||
|
b.Property(x => x.Description).HasColumnType("text");
|
||||||
|
b.Property(x => x.Status).HasConversion<EnumCodeConverter<ProposalStatus>>().HasMaxLength(30);
|
||||||
|
b.HasOne<ProposalCategory>().WithMany().HasForeignKey(x => x.CategoryId);
|
||||||
|
b.HasOne<User>().WithMany().HasForeignKey(x => x.AuthorId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class ProposalEventConfiguration : IEntityTypeConfiguration<ProposalEvent>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<ProposalEvent> b)
|
||||||
|
{
|
||||||
|
b.ToTable("proposal_event");
|
||||||
|
b.Property(x => x.EventType).HasConversion<EnumCodeConverter<ProposalEventType>>().HasMaxLength(20);
|
||||||
|
b.Property(x => x.FromStatus).HasConversion<EnumCodeConverter<ProposalStatus>>().HasMaxLength(30);
|
||||||
|
b.Property(x => x.ToStatus).HasConversion<EnumCodeConverter<ProposalStatus>>().HasMaxLength(30);
|
||||||
|
b.Property(x => x.Note).HasColumnType("text");
|
||||||
|
b.HasOne(x => x.Proposal).WithMany().HasForeignKey(x => x.ProposalId);
|
||||||
|
b.HasOne<User>().WithMany().HasForeignKey(x => x.ActorId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class ProposalVoteConfiguration : IEntityTypeConfiguration<ProposalVote>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<ProposalVote> b)
|
||||||
|
{
|
||||||
|
b.ToTable("proposal_vote");
|
||||||
|
b.HasKey(x => new { x.ProposalId, x.UserId });
|
||||||
|
b.Property(x => x.Value).HasColumnType("tinyint");
|
||||||
|
b.HasOne<Proposal>().WithMany().HasForeignKey(x => x.ProposalId);
|
||||||
|
b.HasOne<User>().WithMany().HasForeignKey(x => x.UserId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<ProposalStatus>())
|
||||||
|
{
|
||||||
|
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<InvalidOperationException>(() => proposal.ChangeStatus(target, UserRole.Management, null));
|
||||||
|
Assert.Equal(from, proposal.Status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReviewRequiresManagementAndRejectionRequiresNote()
|
||||||
|
{
|
||||||
|
var proposal = At(ProposalStatus.Submitted);
|
||||||
|
Assert.Throws<InvalidOperationException>(() => proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Admin, null));
|
||||||
|
Assert.Throws<ArgumentException>(() => 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => proposal.Edit(Author, "Změna", "Popis", 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RepeatingVotePreservesTimestampAndClosingPreventsChanges()
|
||||||
|
{
|
||||||
|
var proposal = At(ProposalStatus.Submitted);
|
||||||
|
var now = DateTime.UnixEpoch;
|
||||||
|
Assert.Throws<InvalidOperationException>(() => new ProposalVote(proposal, Author, 1, now));
|
||||||
|
Assert.Throws<ArgumentOutOfRangeException>(() => 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<InvalidOperationException>(() => 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user