< Summary

Information
Class: RoleRadar.Application.Import.Commands.ImportMarkdownCommandValidator
Assembly: RoleRadar.Application
File(s): /home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Import/Commands/ImportMarkdownCommand.cs
Line coverage
98%
Covered lines: 49
Uncovered lines: 1
Coverable lines: 50
Total lines: 349
Line coverage: 98%
Branch coverage
94%
Covered branches: 34
Total branches: 36
Branch coverage: 94.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
Validate(...)94.44%363698%

File(s)

/home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Import/Commands/ImportMarkdownCommand.cs

#LineLine coverage
 1using RoleRadar.Application.Abstractions;
 2using RoleRadar.Domain.Common;
 3using RoleRadar.Domain.Notes;
 4
 5namespace RoleRadar.Application.Import.Commands;
 6
 7public sealed record ImportMarkdownConflictDto(
 8    string ImportKey,
 9    Guid NoteId,
 10    string Title,
 11    string Reason);
 12
 13public sealed record ImportMarkdownOrphanDto(
 14    string ImportKey,
 15    Guid NoteId,
 16    string Title);
 17
 18public sealed record ImportMarkdownSummaryDto(
 19    int FilesProcessed,
 20    int CreatedCount,
 21    int UpdatedCount,
 22    int UnchangedCount,
 23    int ConflictCount,
 24    int OrphanCount,
 25    IReadOnlyList<ImportMarkdownConflictDto> Conflicts,
 26    IReadOnlyList<ImportMarkdownOrphanDto> Orphans);
 27
 28public sealed record ImportMarkdownCommand(
 29    IReadOnlyList<string> FilePaths,
 30    string Actor,
 31    string Area = "imported",
 32    IReadOnlyList<string>? Tags = null,
 33    string? DefaultDate = null,
 34    bool DryRun = false,
 35    string? SourceFileId = null,
 36    string? OwnerId = null) : ICommand<ImportMarkdownSummaryDto>;
 37
 38public sealed class ImportMarkdownCommandValidator : ICommandValidator<ImportMarkdownCommand>
 39{
 40    public ResultError? Validate(ImportMarkdownCommand command)
 41    {
 10442        ArgumentNullException.ThrowIfNull(command);
 43
 10244        var actorError = CommandActor.Validate(command.Actor);
 10245        if (actorError is not null)
 46        {
 047            return actorError;
 48        }
 49
 10250        if (command.FilePaths is null || command.FilePaths.Count == 0)
 51        {
 252            return new ResultError(ErrorCode.ValidationError, "At least one file path must be provided for import.");
 53        }
 54
 42855        foreach (var path in command.FilePaths)
 56        {
 11657            if (string.IsNullOrWhiteSpace(path))
 58            {
 259                return new ResultError(ErrorCode.ValidationError, "File path cannot be null or whitespace.");
 60            }
 61
 11462            if (!File.Exists(path))
 63            {
 264                return new ResultError(ErrorCode.ValidationError, $"File not found: '{path}'.");
 65            }
 66        }
 67
 9668        var collidingGroups = command.FilePaths
 11269            .GroupBy(p => Path.GetFileName(p), StringComparer.OrdinalIgnoreCase)
 10670            .Where(g => g.Count() > 1)
 9671            .ToList();
 72
 9673        if (collidingGroups.Count > 0)
 74        {
 675            var firstGroup = collidingGroups[0];
 676            var collidingPaths = string.Join("', '", firstGroup);
 677            return new ResultError(
 678                ErrorCode.ValidationError,
 679                $"Input file paths resolve to colliding source file identifier '{firstGroup.Key}': '{collidingPaths}'.")
 80        }
 81
 9082        if (!string.IsNullOrWhiteSpace(command.SourceFileId))
 83        {
 1084            if (command.FilePaths.Count > 1)
 85            {
 486                return new ResultError(
 487                    ErrorCode.ValidationError,
 488                    "Option '--source-id' can only be specified when importing exactly one file.");
 89            }
 90        }
 91
 8692        if (string.IsNullOrWhiteSpace(command.Area))
 93        {
 294            return new ResultError(ErrorCode.ValidationError, "Area label is required and cannot be blank.");
 95        }
 96
 8497        if (command.Area.Trim().Length > Note.MaxAreaChars)
 98        {
 299            return new ResultError(
 2100                ErrorCode.ValidationError,
 2101                $"Area label length ({command.Area.Trim().Length}) exceeds maximum allowed ({Note.MaxAreaChars} characte
 102        }
 103
 82104        if (command.Tags is not null)
 105        {
 24106            if (command.Tags.Count > Note.MaxTagCount)
 107            {
 2108                return new ResultError(
 2109                    ErrorCode.ValidationError,
 2110                    $"Tag count ({command.Tags.Count}) exceeds maximum allowed ({Note.MaxTagCount} tags).");
 111            }
 112
 68113            foreach (var tag in command.Tags)
 114            {
 14115                if (string.IsNullOrWhiteSpace(tag))
 116                {
 2117                    return new ResultError(ErrorCode.ValidationError, "Tag values cannot be blank or whitespace.");
 118                }
 119
 12120                if (tag.Trim().Length > Note.MaxTagChars)
 121                {
 2122                    return new ResultError(
 2123                        ErrorCode.ValidationError,
 2124                        $"Tag length ({tag.Trim().Length}) exceeds maximum allowed ({Note.MaxTagChars} characters).");
 125                }
 126            }
 127        }
 128
 76129        if (!string.IsNullOrWhiteSpace(command.DefaultDate) && !ProvenanceMarker.IsValidIsoDate(command.DefaultDate))
 130        {
 2131            return new ResultError(
 2132                ErrorCode.ValidationError,
 2133                $"Invalid default date '{command.DefaultDate}'. Expected ISO-8601 date 'YYYY-MM-DD'.");
 134        }
 135
 74136        return null;
 8137    }
 138}
 139
 140public sealed class ImportMarkdownCommandHandler : ICommandHandler<ImportMarkdownCommand, ImportMarkdownSummaryDto>
 141{
 142    private static readonly ImportMarkdownCommandValidator Validator = new();
 143    private readonly INoteRepository _repository;
 144    private readonly IUtcClock _clock;
 145
 146    public ImportMarkdownCommandHandler(INoteRepository repository, IUtcClock clock)
 147    {
 148        ArgumentNullException.ThrowIfNull(repository);
 149        ArgumentNullException.ThrowIfNull(clock);
 150        _repository = repository;
 151        _clock = clock;
 152    }
 153
 154    public async Task<Result<ImportMarkdownSummaryDto>> HandleAsync(
 155        ImportMarkdownCommand command,
 156        CancellationToken cancellationToken = default)
 157    {
 158        ArgumentNullException.ThrowIfNull(command);
 159
 160        var validationError = Validator.Validate(command);
 161        if (validationError is not null)
 162        {
 163            return Result<ImportMarkdownSummaryDto>.Failure(validationError.Value);
 164        }
 165
 166        var ownerId = string.IsNullOrWhiteSpace(command.OwnerId)
 167            ? OwnerId.Default.Value
 168            : new OwnerId(command.OwnerId).Value;
 169
 170        var actor = command.Actor.Trim();
 171        var normalizedTags = Note.NormalizeTags(command.Tags);
 172        var normalizedArea = Note.NormalizeArea(command.Area);
 173        var now = _clock.UtcNow;
 174
 175        // Pre-flight UTF-8 validation across all input files before any database operations
 176        var fileDataList = new List<(string FilePath, string SourceFileId, byte[] Bytes)>(command.FilePaths.Count);
 177        foreach (var path in command.FilePaths)
 178        {
 179            byte[] bytes;
 180            try
 181            {
 182                bytes = await File.ReadAllBytesAsync(path, cancellationToken);
 183            }
 184            catch (Exception ex)
 185            {
 186                return Result<ImportMarkdownSummaryDto>.Failure(
 187                    ErrorCode.ValidationError,
 188                    $"Failed to read file '{path}': {ex.Message}");
 189            }
 190
 191            if (!MarkdownImportParser.ValidateUtf8(bytes))
 192            {
 193                return Result<ImportMarkdownSummaryDto>.Failure(
 194                    ErrorCode.InvalidUtf8,
 195                    $"File '{path}' contains invalid UTF-8 byte sequences.");
 196            }
 197
 198            var sourceFileId = (!string.IsNullOrWhiteSpace(command.SourceFileId) && command.FilePaths.Count == 1)
 199                ? command.SourceFileId.Trim()
 200                : Path.GetFileName(path);
 201
 202            fileDataList.Add((path, sourceFileId, bytes));
 203        }
 204
 205        var createdCount = 0;
 206        var updatedCount = 0;
 207        var unchangedCount = 0;
 208        var conflictCount = 0;
 209        var orphanCount = 0;
 210
 211        var conflicts = new List<ImportMarkdownConflictDto>();
 212        var orphans = new List<ImportMarkdownOrphanDto>();
 213
 214        foreach (var (filePath, sourceFileId, bytes) in fileDataList)
 215        {
 216            var resolvedDefaultDate = !string.IsNullOrWhiteSpace(command.DefaultDate)
 217                ? command.DefaultDate.Trim()
 218                : File.GetLastWriteTimeUtc(filePath).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCu
 219
 220            var parsedSections = MarkdownImportParser.ParseBytes(sourceFileId, bytes, resolvedDefaultDate);
 221
 222            var existingNotesResult = await _repository.GetImportedBySourceFileAsync(ownerId, sourceFileId, cancellation
 223            if (!existingNotesResult.IsSuccess)
 224            {
 225                return Result<ImportMarkdownSummaryDto>.Failure(existingNotesResult.Error!.Value);
 226            }
 227
 228            var existingMap = existingNotesResult.Value!
 229                .Where(n => n.ImportMetadata is not null)
 230                .ToDictionary(n => n.ImportMetadata!.ImportKey, StringComparer.Ordinal);
 231
 232            var seenImportKeys = new HashSet<string>(StringComparer.Ordinal);
 233
 234            foreach (var section in parsedSections)
 235            {
 236                seenImportKeys.Add(section.ImportKey);
 237
 238                if (!existingMap.TryGetValue(section.ImportKey, out var existing))
 239                {
 240                    // Brand new section
 241                    if (!command.DryRun)
 242                    {
 243                        var upsertReq = new UpsertImportedSectionRequest(
 244                            OwnerId: ownerId,
 245                            SourceFileId: sourceFileId,
 246                            HeadingPath: section.HeadingPath,
 247                            OccurrenceIndex: section.OccurrenceIndex,
 248                            SectionOrderIndex: section.SectionOrderIndex,
 249                            Title: section.Title,
 250                            Body: section.Body,
 251                            Tags: normalizedTags,
 252                            Area: normalizedArea,
 253                            Provenance: section.Provenance,
 254                            ResolvedDefaultDate: resolvedDefaultDate,
 255                            Actor: actor,
 256                            OccurredAtUtc: now);
 257
 258                        var outcome = await _repository.ExecuteInTransactionAsync(
 259                            (tx, ct) => tx.UpsertImportedSectionAsync(upsertReq, ct),
 260                            cancellationToken);
 261
 262                        if (!outcome.IsSuccess)
 263                        {
 264                            return Result<ImportMarkdownSummaryDto>.Failure(outcome.Error!.Value);
 265                        }
 266                    }
 267
 268                    createdCount++;
 269                }
 270                else
 271                {
 272                    // Existing section in DB
 273                    if (existing.HasPostImportEdits)
 274                    {
 275                        // Stored note was modified after its last import: conflict, do not overwrite!
 276                        conflicts.Add(new ImportMarkdownConflictDto(
 277                            ImportKey: section.ImportKey,
 278                            NoteId: existing.Id,
 279                            Title: existing.Title,
 280                            Reason: "Note was modified after its last import."));
 281                        conflictCount++;
 282                    }
 283                    else if (string.Equals(existing.CurrentBodyHash, section.BodyHash, StringComparison.Ordinal))
 284                    {
 285                        // Unchanged body: no write needed, no duplicate revision
 286                        unchangedCount++;
 287                    }
 288                    else
 289                    {
 290                        // Source section updated and stored note unmodified: update note with revision
 291                        if (!command.DryRun)
 292                        {
 293                            var upsertReq = new UpsertImportedSectionRequest(
 294                                OwnerId: ownerId,
 295                                SourceFileId: sourceFileId,
 296                                HeadingPath: section.HeadingPath,
 297                                OccurrenceIndex: section.OccurrenceIndex,
 298                                SectionOrderIndex: section.SectionOrderIndex,
 299                                Title: section.Title,
 300                                Body: section.Body,
 301                                Tags: normalizedTags,
 302                                Area: normalizedArea,
 303                                Provenance: section.Provenance,
 304                                ResolvedDefaultDate: resolvedDefaultDate,
 305                                Actor: actor,
 306                                OccurredAtUtc: now);
 307
 308                            var outcome = await _repository.ExecuteInTransactionAsync(
 309                                (tx, ct) => tx.UpsertImportedSectionAsync(upsertReq, ct),
 310                                cancellationToken);
 311
 312                            if (!outcome.IsSuccess)
 313                            {
 314                                return Result<ImportMarkdownSummaryDto>.Failure(outcome.Error!.Value);
 315                            }
 316                        }
 317
 318                        updatedCount++;
 319                    }
 320                }
 321            }
 322
 323            // Detect orphaned notes that existed for this source file but are no longer in the parsed source file
 324            foreach (var (key, note) in existingMap)
 325            {
 326                if (!seenImportKeys.Contains(key))
 327                {
 328                    orphans.Add(new ImportMarkdownOrphanDto(
 329                        ImportKey: key,
 330                        NoteId: note.Id,
 331                        Title: note.Title));
 332                    orphanCount++;
 333                }
 334            }
 335        }
 336
 337        var summary = new ImportMarkdownSummaryDto(
 338            FilesProcessed: fileDataList.Count,
 339            CreatedCount: createdCount,
 340            UpdatedCount: updatedCount,
 341            UnchangedCount: unchangedCount,
 342            ConflictCount: conflictCount,
 343            OrphanCount: orphanCount,
 344            Conflicts: conflicts,
 345            Orphans: orphans);
 346
 347        return Result<ImportMarkdownSummaryDto>.Success(summary);
 348    }
 349}