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,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