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
@@ -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<Issue> Issues { get; }
|
||||
DbSet<IssueEvent> IssueEvents { 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<PushDevice> PushDevices { get; }
|
||||
|
||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
||||
Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct);
|
||||
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
|
||||
}
|
||||
|
||||
public interface IPasswordHasher
|
||||
|
||||
@@ -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<CatalogService>();
|
||||
services.AddScoped<IssueService>();
|
||||
services.AddScoped<NotificationService>();
|
||||
services.AddScoped<NotificationWriter>();
|
||||
services.AddScoped<ProposalService>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -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<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);
|
||||
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
|
||||
|
||||
@@ -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<IssueNotification> Inbox()
|
||||
private IQueryable<Notification> Inbox()
|
||||
{
|
||||
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;
|
||||
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.");
|
||||
}
|
||||
Reference in new issue
Block a user