| | | 1 | | using RoleRadar.Application.Abstractions; |
| | | 2 | | using RoleRadar.Domain.Audit; |
| | | 3 | | using RoleRadar.Domain.Common; |
| | | 4 | | using RoleRadar.Domain.Tracking; |
| | | 5 | | |
| | | 6 | | namespace RoleRadar.Application.Tracking.Commands; |
| | | 7 | | |
| | | 8 | | public sealed class TrackerLogCommandHandler : ICommandHandler<TrackerLogCommand, TrackerLogResultDto> |
| | | 9 | | { |
| | | 10 | | private readonly ITrackingTransactionContext _context; |
| | | 11 | | private readonly IUtcClock _clock; |
| | | 12 | | |
| | 306 | 13 | | public TrackerLogCommandHandler(ITrackingTransactionContext context, IUtcClock clock) |
| | | 14 | | { |
| | 306 | 15 | | _context = context ?? throw new ArgumentNullException(nameof(context)); |
| | 306 | 16 | | _clock = clock ?? throw new ArgumentNullException(nameof(clock)); |
| | 306 | 17 | | } |
| | | 18 | | |
| | | 19 | | public async Task<Result<TrackerLogResultDto>> HandleAsync(TrackerLogCommand command, CancellationToken cancellation |
| | | 20 | | { |
| | 110 | 21 | | ArgumentNullException.ThrowIfNull(command); |
| | | 22 | | |
| | 110 | 23 | | if (string.IsNullOrWhiteSpace(command.Action)) |
| | | 24 | | { |
| | 2 | 25 | | return Result<TrackerLogResultDto>.Failure(ErrorCode.ValidationError, "Action is required for tracker_log.") |
| | | 26 | | } |
| | | 27 | | |
| | 108 | 28 | | var action = command.Action.Trim().ToLowerInvariant(); |
| | 108 | 29 | | var ownerId = string.IsNullOrWhiteSpace(command.OwnerId) |
| | 108 | 30 | | ? OwnerId.Default.Value |
| | 108 | 31 | | : new OwnerId(command.OwnerId).Value; |
| | 108 | 32 | | var now = _clock.UtcNow; |
| | | 33 | | |
| | 108 | 34 | | return action switch |
| | 108 | 35 | | { |
| | 50 | 36 | | "criterion_revision" => await HandleCriterionRevisionAsync(command, ownerId, now, cancellationToken), |
| | 10 | 37 | | "criterion_deactivate" => await HandleCriterionDeactivateAsync(command, ownerId, now, cancellationToken), |
| | 32 | 38 | | "search_run" => await HandleSearchRunAsync(command, ownerId, now, cancellationToken), |
| | 2 | 39 | | _ => Result<TrackerLogResultDto>.Failure( |
| | 2 | 40 | | ErrorCode.ValidationError, |
| | 2 | 41 | | $"Action '{command.Action}' is not supported by tracker_log.") |
| | 108 | 42 | | }; |
| | 96 | 43 | | } |
| | | 44 | | |
| | | 45 | | private async Task<Result<TrackerLogResultDto>> HandleCriterionRevisionAsync( |
| | | 46 | | TrackerLogCommand command, |
| | | 47 | | string ownerId, |
| | | 48 | | DateTimeOffset now, |
| | | 49 | | CancellationToken cancellationToken) |
| | | 50 | | { |
| | 50 | 51 | | if (string.IsNullOrWhiteSpace(command.Key)) |
| | | 52 | | { |
| | 2 | 53 | | return Result<TrackerLogResultDto>.Failure(ErrorCode.ValidationError, "Key is required for criterion_revisio |
| | | 54 | | } |
| | | 55 | | |
| | 48 | 56 | | var key = command.Key.Trim(); |
| | | 57 | | |
| | 48 | 58 | | if (string.IsNullOrWhiteSpace(command.Category) || |
| | 48 | 59 | | !TrackingEnumExtensions.TryParseCriterionCategory(command.Category, out var category)) |
| | | 60 | | { |
| | 2 | 61 | | return Result<TrackerLogResultDto>.Failure( |
| | 2 | 62 | | ErrorCode.ValidationError, |
| | 2 | 63 | | "Category is required for criterion_revision ('hard_skip', 'weight', 'preference')."); |
| | | 64 | | } |
| | | 65 | | |
| | 46 | 66 | | if (string.IsNullOrWhiteSpace(command.Value)) |
| | | 67 | | { |
| | 2 | 68 | | return Result<TrackerLogResultDto>.Failure(ErrorCode.ValidationError, "Value is required for criterion_revis |
| | | 69 | | } |
| | | 70 | | |
| | 44 | 71 | | if (string.IsNullOrWhiteSpace(command.Provenance) || |
| | 44 | 72 | | !TrackingEnumExtensions.TryParseProvenanceKind(command.Provenance, out var provenance)) |
| | | 73 | | { |
| | 2 | 74 | | return Result<TrackerLogResultDto>.Failure( |
| | 2 | 75 | | ErrorCode.ValidationError, |
| | 2 | 76 | | "Provenance is required for criterion_revision ('stated', 'inferred')."); |
| | | 77 | | } |
| | | 78 | | |
| | 42 | 79 | | if (string.IsNullOrWhiteSpace(command.EffectiveFrom) || |
| | 42 | 80 | | !DateTimeOffset.TryParse(command.EffectiveFrom, System.Globalization.CultureInfo.InvariantCulture, out var e |
| | | 81 | | { |
| | 2 | 82 | | return Result<TrackerLogResultDto>.Failure( |
| | 2 | 83 | | ErrorCode.ValidationError, |
| | 2 | 84 | | "EffectiveFrom timestamp is required for criterion_revision (ISO 8601)."); |
| | | 85 | | } |
| | | 86 | | |
| | 40 | 87 | | var activeRes = await _context.Criteria.GetActiveByKeyAsync(ownerId, key, cancellationToken); |
| | 40 | 88 | | if (!activeRes.IsSuccess) |
| | | 89 | | { |
| | 0 | 90 | | return Result<TrackerLogResultDto>.Failure(activeRes.Error ?? new ResultError(ErrorCode.ValidationError, "Fa |
| | | 91 | | } |
| | | 92 | | |
| | 40 | 93 | | var currentActive = activeRes.Value; |
| | | 94 | | |
| | 40 | 95 | | if (currentActive is null) |
| | | 96 | | { |
| | | 97 | | // Initial version creation: insert active version |
| | | 98 | | Criterion newCriterion; |
| | | 99 | | try |
| | | 100 | | { |
| | 12 | 101 | | newCriterion = Criterion.Create( |
| | 12 | 102 | | ownerId: ownerId, |
| | 12 | 103 | | key: key, |
| | 12 | 104 | | category: category, |
| | 12 | 105 | | value: command.Value, |
| | 12 | 106 | | provenance: provenance, |
| | 12 | 107 | | effectiveFrom: effectiveFrom, |
| | 12 | 108 | | createdAt: now); |
| | 12 | 109 | | } |
| | 0 | 110 | | catch (ArgumentException ex) |
| | | 111 | | { |
| | 0 | 112 | | return Result<TrackerLogResultDto>.Failure(ErrorCode.ValidationError, ex.Message); |
| | | 113 | | } |
| | | 114 | | |
| | 12 | 115 | | var upsertRes = await _context.Criteria.UpsertCriterionAsync(newCriterion, cancellationToken); |
| | 12 | 116 | | if (!upsertRes.IsSuccess) |
| | | 117 | | { |
| | 0 | 118 | | return Result<TrackerLogResultDto>.Failure(upsertRes.Error ?? new ResultError(ErrorCode.ValidationError, |
| | | 119 | | } |
| | | 120 | | |
| | 12 | 121 | | var auditSummary = new CriterionAuditSummary( |
| | 12 | 122 | | CriterionId: newCriterion.Id, |
| | 12 | 123 | | Key: newCriterion.Key, |
| | 12 | 124 | | Action: AuditOperation.CriterionRevision, |
| | 12 | 125 | | Timestamp: now); |
| | | 126 | | |
| | 12 | 127 | | await AppendAuditAsync( |
| | 12 | 128 | | ownerId, |
| | 12 | 129 | | "system", |
| | 12 | 130 | | AuditOperation.CriterionRevision, |
| | 12 | 131 | | newCriterion.Id, |
| | 12 | 132 | | newCriterion.VersionToken, |
| | 12 | 133 | | auditSummary, |
| | 12 | 134 | | cancellationToken); |
| | | 135 | | |
| | 12 | 136 | | return Result<TrackerLogResultDto>.Success(new TrackerLogResultDto( |
| | 12 | 137 | | Action: "criterion_revision", |
| | 12 | 138 | | RecordId: newCriterion.Id, |
| | 12 | 139 | | Status: "success", |
| | 12 | 140 | | UpdatedAtUtc: now, |
| | 12 | 141 | | VersionToken: newCriterion.VersionToken)); |
| | | 142 | | } |
| | | 143 | | |
| | | 144 | | // Active version exists: version token is mandatory |
| | 28 | 145 | | if (!command.VersionToken.HasValue || command.VersionToken.Value != currentActive.VersionToken) |
| | | 146 | | { |
| | 18 | 147 | | return Result<TrackerLogResultDto>.Failure( |
| | 18 | 148 | | ErrorCode.StaleVersionToken, |
| | 18 | 149 | | "Active criterion version token mismatch or missing."); |
| | | 150 | | } |
| | | 151 | | |
| | | 152 | | Criterion replacement; |
| | | 153 | | try |
| | | 154 | | { |
| | 10 | 155 | | replacement = currentActive.Supersede( |
| | 10 | 156 | | newCategory: category, |
| | 10 | 157 | | newValue: command.Value, |
| | 10 | 158 | | newProvenance: provenance, |
| | 10 | 159 | | newEffectiveFrom: effectiveFrom, |
| | 10 | 160 | | now: now); |
| | 8 | 161 | | } |
| | 2 | 162 | | catch (ArgumentException ex) |
| | | 163 | | { |
| | 2 | 164 | | return Result<TrackerLogResultDto>.Failure(ErrorCode.ValidationError, ex.Message); |
| | | 165 | | } |
| | | 166 | | |
| | | 167 | | // Persist both closed previous version and new active replacement |
| | 8 | 168 | | var closeOldRes = await _context.Criteria.UpsertCriterionAsync(currentActive, cancellationToken); |
| | 8 | 169 | | if (!closeOldRes.IsSuccess) |
| | | 170 | | { |
| | 0 | 171 | | return Result<TrackerLogResultDto>.Failure(closeOldRes.Error ?? new ResultError(ErrorCode.ValidationError, " |
| | | 172 | | } |
| | | 173 | | |
| | 8 | 174 | | var saveNewRes = await _context.Criteria.UpsertCriterionAsync(replacement, cancellationToken); |
| | 8 | 175 | | if (!saveNewRes.IsSuccess) |
| | | 176 | | { |
| | 0 | 177 | | return Result<TrackerLogResultDto>.Failure(saveNewRes.Error ?? new ResultError(ErrorCode.ValidationError, "F |
| | | 178 | | } |
| | | 179 | | |
| | 8 | 180 | | var revisionAuditSummary = new CriterionAuditSummary( |
| | 8 | 181 | | CriterionId: replacement.Id, |
| | 8 | 182 | | Key: replacement.Key, |
| | 8 | 183 | | Action: "criterion_revision", |
| | 8 | 184 | | Timestamp: now); |
| | | 185 | | |
| | 8 | 186 | | await AppendAuditAsync( |
| | 8 | 187 | | ownerId, |
| | 8 | 188 | | "system", |
| | 8 | 189 | | AuditOperation.CriterionRevision, |
| | 8 | 190 | | replacement.Id, |
| | 8 | 191 | | replacement.VersionToken, |
| | 8 | 192 | | revisionAuditSummary, |
| | 8 | 193 | | cancellationToken); |
| | | 194 | | |
| | 8 | 195 | | return Result<TrackerLogResultDto>.Success(new TrackerLogResultDto( |
| | 8 | 196 | | Action: "criterion_revision", |
| | 8 | 197 | | RecordId: replacement.Id, |
| | 8 | 198 | | Status: "success", |
| | 8 | 199 | | UpdatedAtUtc: now, |
| | 8 | 200 | | VersionToken: replacement.VersionToken)); |
| | 50 | 201 | | } |
| | | 202 | | |
| | | 203 | | private async Task<Result<TrackerLogResultDto>> HandleCriterionDeactivateAsync( |
| | | 204 | | TrackerLogCommand command, |
| | | 205 | | string ownerId, |
| | | 206 | | DateTimeOffset now, |
| | | 207 | | CancellationToken cancellationToken) |
| | | 208 | | { |
| | 10 | 209 | | if (string.IsNullOrWhiteSpace(command.Key)) |
| | | 210 | | { |
| | 2 | 211 | | return Result<TrackerLogResultDto>.Failure(ErrorCode.ValidationError, "Key is required for criterion_deactiv |
| | | 212 | | } |
| | | 213 | | |
| | 8 | 214 | | var key = command.Key.Trim(); |
| | | 215 | | |
| | 8 | 216 | | var activeRes = await _context.Criteria.GetActiveByKeyAsync(ownerId, key, cancellationToken); |
| | 8 | 217 | | if (!activeRes.IsSuccess) |
| | | 218 | | { |
| | 0 | 219 | | return Result<TrackerLogResultDto>.Failure(activeRes.Error ?? new ResultError(ErrorCode.ValidationError, "Fa |
| | | 220 | | } |
| | | 221 | | |
| | 8 | 222 | | var currentActive = activeRes.Value; |
| | 8 | 223 | | if (currentActive is null) |
| | | 224 | | { |
| | 0 | 225 | | return Result<TrackerLogResultDto>.Failure( |
| | 0 | 226 | | ErrorCode.NotFound, |
| | 0 | 227 | | $"No active criterion found for key '{key}'."); |
| | | 228 | | } |
| | | 229 | | |
| | 8 | 230 | | if (!command.VersionToken.HasValue || command.VersionToken.Value != currentActive.VersionToken) |
| | | 231 | | { |
| | 2 | 232 | | return Result<TrackerLogResultDto>.Failure( |
| | 2 | 233 | | ErrorCode.StaleVersionToken, |
| | 2 | 234 | | "Active criterion version token mismatch or missing."); |
| | | 235 | | } |
| | | 236 | | |
| | 6 | 237 | | DateTimeOffset deactivationDate = now; |
| | 6 | 238 | | if (!string.IsNullOrWhiteSpace(command.EffectiveFrom) && |
| | 6 | 239 | | DateTimeOffset.TryParse(command.EffectiveFrom, System.Globalization.CultureInfo.InvariantCulture, out var pa |
| | | 240 | | { |
| | 2 | 241 | | deactivationDate = parsedDeactDate; |
| | | 242 | | } |
| | | 243 | | |
| | 6 | 244 | | currentActive.Deactivate(deactivationDate); |
| | | 245 | | |
| | 6 | 246 | | var upsertRes = await _context.Criteria.UpsertCriterionAsync(currentActive, cancellationToken); |
| | 6 | 247 | | if (!upsertRes.IsSuccess) |
| | | 248 | | { |
| | 0 | 249 | | return Result<TrackerLogResultDto>.Failure(upsertRes.Error ?? new ResultError(ErrorCode.ValidationError, "Fa |
| | | 250 | | } |
| | | 251 | | |
| | 6 | 252 | | var auditSummary = new CriterionAuditSummary( |
| | 6 | 253 | | CriterionId: currentActive.Id, |
| | 6 | 254 | | Key: currentActive.Key, |
| | 6 | 255 | | Action: "criterion_deactivate", |
| | 6 | 256 | | Timestamp: now); |
| | | 257 | | |
| | 6 | 258 | | await AppendAuditAsync( |
| | 6 | 259 | | ownerId, |
| | 6 | 260 | | "system", |
| | 6 | 261 | | AuditOperation.CriterionDeactivate, |
| | 6 | 262 | | currentActive.Id, |
| | 6 | 263 | | currentActive.VersionToken, |
| | 6 | 264 | | auditSummary, |
| | 6 | 265 | | cancellationToken); |
| | | 266 | | |
| | 6 | 267 | | return Result<TrackerLogResultDto>.Success(new TrackerLogResultDto( |
| | 6 | 268 | | Action: "criterion_deactivate", |
| | 6 | 269 | | RecordId: currentActive.Id, |
| | 6 | 270 | | Status: "success", |
| | 6 | 271 | | UpdatedAtUtc: now, |
| | 6 | 272 | | VersionToken: currentActive.VersionToken)); |
| | 10 | 273 | | } |
| | | 274 | | |
| | | 275 | | private Task AppendAuditAsync( |
| | | 276 | | string ownerId, |
| | | 277 | | string actor, |
| | | 278 | | string operation, |
| | | 279 | | Guid criterionId, |
| | | 280 | | Guid versionToken, |
| | | 281 | | CriterionAuditSummary summary, |
| | | 282 | | CancellationToken cancellationToken) |
| | | 283 | | { |
| | 26 | 284 | | var details = AuditDetails.ForEntity( |
| | 26 | 285 | | changedFields: [summary.Key, summary.Action], |
| | 26 | 286 | | before: null, |
| | 26 | 287 | | after: new Dictionary<string, object?> { ["key"] = summary.Key, ["action"] = summary.Action }); |
| | | 288 | | |
| | 26 | 289 | | var entry = AuditLogEntry.CreateForTracking( |
| | 26 | 290 | | ownerId: ownerId, |
| | 26 | 291 | | actor: actor, |
| | 26 | 292 | | operation: operation, |
| | 26 | 293 | | entityType: "criterion", |
| | 26 | 294 | | entityId: criterionId, |
| | 26 | 295 | | resultingVersionToken: versionToken, |
| | 26 | 296 | | occurredAtUtc: summary.Timestamp.UtcDateTime, |
| | 26 | 297 | | details: details); |
| | | 298 | | |
| | 26 | 299 | | return _context.AppendAuditEntryAsync(entry, cancellationToken); |
| | | 300 | | } |
| | | 301 | | |
| | | 302 | | private async Task<Result<TrackerLogResultDto>> HandleSearchRunAsync( |
| | | 303 | | TrackerLogCommand command, |
| | | 304 | | string ownerId, |
| | | 305 | | DateTimeOffset now, |
| | | 306 | | CancellationToken cancellationToken) |
| | | 307 | | { |
| | 46 | 308 | | if (string.IsNullOrWhiteSpace(command.StartedAt) || |
| | 46 | 309 | | !DateTimeOffset.TryParse(command.StartedAt, System.Globalization.CultureInfo.InvariantCulture, out var start |
| | | 310 | | { |
| | 4 | 311 | | return Result<TrackerLogResultDto>.Failure( |
| | 4 | 312 | | ErrorCode.ValidationError, |
| | 4 | 313 | | "StartedAt is required for search_run (ISO 8601)."); |
| | | 314 | | } |
| | | 315 | | |
| | 42 | 316 | | if (!command.NewPostingsCount.HasValue || command.NewPostingsCount.Value < 0) |
| | | 317 | | { |
| | 2 | 318 | | return Result<TrackerLogResultDto>.Failure( |
| | 2 | 319 | | ErrorCode.ValidationError, |
| | 2 | 320 | | "NewPostingsCount must be >= 0."); |
| | | 321 | | } |
| | | 322 | | |
| | 40 | 323 | | if (command.Notes is not null && command.Notes.Length > SearchRun.MaxNotesLength) |
| | | 324 | | { |
| | 0 | 325 | | return Result<TrackerLogResultDto>.Failure( |
| | 0 | 326 | | ErrorCode.ValidationError, |
| | 0 | 327 | | $"Notes cannot exceed {SearchRun.MaxNotesLength} characters."); |
| | | 328 | | } |
| | | 329 | | |
| | 40 | 330 | | var startedAtUtc = startedAt.ToUniversalTime(); |
| | | 331 | | |
| | 40 | 332 | | var existingRes = await _context.SearchRuns.GetByStartedAtAsync(ownerId, startedAtUtc, cancellationToken); |
| | 40 | 333 | | if (existingRes.IsSuccess && existingRes.Value is not null) |
| | | 334 | | { |
| | 16 | 335 | | return Result<TrackerLogResultDto>.Success(new TrackerLogResultDto( |
| | 16 | 336 | | Action: "search_run", |
| | 16 | 337 | | RecordId: existingRes.Value.Id, |
| | 16 | 338 | | Status: "already_logged", |
| | 16 | 339 | | UpdatedAtUtc: existingRes.Value.CreatedAt)); |
| | | 340 | | } |
| | | 341 | | |
| | 24 | 342 | | var searchRun = SearchRun.Create( |
| | 24 | 343 | | ownerId: ownerId, |
| | 24 | 344 | | startedAt: startedAtUtc, |
| | 24 | 345 | | newPostingsCount: command.NewPostingsCount.Value, |
| | 24 | 346 | | reportNoteId: command.ReportNoteId, |
| | 24 | 347 | | notes: command.Notes, |
| | 24 | 348 | | createdAt: now); |
| | | 349 | | |
| | 24 | 350 | | var upsertRes = await _context.SearchRuns.UpsertSearchRunAsync(searchRun, cancellationToken); |
| | 10 | 351 | | if (!upsertRes.IsSuccess) |
| | | 352 | | { |
| | 0 | 353 | | var raceExisting = await _context.SearchRuns.GetByStartedAtAsync(ownerId, startedAtUtc, cancellationToken); |
| | 0 | 354 | | if (raceExisting.IsSuccess && raceExisting.Value is not null) |
| | | 355 | | { |
| | 0 | 356 | | return Result<TrackerLogResultDto>.Success(new TrackerLogResultDto( |
| | 0 | 357 | | Action: "search_run", |
| | 0 | 358 | | RecordId: raceExisting.Value.Id, |
| | 0 | 359 | | Status: "already_logged", |
| | 0 | 360 | | UpdatedAtUtc: raceExisting.Value.CreatedAt)); |
| | | 361 | | } |
| | | 362 | | |
| | 0 | 363 | | return Result<TrackerLogResultDto>.Failure(upsertRes.Error ?? new ResultError(ErrorCode.ValidationError, "Fa |
| | | 364 | | } |
| | | 365 | | |
| | 10 | 366 | | var details = AuditDetails.ForEntity( |
| | 10 | 367 | | changedFields: ["started_at", "new_postings_count"], |
| | 10 | 368 | | before: null, |
| | 10 | 369 | | after: new Dictionary<string, object?> |
| | 10 | 370 | | { |
| | 10 | 371 | | ["started_at"] = startedAtUtc.ToString("O"), |
| | 10 | 372 | | ["new_postings_count"] = searchRun.NewPostingsCount, |
| | 10 | 373 | | ["notes"] = searchRun.Notes |
| | 10 | 374 | | }); |
| | | 375 | | |
| | 10 | 376 | | var auditEntry = AuditLogEntry.CreateForTracking( |
| | 10 | 377 | | ownerId: ownerId, |
| | 10 | 378 | | actor: "mcp-user", |
| | 10 | 379 | | operation: AuditOperation.SearchRunLog, |
| | 10 | 380 | | entityType: "search_run", |
| | 10 | 381 | | entityId: searchRun.Id, |
| | 10 | 382 | | resultingVersionToken: searchRun.Id, |
| | 10 | 383 | | occurredAtUtc: now.UtcDateTime, |
| | 10 | 384 | | details: details); |
| | | 385 | | |
| | 10 | 386 | | await _context.AppendAuditEntryAsync(auditEntry, cancellationToken); |
| | | 387 | | |
| | 10 | 388 | | return Result<TrackerLogResultDto>.Success(new TrackerLogResultDto( |
| | 10 | 389 | | Action: "search_run", |
| | 10 | 390 | | RecordId: searchRun.Id, |
| | 10 | 391 | | Status: "success", |
| | 10 | 392 | | UpdatedAtUtc: searchRun.CreatedAt)); |
| | 32 | 393 | | } |
| | | 394 | | } |