| | | 1 | | using RoleRadar.Application.Abstractions; |
| | | 2 | | using RoleRadar.Domain.Common; |
| | | 3 | | using RoleRadar.Domain.Notes; |
| | | 4 | | |
| | | 5 | | namespace RoleRadar.Application.Import.Commands; |
| | | 6 | | |
| | | 7 | | public sealed record ImportMarkdownConflictDto( |
| | | 8 | | string ImportKey, |
| | | 9 | | Guid NoteId, |
| | | 10 | | string Title, |
| | | 11 | | string Reason); |
| | | 12 | | |
| | | 13 | | public sealed record ImportMarkdownOrphanDto( |
| | | 14 | | string ImportKey, |
| | | 15 | | Guid NoteId, |
| | | 16 | | string Title); |
| | | 17 | | |
| | | 18 | | public 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 | | |
| | | 28 | | public 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 | | |
| | | 38 | | public sealed class ImportMarkdownCommandValidator : ICommandValidator<ImportMarkdownCommand> |
| | | 39 | | { |
| | | 40 | | public ResultError? Validate(ImportMarkdownCommand command) |
| | | 41 | | { |
| | 104 | 42 | | ArgumentNullException.ThrowIfNull(command); |
| | | 43 | | |
| | 102 | 44 | | var actorError = CommandActor.Validate(command.Actor); |
| | 102 | 45 | | if (actorError is not null) |
| | | 46 | | { |
| | 0 | 47 | | return actorError; |
| | | 48 | | } |
| | | 49 | | |
| | 102 | 50 | | if (command.FilePaths is null || command.FilePaths.Count == 0) |
| | | 51 | | { |
| | 2 | 52 | | return new ResultError(ErrorCode.ValidationError, "At least one file path must be provided for import."); |
| | | 53 | | } |
| | | 54 | | |
| | 428 | 55 | | foreach (var path in command.FilePaths) |
| | | 56 | | { |
| | 116 | 57 | | if (string.IsNullOrWhiteSpace(path)) |
| | | 58 | | { |
| | 2 | 59 | | return new ResultError(ErrorCode.ValidationError, "File path cannot be null or whitespace."); |
| | | 60 | | } |
| | | 61 | | |
| | 114 | 62 | | if (!File.Exists(path)) |
| | | 63 | | { |
| | 2 | 64 | | return new ResultError(ErrorCode.ValidationError, $"File not found: '{path}'."); |
| | | 65 | | } |
| | | 66 | | } |
| | | 67 | | |
| | 96 | 68 | | var collidingGroups = command.FilePaths |
| | 112 | 69 | | .GroupBy(p => Path.GetFileName(p), StringComparer.OrdinalIgnoreCase) |
| | 106 | 70 | | .Where(g => g.Count() > 1) |
| | 96 | 71 | | .ToList(); |
| | | 72 | | |
| | 96 | 73 | | if (collidingGroups.Count > 0) |
| | | 74 | | { |
| | 6 | 75 | | var firstGroup = collidingGroups[0]; |
| | 6 | 76 | | var collidingPaths = string.Join("', '", firstGroup); |
| | 6 | 77 | | return new ResultError( |
| | 6 | 78 | | ErrorCode.ValidationError, |
| | 6 | 79 | | $"Input file paths resolve to colliding source file identifier '{firstGroup.Key}': '{collidingPaths}'.") |
| | | 80 | | } |
| | | 81 | | |
| | 90 | 82 | | if (!string.IsNullOrWhiteSpace(command.SourceFileId)) |
| | | 83 | | { |
| | 10 | 84 | | if (command.FilePaths.Count > 1) |
| | | 85 | | { |
| | 4 | 86 | | return new ResultError( |
| | 4 | 87 | | ErrorCode.ValidationError, |
| | 4 | 88 | | "Option '--source-id' can only be specified when importing exactly one file."); |
| | | 89 | | } |
| | | 90 | | } |
| | | 91 | | |
| | 86 | 92 | | if (string.IsNullOrWhiteSpace(command.Area)) |
| | | 93 | | { |
| | 2 | 94 | | return new ResultError(ErrorCode.ValidationError, "Area label is required and cannot be blank."); |
| | | 95 | | } |
| | | 96 | | |
| | 84 | 97 | | if (command.Area.Trim().Length > Note.MaxAreaChars) |
| | | 98 | | { |
| | 2 | 99 | | return new ResultError( |
| | 2 | 100 | | ErrorCode.ValidationError, |
| | 2 | 101 | | $"Area label length ({command.Area.Trim().Length}) exceeds maximum allowed ({Note.MaxAreaChars} characte |
| | | 102 | | } |
| | | 103 | | |
| | 82 | 104 | | if (command.Tags is not null) |
| | | 105 | | { |
| | 24 | 106 | | if (command.Tags.Count > Note.MaxTagCount) |
| | | 107 | | { |
| | 2 | 108 | | return new ResultError( |
| | 2 | 109 | | ErrorCode.ValidationError, |
| | 2 | 110 | | $"Tag count ({command.Tags.Count}) exceeds maximum allowed ({Note.MaxTagCount} tags)."); |
| | | 111 | | } |
| | | 112 | | |
| | 68 | 113 | | foreach (var tag in command.Tags) |
| | | 114 | | { |
| | 14 | 115 | | if (string.IsNullOrWhiteSpace(tag)) |
| | | 116 | | { |
| | 2 | 117 | | return new ResultError(ErrorCode.ValidationError, "Tag values cannot be blank or whitespace."); |
| | | 118 | | } |
| | | 119 | | |
| | 12 | 120 | | if (tag.Trim().Length > Note.MaxTagChars) |
| | | 121 | | { |
| | 2 | 122 | | return new ResultError( |
| | 2 | 123 | | ErrorCode.ValidationError, |
| | 2 | 124 | | $"Tag length ({tag.Trim().Length}) exceeds maximum allowed ({Note.MaxTagChars} characters)."); |
| | | 125 | | } |
| | | 126 | | } |
| | | 127 | | } |
| | | 128 | | |
| | 76 | 129 | | if (!string.IsNullOrWhiteSpace(command.DefaultDate) && !ProvenanceMarker.IsValidIsoDate(command.DefaultDate)) |
| | | 130 | | { |
| | 2 | 131 | | return new ResultError( |
| | 2 | 132 | | ErrorCode.ValidationError, |
| | 2 | 133 | | $"Invalid default date '{command.DefaultDate}'. Expected ISO-8601 date 'YYYY-MM-DD'."); |
| | | 134 | | } |
| | | 135 | | |
| | 74 | 136 | | return null; |
| | 8 | 137 | | } |
| | | 138 | | } |
| | | 139 | | |
| | | 140 | | public 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 | | } |