< Summary

Information
Class: RoleRadar.Application.Notes.Commands.ReplaceNoteSectionCommand
Assembly: RoleRadar.Application
File(s): /home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Notes/Commands/ReplaceNoteSectionCommand.cs
Line coverage
100%
Covered lines: 7
Uncovered lines: 0
Coverable lines: 7
Total lines: 195
Line coverage: 100%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_Id()100%11100%
get_Heading()100%11100%
get_NewSectionBody()100%11100%
get_VersionToken()100%11100%
get_Actor()100%11100%
get_OwnerId()100%11100%

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
 2817public sealed record ReplaceNoteSectionCommand(
 5418    Guid Id,
 4419    string Heading,
 6420    string NewSectionBody,
 4821    Guid VersionToken,
 4822    string Actor,
 4223    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{
 71    private static readonly ReplaceNoteSectionCommandValidator Validator = new();
 72    private readonly INoteRepository _repository;
 73    private readonly IUtcClock _clock;
 74
 75    public ReplaceNoteSectionCommandHandler(INoteRepository repository, IUtcClock clock)
 76    {
 77        ArgumentNullException.ThrowIfNull(repository);
 78        ArgumentNullException.ThrowIfNull(clock);
 79        _repository = repository;
 80        _clock = clock;
 81    }
 82
 83    public async Task<Result<NoteSectionReplacedDto>> HandleAsync(
 84        ReplaceNoteSectionCommand command,
 85        CancellationToken cancellationToken = default)
 86    {
 87        ArgumentNullException.ThrowIfNull(command);
 88
 89        var validationError = Validator.Validate(command);
 90        if (validationError is not null)
 91        {
 92            return Result<NoteSectionReplacedDto>.Failure(validationError.Value);
 93        }
 94
 95        var ownerId = string.IsNullOrWhiteSpace(command.OwnerId)
 96            ? OwnerId.Default.Value
 97            : new OwnerId(command.OwnerId).Value;
 98
 99        var actor = command.Actor.Trim();
 100        var now = _clock.UtcNow;
 101
 102        var outcome = await _repository.ExecuteInTransactionAsync(
 103            async (tx, ct) =>
 104            {
 105                var existingResult = await _repository.GetByIdAsync(ownerId, command.Id, ct);
 106                if (!existingResult.IsSuccess)
 107                {
 108                    return Result<NoteWriteOutcome>.Failure(existingResult.Error!.Value);
 109                }
 110
 111                var note = existingResult.Value!;
 112                if (note.VersionToken != command.VersionToken)
 113                {
 114                    return Result<NoteWriteOutcome>.Failure(
 115                        ErrorCode.StaleVersionToken,
 116                        $"Note '{command.Id}' was modified concurrently. Expected version token '{command.VersionToken}'
 117                        new Dictionary<string, object?>
 118                        {
 119                            ["currentVersionToken"] = note.VersionToken.ToString()
 120                        });
 121                }
 122
 123                var sectionOutcome = MarkdownSectionParser.ReplaceSection(
 124                    note.Body,
 125                    command.Heading,
 126                    command.NewSectionBody);
 127
 128                if (sectionOutcome.Status == SectionReplacementStatus.SectionNotFound)
 129                {
 130                    return Result<NoteWriteOutcome>.Failure(
 131                        ErrorCode.SectionNotFound,
 132                        $"Heading '{command.Heading}' was not found in note '{command.Id}'.",
 133                        new Dictionary<string, object?>
 134                        {
 135                            ["availableHeadings"] = sectionOutcome.AvailableHeadings
 136                        });
 137                }
 138
 139                if (sectionOutcome.Status == SectionReplacementStatus.AmbiguousHeading)
 140                {
 141                    return Result<NoteWriteOutcome>.Failure(
 142                        ErrorCode.AmbiguousHeading,
 143                        $"Heading '{command.Heading}' matched multiple sections in note '{command.Id}'. Disambiguate usi
 144                        new Dictionary<string, object?>
 145                        {
 146                            ["matchingHeadings"] = sectionOutcome.MatchingHeadings,
 147                            ["availableHeadings"] = sectionOutcome.AvailableHeadings
 148                        });
 149                }
 150
 151                var resultingBytes = Encoding.UTF8.GetByteCount(sectionOutcome.UpdatedBody!);
 152                if (resultingBytes > Note.MaxBodyBytes)
 153                {
 154                    return Result<NoteWriteOutcome>.Failure(
 155                        ErrorCode.ValidationError,
 156                        $"Resulting note body UTF-8 size ({resultingBytes} bytes) after section replacement exceeds maxi
 157                }
 158
 159                var beforeSummary = AuditContentSummary.FromNote(note);
 160                var revision = note.ReplaceBodyWithRevision(
 161                    newBody: sectionOutcome.UpdatedBody!,
 162                    reason: NoteRevision.ReasonReplaceSection,
 163                    occurredAtUtc: now);
 164
 165                var afterSummary = AuditContentSummary.FromNote(note);
 166                var audit = AuditLogEntry.CreateForReplaceSection(
 167                    ownerId: ownerId,
 168                    actor: actor,
 169                    targetNoteId: note.Id,
 170                    noteRevisionId: revision.Id,
 171                    resultingVersionToken: note.VersionToken,
 172                    occurredAtUtc: note.UpdatedAtUtc,
 173                    beforeSummary: beforeSummary,
 174                    afterSummary: afterSummary);
 175
 176                return await tx.ReplaceSectionAsync(note, command.VersionToken, revision, audit, ct);
 177            },
 178            cancellationToken);
 179
 180        if (!outcome.IsSuccess)
 181        {
 182            return Result<NoteSectionReplacedDto>.Failure(outcome.Error!.Value);
 183        }
 184
 185        var updated = outcome.Value!.Note;
 186        var savedRevision = outcome.Value.Revision!;
 187        return Result<NoteSectionReplacedDto>.Success(new NoteSectionReplacedDto(
 188            Id: updated.Id,
 189            VersionToken: updated.VersionToken,
 190            RevisionId: savedRevision.Id,
 191            RevisionCount: updated.RevisionCount,
 192            BodyHash: updated.CurrentBodyHash,
 193            UpdatedAtUtc: updated.UpdatedAtUtc));
 194    }
 195}