< Summary

Information
Class: RoleRadar.Application.Notes.Commands.ReplaceNoteSectionCommandHandler
Assembly: RoleRadar.Application
File(s): /home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Notes/Commands/ReplaceNoteSectionCommand.cs
Line coverage
91%
Covered lines: 96
Uncovered lines: 9
Coverable lines: 105
Total lines: 195
Line coverage: 91.4%
Branch coverage
81%
Covered branches: 13
Total branches: 16
Branch coverage: 81.2%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)100%11100%
HandleAsync()83.33%66100%
<HandleAsync()80%101083.63%

File(s)

/home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Notes/Commands/ReplaceNoteSectionCommand.cs

#LineLine coverage
 1using System.Text;
 2using RoleRadar.Application.Abstractions;
 3using RoleRadar.Domain.Audit;
 4using RoleRadar.Domain.Common;
 5using RoleRadar.Domain.Notes;
 6
 7namespace RoleRadar.Application.Notes.Commands;
 8
 9public sealed record NoteSectionReplacedDto(
 10    Guid Id,
 11    Guid VersionToken,
 12    Guid RevisionId,
 13    int RevisionCount,
 14    string BodyHash,
 15    DateTime UpdatedAtUtc);
 16
 17public sealed record ReplaceNoteSectionCommand(
 18    Guid Id,
 19    string Heading,
 20    string NewSectionBody,
 21    Guid VersionToken,
 22    string Actor,
 23    string? OwnerId = null) : ICommand<NoteSectionReplacedDto>;
 24
 25public sealed class ReplaceNoteSectionCommandValidator : ICommandValidator<ReplaceNoteSectionCommand>
 26{
 27    public ResultError? Validate(ReplaceNoteSectionCommand command)
 28    {
 29        ArgumentNullException.ThrowIfNull(command);
 30
 31        var actorError = CommandActor.Validate(command.Actor);
 32        if (actorError is not null)
 33        {
 34            return actorError;
 35        }
 36
 37        if (command.Id == Guid.Empty)
 38        {
 39            return new ResultError(ErrorCode.ValidationError, "Note ID cannot be Guid.Empty.");
 40        }
 41
 42        if (string.IsNullOrWhiteSpace(command.Heading))
 43        {
 44            return new ResultError(ErrorCode.ValidationError, "Target heading is required and cannot be blank.");
 45        }
 46
 47        if (command.NewSectionBody is null)
 48        {
 49            return new ResultError(ErrorCode.ValidationError, "NewSectionBody is required.");
 50        }
 51
 52        var sectionBytes = Encoding.UTF8.GetByteCount(command.NewSectionBody);
 53        if (sectionBytes > Note.MaxBodyBytes)
 54        {
 55            return new ResultError(
 56                ErrorCode.ValidationError,
 57                $"NewSectionBody UTF-8 size ({sectionBytes} bytes) exceeds maximum allowed ({Note.MaxBodyBytes} bytes / 
 58        }
 59
 60        if (command.VersionToken == Guid.Empty)
 61        {
 62            return new ResultError(ErrorCode.ValidationError, "VersionToken cannot be Guid.Empty.");
 63        }
 64
 65        return null;
 66    }
 67}
 68
 69public sealed class ReplaceNoteSectionCommandHandler : ICommandHandler<ReplaceNoteSectionCommand, NoteSectionReplacedDto
 70{
 471    private static readonly ReplaceNoteSectionCommandValidator Validator = new();
 72    private readonly INoteRepository _repository;
 73    private readonly IUtcClock _clock;
 74
 11275    public ReplaceNoteSectionCommandHandler(INoteRepository repository, IUtcClock clock)
 76    {
 11277        ArgumentNullException.ThrowIfNull(repository);
 11278        ArgumentNullException.ThrowIfNull(clock);
 11279        _repository = repository;
 11280        _clock = clock;
 11281    }
 82
 83    public async Task<Result<NoteSectionReplacedDto>> HandleAsync(
 84        ReplaceNoteSectionCommand command,
 85        CancellationToken cancellationToken = default)
 86    {
 1687        ArgumentNullException.ThrowIfNull(command);
 88
 1689        var validationError = Validator.Validate(command);
 1690        if (validationError is not null)
 91        {
 292            return Result<NoteSectionReplacedDto>.Failure(validationError.Value);
 93        }
 94
 1495        var ownerId = string.IsNullOrWhiteSpace(command.OwnerId)
 1496            ? OwnerId.Default.Value
 1497            : new OwnerId(command.OwnerId).Value;
 98
 1499        var actor = command.Actor.Trim();
 14100        var now = _clock.UtcNow;
 101
 14102        var outcome = await _repository.ExecuteInTransactionAsync(
 14103            async (tx, ct) =>
 14104            {
 14105                var existingResult = await _repository.GetByIdAsync(ownerId, command.Id, ct);
 14106                if (!existingResult.IsSuccess)
 14107                {
 0108                    return Result<NoteWriteOutcome>.Failure(existingResult.Error!.Value);
 14109                }
 14110
 14111                var note = existingResult.Value!;
 14112                if (note.VersionToken != command.VersionToken)
 14113                {
 4114                    return Result<NoteWriteOutcome>.Failure(
 4115                        ErrorCode.StaleVersionToken,
 4116                        $"Note '{command.Id}' was modified concurrently. Expected version token '{command.VersionToken}'
 4117                        new Dictionary<string, object?>
 4118                        {
 4119                            ["currentVersionToken"] = note.VersionToken.ToString()
 4120                        });
 14121                }
 14122
 10123                var sectionOutcome = MarkdownSectionParser.ReplaceSection(
 10124                    note.Body,
 10125                    command.Heading,
 10126                    command.NewSectionBody);
 14127
 10128                if (sectionOutcome.Status == SectionReplacementStatus.SectionNotFound)
 14129                {
 2130                    return Result<NoteWriteOutcome>.Failure(
 2131                        ErrorCode.SectionNotFound,
 2132                        $"Heading '{command.Heading}' was not found in note '{command.Id}'.",
 2133                        new Dictionary<string, object?>
 2134                        {
 2135                            ["availableHeadings"] = sectionOutcome.AvailableHeadings
 2136                        });
 14137                }
 14138
 8139                if (sectionOutcome.Status == SectionReplacementStatus.AmbiguousHeading)
 14140                {
 0141                    return Result<NoteWriteOutcome>.Failure(
 0142                        ErrorCode.AmbiguousHeading,
 0143                        $"Heading '{command.Heading}' matched multiple sections in note '{command.Id}'. Disambiguate usi
 0144                        new Dictionary<string, object?>
 0145                        {
 0146                            ["matchingHeadings"] = sectionOutcome.MatchingHeadings,
 0147                            ["availableHeadings"] = sectionOutcome.AvailableHeadings
 0148                        });
 14149                }
 14150
 8151                var resultingBytes = Encoding.UTF8.GetByteCount(sectionOutcome.UpdatedBody!);
 8152                if (resultingBytes > Note.MaxBodyBytes)
 14153                {
 2154                    return Result<NoteWriteOutcome>.Failure(
 2155                        ErrorCode.ValidationError,
 2156                        $"Resulting note body UTF-8 size ({resultingBytes} bytes) after section replacement exceeds maxi
 14157                }
 14158
 6159                var beforeSummary = AuditContentSummary.FromNote(note);
 6160                var revision = note.ReplaceBodyWithRevision(
 6161                    newBody: sectionOutcome.UpdatedBody!,
 6162                    reason: NoteRevision.ReasonReplaceSection,
 6163                    occurredAtUtc: now);
 14164
 6165                var afterSummary = AuditContentSummary.FromNote(note);
 6166                var audit = AuditLogEntry.CreateForReplaceSection(
 6167                    ownerId: ownerId,
 6168                    actor: actor,
 6169                    targetNoteId: note.Id,
 6170                    noteRevisionId: revision.Id,
 6171                    resultingVersionToken: note.VersionToken,
 6172                    occurredAtUtc: note.UpdatedAtUtc,
 6173                    beforeSummary: beforeSummary,
 6174                    afterSummary: afterSummary);
 14175
 6176                return await tx.ReplaceSectionAsync(note, command.VersionToken, revision, audit, ct);
 14177            },
 14178            cancellationToken);
 179
 14180        if (!outcome.IsSuccess)
 181        {
 8182            return Result<NoteSectionReplacedDto>.Failure(outcome.Error!.Value);
 183        }
 184
 6185        var updated = outcome.Value!.Note;
 6186        var savedRevision = outcome.Value.Revision!;
 6187        return Result<NoteSectionReplacedDto>.Success(new NoteSectionReplacedDto(
 6188            Id: updated.Id,
 6189            VersionToken: updated.VersionToken,
 6190            RevisionId: savedRevision.Id,
 6191            RevisionCount: updated.RevisionCount,
 6192            BodyHash: updated.CurrentBodyHash,
 6193            UpdatedAtUtc: updated.UpdatedAtUtc));
 16194    }
 195}