| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using System.Text.Json.Serialization; |
| | | 4 | | using RoleRadar.Application.Abstractions; |
| | | 5 | | using RoleRadar.Domain.Audit; |
| | | 6 | | using RoleRadar.Domain.Common; |
| | | 7 | | using RoleRadar.Domain.Tracking; |
| | | 8 | | |
| | | 9 | | namespace RoleRadar.Application.Tracking.Commands; |
| | | 10 | | |
| | | 11 | | public sealed record PostingDto( |
| | | 12 | | Guid Id, |
| | | 13 | | Guid CompanyId, |
| | | 14 | | string Title, |
| | | 15 | | string NormalizedTitle, |
| | | 16 | | string Disposition, |
| | | 17 | | string ResurfacePolicy, |
| | | 18 | | Guid VersionToken, |
| | | 19 | | string? Location = null, |
| | | 20 | | string? RemoteType = null, |
| | | 21 | | decimal? Score = null, |
| | | 22 | | string? CultureLevel = null, |
| | | 23 | | DateTimeOffset? LastVerifiedAt = null, |
| | | 24 | | bool? CompHighPriority = null); |
| | | 25 | | |
| | | 26 | | [JsonConverter(typeof(SignalInputDtoConverter))] |
| | | 27 | | public sealed record SignalInputDto( |
| | | 28 | | string SignalType, |
| | | 29 | | string Evidence = "reported by agent", |
| | | 30 | | string? ObservedAt = null, |
| | | 31 | | string? DeadlineDate = null); |
| | | 32 | | |
| | | 33 | | public sealed class SignalInputDtoConverter : JsonConverter<SignalInputDto> |
| | | 34 | | { |
| | | 35 | | private const string DefaultEvidence = "reported by agent"; |
| | | 36 | | |
| | | 37 | | public override SignalInputDto? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | | 38 | | { |
| | | 39 | | if (reader.TokenType == JsonTokenType.Null) |
| | | 40 | | { |
| | | 41 | | return null; |
| | | 42 | | } |
| | | 43 | | |
| | | 44 | | if (reader.TokenType == JsonTokenType.String) |
| | | 45 | | { |
| | | 46 | | var text = reader.GetString()?.Trim() ?? string.Empty; |
| | | 47 | | if (text.StartsWith("deadline:", StringComparison.OrdinalIgnoreCase)) |
| | | 48 | | { |
| | | 49 | | var deadlineDate = text["deadline:".Length..].Trim(); |
| | | 50 | | return new SignalInputDto( |
| | | 51 | | SignalType: "deadline", |
| | | 52 | | Evidence: DefaultEvidence, |
| | | 53 | | ObservedAt: null, |
| | | 54 | | DeadlineDate: deadlineDate); |
| | | 55 | | } |
| | | 56 | | |
| | | 57 | | return new SignalInputDto( |
| | | 58 | | SignalType: text, |
| | | 59 | | Evidence: DefaultEvidence, |
| | | 60 | | ObservedAt: null, |
| | | 61 | | DeadlineDate: null); |
| | | 62 | | } |
| | | 63 | | |
| | | 64 | | if (reader.TokenType == JsonTokenType.StartObject) |
| | | 65 | | { |
| | | 66 | | using var doc = JsonDocument.ParseValue(ref reader); |
| | | 67 | | var root = doc.RootElement; |
| | | 68 | | |
| | | 69 | | string? signalType = null; |
| | | 70 | | if (root.TryGetProperty("signalType", out var stElem) || root.TryGetProperty("signal_type", out stElem)) |
| | | 71 | | { |
| | | 72 | | signalType = stElem.GetString(); |
| | | 73 | | } |
| | | 74 | | |
| | | 75 | | string? evidence = null; |
| | | 76 | | if (root.TryGetProperty("evidence", out var evElem)) |
| | | 77 | | { |
| | | 78 | | evidence = evElem.GetString(); |
| | | 79 | | } |
| | | 80 | | if (string.IsNullOrWhiteSpace(evidence)) |
| | | 81 | | { |
| | | 82 | | evidence = DefaultEvidence; |
| | | 83 | | } |
| | | 84 | | |
| | | 85 | | string? deadlineDate = null; |
| | | 86 | | if (root.TryGetProperty("deadlineDate", out var dlElem) || root.TryGetProperty("deadline_date", out dlElem)) |
| | | 87 | | { |
| | | 88 | | deadlineDate = dlElem.GetString(); |
| | | 89 | | } |
| | | 90 | | |
| | | 91 | | string? observedAt = null; |
| | | 92 | | if (root.TryGetProperty("observedAt", out var obsElem) || root.TryGetProperty("observed_at", out obsElem)) |
| | | 93 | | { |
| | | 94 | | observedAt = obsElem.GetString(); |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | return new SignalInputDto( |
| | | 98 | | SignalType: signalType ?? string.Empty, |
| | | 99 | | Evidence: evidence, |
| | | 100 | | ObservedAt: observedAt, |
| | | 101 | | DeadlineDate: deadlineDate); |
| | | 102 | | } |
| | | 103 | | |
| | | 104 | | throw new JsonException($"Expected string or object for signal, but encountered {reader.TokenType}."); |
| | | 105 | | } |
| | | 106 | | |
| | | 107 | | public override void Write(Utf8JsonWriter writer, SignalInputDto value, JsonSerializerOptions options) |
| | | 108 | | { |
| | | 109 | | ArgumentNullException.ThrowIfNull(writer); |
| | | 110 | | ArgumentNullException.ThrowIfNull(value); |
| | | 111 | | |
| | | 112 | | writer.WriteStartObject(); |
| | | 113 | | writer.WriteString("signalType", value.SignalType); |
| | | 114 | | writer.WriteString("evidence", value.Evidence); |
| | | 115 | | if (value.ObservedAt is not null) |
| | | 116 | | { |
| | | 117 | | writer.WriteString("observedAt", value.ObservedAt); |
| | | 118 | | } |
| | | 119 | | if (value.DeadlineDate is not null) |
| | | 120 | | { |
| | | 121 | | writer.WriteString("deadlineDate", value.DeadlineDate); |
| | | 122 | | } |
| | | 123 | | writer.WriteEndObject(); |
| | | 124 | | } |
| | | 125 | | } |
| | | 126 | | |
| | | 127 | | public sealed record PostingRecordResultDto( |
| | | 128 | | string Status, |
| | | 129 | | PostingDto? Posting = null, |
| | | 130 | | string? PriorReason = null, |
| | | 131 | | bool? CanReopen = null, |
| | | 132 | | IReadOnlyList<PostingCandidate>? Candidates = null, |
| | | 133 | | IReadOnlyList<PostingDifference>? Differences = null); |
| | | 134 | | |
| | | 135 | | public sealed record RecordPostingCommand( |
| | | 136 | | string Actor, |
| | | 137 | | Guid? PostingId = null, |
| | | 138 | | Guid? VersionToken = null, |
| | | 139 | | Guid? CompanyId = null, |
| | | 140 | | string? Title = null, |
| | | 141 | | string? Url = null, |
| | | 142 | | string? SourceKind = null, |
| | | 143 | | string? AtsTenant = null, |
| | | 144 | | string? RequisitionId = null, |
| | | 145 | | string? Location = null, |
| | | 146 | | string? RemoteType = null, |
| | | 147 | | decimal? CompensationMin = null, |
| | | 148 | | decimal? CompensationMax = null, |
| | | 149 | | string? CompensationCurrency = null, |
| | | 150 | | string? CompensationText = null, |
| | | 151 | | string? PostedDate = null, |
| | | 152 | | decimal? Score = null, |
| | | 153 | | string? CultureLevel = null, |
| | | 154 | | string? CultureSummary = null, |
| | | 155 | | string? ResurfacePolicy = null, |
| | | 156 | | Guid? ScreeningNoteId = null, |
| | | 157 | | Guid? DuplicateOfId = null, |
| | | 158 | | IReadOnlyList<SignalInputDto>? Signals = null, |
| | | 159 | | string? OwnerId = null, |
| | | 160 | | bool? CompHighPriority = null) : ICommand<PostingRecordResultDto>; |
| | | 161 | | |
| | | 162 | | public sealed class RecordPostingCommandValidator : ICommandValidator<RecordPostingCommand> |
| | | 163 | | { |
| | | 164 | | public ResultError? Validate(RecordPostingCommand command) |
| | | 165 | | { |
| | 5566 | 166 | | ArgumentNullException.ThrowIfNull(command); |
| | | 167 | | |
| | 5564 | 168 | | var actorError = CommandActor.Validate(command.Actor); |
| | 5564 | 169 | | if (actorError is not null) |
| | | 170 | | { |
| | 0 | 171 | | return actorError; |
| | | 172 | | } |
| | | 173 | | |
| | | 174 | | // Explicit update mode |
| | 5564 | 175 | | if (command.PostingId.HasValue) |
| | | 176 | | { |
| | 30 | 177 | | if (!command.VersionToken.HasValue) |
| | | 178 | | { |
| | 2 | 179 | | return new ResultError(ErrorCode.StaleVersionToken, "VersionToken is required when updating a posting.") |
| | | 180 | | } |
| | | 181 | | |
| | 28 | 182 | | if (command.Title is not null && (string.IsNullOrWhiteSpace(command.Title) || command.Title.Trim().Length > |
| | | 183 | | { |
| | 4 | 184 | | return new ResultError(ErrorCode.ValidationError, $"Title must be 1..{Posting.MaxTitleLength} characters |
| | | 185 | | } |
| | | 186 | | |
| | 24 | 187 | | if (command.Url is not null && command.Url.Length > Posting.MaxUrlLength) |
| | | 188 | | { |
| | 2 | 189 | | return new ResultError(ErrorCode.ValidationError, $"Url cannot exceed {Posting.MaxUrlLength} characters. |
| | | 190 | | } |
| | | 191 | | |
| | 22 | 192 | | if (command.Score.HasValue && (command.Score.Value < 0.0m || command.Score.Value > 10.0m)) |
| | | 193 | | { |
| | 4 | 194 | | return new ResultError(ErrorCode.ValidationError, "Score must be between 0.0 and 10.0."); |
| | | 195 | | } |
| | | 196 | | |
| | 18 | 197 | | if (command.Signals is not null) |
| | | 198 | | { |
| | 0 | 199 | | foreach (var sig in command.Signals) |
| | | 200 | | { |
| | 0 | 201 | | if (sig is null) |
| | | 202 | | { |
| | 0 | 203 | | return new ResultError(ErrorCode.ValidationError, "Signal item cannot be null."); |
| | | 204 | | } |
| | | 205 | | |
| | 0 | 206 | | if (!TrackingEnumExtensions.TryParseSignalType(sig.SignalType, out _)) |
| | | 207 | | { |
| | 0 | 208 | | return new ResultError(ErrorCode.ValidationError, $"Invalid signalType '{sig.SignalType}'."); |
| | | 209 | | } |
| | | 210 | | |
| | 0 | 211 | | if (!string.IsNullOrWhiteSpace(sig.DeadlineDate)) |
| | | 212 | | { |
| | 0 | 213 | | if (!DateOnly.TryParseExact(sig.DeadlineDate.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, |
| | | 214 | | { |
| | 0 | 215 | | return new ResultError(ErrorCode.ValidationError, "Deadline date must be in YYYY-MM-DD forma |
| | | 216 | | } |
| | | 217 | | } |
| | | 218 | | |
| | 0 | 219 | | if (string.IsNullOrWhiteSpace(sig.Evidence) || sig.Evidence.Trim().Length > 500) |
| | | 220 | | { |
| | 0 | 221 | | return new ResultError(ErrorCode.ValidationError, "Signal evidence is required and cannot exceed |
| | | 222 | | } |
| | | 223 | | } |
| | | 224 | | } |
| | | 225 | | |
| | 18 | 226 | | return null; |
| | | 227 | | } |
| | | 228 | | |
| | | 229 | | // Create / Ingest mode |
| | 5534 | 230 | | if (!command.CompanyId.HasValue || command.CompanyId.Value == Guid.Empty) |
| | | 231 | | { |
| | 2 | 232 | | return new ResultError(ErrorCode.ValidationError, "CompanyId is required for new posting."); |
| | | 233 | | } |
| | | 234 | | |
| | 5532 | 235 | | if (string.IsNullOrWhiteSpace(command.Title)) |
| | | 236 | | { |
| | 2 | 237 | | return new ResultError(ErrorCode.ValidationError, "Title is required and cannot be blank."); |
| | | 238 | | } |
| | | 239 | | |
| | 5530 | 240 | | if (command.Title.Trim().Length > Posting.MaxTitleLength) |
| | | 241 | | { |
| | 2 | 242 | | return new ResultError(ErrorCode.ValidationError, $"Title cannot exceed {Posting.MaxTitleLength} characters. |
| | | 243 | | } |
| | | 244 | | |
| | 5528 | 245 | | if (command.Url is not null && command.Url.Length > Posting.MaxUrlLength) |
| | | 246 | | { |
| | 2 | 247 | | return new ResultError(ErrorCode.ValidationError, $"Url cannot exceed {Posting.MaxUrlLength} characters."); |
| | | 248 | | } |
| | | 249 | | |
| | 5526 | 250 | | if (command.Score.HasValue && (command.Score.Value < 0.0m || command.Score.Value > 10.0m)) |
| | | 251 | | { |
| | 2 | 252 | | return new ResultError(ErrorCode.ValidationError, "Score must be between 0.0 and 10.0."); |
| | | 253 | | } |
| | | 254 | | |
| | 5524 | 255 | | if (command.Signals is not null) |
| | | 256 | | { |
| | 208 | 257 | | foreach (var sig in command.Signals) |
| | | 258 | | { |
| | 64 | 259 | | if (sig is null) |
| | | 260 | | { |
| | 0 | 261 | | return new ResultError(ErrorCode.ValidationError, "Signal item cannot be null."); |
| | | 262 | | } |
| | | 263 | | |
| | 64 | 264 | | if (!TrackingEnumExtensions.TryParseSignalType(sig.SignalType, out _)) |
| | | 265 | | { |
| | 6 | 266 | | return new ResultError(ErrorCode.ValidationError, $"Invalid signalType '{sig.SignalType}'."); |
| | | 267 | | } |
| | | 268 | | |
| | 58 | 269 | | if (!string.IsNullOrWhiteSpace(sig.DeadlineDate)) |
| | | 270 | | { |
| | 14 | 271 | | if (!DateOnly.TryParseExact(sig.DeadlineDate.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, Dat |
| | | 272 | | { |
| | 4 | 273 | | return new ResultError(ErrorCode.ValidationError, "Deadline date must be in YYYY-MM-DD format.") |
| | | 274 | | } |
| | | 275 | | } |
| | | 276 | | |
| | 54 | 277 | | if (string.IsNullOrWhiteSpace(sig.Evidence) || sig.Evidence.Trim().Length > 500) |
| | | 278 | | { |
| | 2 | 279 | | return new ResultError(ErrorCode.ValidationError, "Signal evidence is required and cannot exceed 500 |
| | | 280 | | } |
| | | 281 | | } |
| | | 282 | | } |
| | | 283 | | |
| | 5512 | 284 | | return null; |
| | 12 | 285 | | } |
| | | 286 | | } |
| | | 287 | | |
| | | 288 | | public sealed class RecordPostingCommandHandler : ICommandHandler<RecordPostingCommand, PostingRecordResultDto> |
| | | 289 | | { |
| | | 290 | | private static readonly RecordPostingCommandValidator Validator = new(); |
| | | 291 | | private readonly ITrackingTransactionContext _context; |
| | | 292 | | private readonly IUtcClock _clock; |
| | | 293 | | |
| | | 294 | | public RecordPostingCommandHandler(ITrackingTransactionContext context, IUtcClock clock) |
| | | 295 | | { |
| | | 296 | | _context = context ?? throw new ArgumentNullException(nameof(context)); |
| | | 297 | | _clock = clock ?? throw new ArgumentNullException(nameof(clock)); |
| | | 298 | | } |
| | | 299 | | |
| | | 300 | | public async Task<Result<PostingRecordResultDto>> HandleAsync( |
| | | 301 | | RecordPostingCommand command, |
| | | 302 | | CancellationToken cancellationToken = default) |
| | | 303 | | { |
| | | 304 | | ArgumentNullException.ThrowIfNull(command); |
| | | 305 | | |
| | | 306 | | var valError = Validator.Validate(command); |
| | | 307 | | if (valError is not null) |
| | | 308 | | { |
| | | 309 | | return Result<PostingRecordResultDto>.Failure(valError.Value); |
| | | 310 | | } |
| | | 311 | | |
| | | 312 | | var ownerId = string.IsNullOrWhiteSpace(command.OwnerId) |
| | | 313 | | ? OwnerId.Default.Value |
| | | 314 | | : new OwnerId(command.OwnerId).Value; |
| | | 315 | | var now = _clock.UtcNow; |
| | | 316 | | |
| | | 317 | | // 1. Explicit Update Mode |
| | | 318 | | if (command.PostingId.HasValue) |
| | | 319 | | { |
| | | 320 | | return await HandleExplicitUpdateAsync(command, ownerId, now, cancellationToken); |
| | | 321 | | } |
| | | 322 | | |
| | | 323 | | // 2. Ingest / Create Mode |
| | | 324 | | return await HandleIngestOrCreateAsync(command, ownerId, now, cancellationToken); |
| | | 325 | | } |
| | | 326 | | |
| | | 327 | | private async Task<Result<PostingRecordResultDto>> HandleExplicitUpdateAsync( |
| | | 328 | | RecordPostingCommand command, |
| | | 329 | | string ownerId, |
| | | 330 | | DateTimeOffset now, |
| | | 331 | | CancellationToken cancellationToken) |
| | | 332 | | { |
| | | 333 | | var postingResult = await _context.Postings.GetByIdAsync(ownerId, command.PostingId!.Value, cancellationToken); |
| | | 334 | | if (!postingResult.IsSuccess || postingResult.Value is null) |
| | | 335 | | { |
| | | 336 | | return Result<PostingRecordResultDto>.Failure(ErrorCode.NotFound, "Posting not found."); |
| | | 337 | | } |
| | | 338 | | |
| | | 339 | | var posting = postingResult.Value; |
| | | 340 | | if (posting.VersionToken != command.VersionToken!.Value) |
| | | 341 | | { |
| | | 342 | | return Result<PostingRecordResultDto>.Failure(ErrorCode.StaleVersionToken, "Posting version token mismatch o |
| | | 343 | | } |
| | | 344 | | |
| | | 345 | | if (command.CompanyId.HasValue && command.CompanyId.Value != posting.CompanyId) |
| | | 346 | | { |
| | | 347 | | var companyCheck = await _context.Companies.GetByIdAsync(ownerId, command.CompanyId.Value, cancellationToken |
| | | 348 | | if (!companyCheck.IsSuccess || companyCheck.Value is null) |
| | | 349 | | { |
| | | 350 | | return Result<PostingRecordResultDto>.Failure(ErrorCode.ValidationError, $"Target company '{command.Comp |
| | | 351 | | } |
| | | 352 | | } |
| | | 353 | | |
| | | 354 | | SourceKind? sk = null; |
| | | 355 | | if (TrackingEnumExtensions.TryParseSourceKind(command.SourceKind, out var parsedSk)) |
| | | 356 | | { |
| | | 357 | | sk = parsedSk; |
| | | 358 | | } |
| | | 359 | | |
| | | 360 | | RemoteType? rt = null; |
| | | 361 | | if (TrackingEnumExtensions.TryParseRemoteType(command.RemoteType, out var parsedRt)) |
| | | 362 | | { |
| | | 363 | | rt = parsedRt; |
| | | 364 | | } |
| | | 365 | | |
| | | 366 | | CultureLevel? cl = null; |
| | | 367 | | if (TrackingEnumExtensions.TryParseCultureLevel(command.CultureLevel, out var parsedCl)) |
| | | 368 | | { |
| | | 369 | | cl = parsedCl; |
| | | 370 | | } |
| | | 371 | | |
| | | 372 | | Compensation? comp = null; |
| | | 373 | | if (command.CompensationMin.HasValue || command.CompensationMax.HasValue || command.CompensationCurrency is not |
| | | 374 | | { |
| | | 375 | | var existingComp = posting.Compensation; |
| | | 376 | | comp = new Compensation( |
| | | 377 | | command.CompensationMin ?? existingComp?.Min, |
| | | 378 | | command.CompensationMax ?? existingComp?.Max, |
| | | 379 | | command.CompensationCurrency ?? existingComp?.Currency ?? "USD", |
| | | 380 | | command.CompensationText ?? existingComp?.Text); |
| | | 381 | | } |
| | | 382 | | |
| | | 383 | | // Duplicate collapsing if duplicateOfId passed |
| | | 384 | | Guid? collapsedDuplicateOfId = command.DuplicateOfId; |
| | | 385 | | if (collapsedDuplicateOfId.HasValue) |
| | | 386 | | { |
| | | 387 | | if (collapsedDuplicateOfId.Value == posting.Id) |
| | | 388 | | { |
| | | 389 | | return Result<PostingRecordResultDto>.Failure(ErrorCode.ValidationError, "A posting cannot be a duplicat |
| | | 390 | | } |
| | | 391 | | var rootResult = await ResolveRootDuplicateAsync(ownerId, collapsedDuplicateOfId.Value, cancellationToken); |
| | | 392 | | if (!rootResult.IsSuccess) |
| | | 393 | | { |
| | | 394 | | return Result<PostingRecordResultDto>.Failure(rootResult.Error!.Value); |
| | | 395 | | } |
| | | 396 | | collapsedDuplicateOfId = rootResult.Value; |
| | | 397 | | } |
| | | 398 | | |
| | | 399 | | var changedFields = posting.ApplyExplicitUpdate( |
| | | 400 | | command.CompanyId, |
| | | 401 | | command.Title, |
| | | 402 | | command.Url, |
| | | 403 | | sk, |
| | | 404 | | command.AtsTenant, |
| | | 405 | | command.RequisitionId, |
| | | 406 | | command.Location, |
| | | 407 | | rt, |
| | | 408 | | comp, |
| | | 409 | | command.PostedDate, |
| | | 410 | | command.Score, |
| | | 411 | | cl, |
| | | 412 | | command.CultureSummary, |
| | | 413 | | collapsedDuplicateOfId, |
| | | 414 | | command.ScreeningNoteId, |
| | | 415 | | now, |
| | | 416 | | command.CompHighPriority); |
| | | 417 | | |
| | | 418 | | await _context.Postings.UpsertPostingAsync(posting, cancellationToken); |
| | | 419 | | |
| | | 420 | | if (command.Signals is not null && command.Signals.Count > 0) |
| | | 421 | | { |
| | | 422 | | foreach (var sig in command.Signals) |
| | | 423 | | { |
| | | 424 | | if (TrackingEnumExtensions.TryParseSignalType(sig.SignalType, out var st)) |
| | | 425 | | { |
| | | 426 | | var observedAt = !string.IsNullOrWhiteSpace(sig.ObservedAt) && DateTimeOffset.TryParse(sig.ObservedA |
| | | 427 | | ? obs |
| | | 428 | | : now; |
| | | 429 | | var signalEntity = new PostingSignal( |
| | | 430 | | id: Guid.CreateVersion7(), |
| | | 431 | | ownerId: ownerId, |
| | | 432 | | postingId: posting.Id, |
| | | 433 | | signalType: st, |
| | | 434 | | evidence: sig.Evidence, |
| | | 435 | | observedAt: observedAt, |
| | | 436 | | deadlineDate: sig.DeadlineDate); |
| | | 437 | | await _context.Postings.AppendSignalAsync(signalEntity, cancellationToken); |
| | | 438 | | changedFields.Add("signals"); |
| | | 439 | | } |
| | | 440 | | } |
| | | 441 | | } |
| | | 442 | | if (changedFields.Count > 0) |
| | | 443 | | { |
| | | 444 | | var summary = new PostingAuditSummary(posting.Id, changedFields, Timestamp: now); |
| | | 445 | | await AppendAuditAsync(ownerId, command.Actor, AuditOperation.PostingUpdate, posting.Id, posting.VersionToke |
| | | 446 | | } |
| | | 447 | | |
| | | 448 | | return Result<PostingRecordResultDto>.Success(new PostingRecordResultDto( |
| | | 449 | | Status: "updated", |
| | | 450 | | Posting: MapToDto(posting))); |
| | | 451 | | } |
| | | 452 | | |
| | | 453 | | private async Task<Result<PostingRecordResultDto>> HandleIngestOrCreateAsync( |
| | | 454 | | RecordPostingCommand command, |
| | | 455 | | string ownerId, |
| | | 456 | | DateTimeOffset now, |
| | | 457 | | CancellationToken cancellationToken) |
| | | 458 | | { |
| | | 459 | | // 1. Verify company exists |
| | | 460 | | var companyCheck = await _context.Companies.GetByIdAsync(ownerId, command.CompanyId!.Value, cancellationToken); |
| | | 461 | | if (!companyCheck.IsSuccess || companyCheck.Value is null) |
| | | 462 | | { |
| | | 463 | | return Result<PostingRecordResultDto>.Failure(ErrorCode.ValidationError, $"Target company '{command.CompanyI |
| | | 464 | | } |
| | | 465 | | |
| | | 466 | | var trimmedTenant = string.IsNullOrWhiteSpace(command.AtsTenant) ? null : command.AtsTenant.Trim(); |
| | | 467 | | var trimmedReqId = string.IsNullOrWhiteSpace(command.RequisitionId) ? null : command.RequisitionId.Trim(); |
| | | 468 | | if (trimmedReqId is not null && !trimmedReqId.Any(char.IsDigit)) |
| | | 469 | | { |
| | | 470 | | trimmedReqId = null; |
| | | 471 | | } |
| | | 472 | | var normalizedUrl = UrlNormalizer.Normalize(command.Url); |
| | | 473 | | |
| | | 474 | | string? dedupKeyA = (!string.IsNullOrWhiteSpace(trimmedTenant) && !string.IsNullOrWhiteSpace(trimmedReqId)) |
| | | 475 | | ? $"{trimmedTenant}|{trimmedReqId}" |
| | | 476 | | : null; |
| | | 477 | | string? dedupKeyB = normalizedUrl; |
| | | 478 | | string? dedupKeyC = (string.IsNullOrWhiteSpace(trimmedTenant) && !string.IsNullOrWhiteSpace(trimmedReqId)) |
| | | 479 | | ? $"{command.CompanyId.Value:D}|{trimmedReqId}" |
| | | 480 | | : null; |
| | | 481 | | |
| | | 482 | | Posting? matchedPosting = null; |
| | | 483 | | |
| | | 484 | | // Tier A |
| | | 485 | | if (!string.IsNullOrWhiteSpace(dedupKeyA)) |
| | | 486 | | { |
| | | 487 | | var matchA = await _context.Postings.GetByDedupKeyAAsync(ownerId, dedupKeyA, cancellationToken); |
| | | 488 | | if (matchA.IsSuccess && matchA.Value is not null) |
| | | 489 | | { |
| | | 490 | | matchedPosting = matchA.Value; |
| | | 491 | | } |
| | | 492 | | } |
| | | 493 | | |
| | | 494 | | // Tier B |
| | | 495 | | if (matchedPosting is null && !string.IsNullOrWhiteSpace(dedupKeyB)) |
| | | 496 | | { |
| | | 497 | | var matchB = await _context.Postings.GetByDedupKeyBAsync(ownerId, dedupKeyB, cancellationToken); |
| | | 498 | | if (matchB.IsSuccess && matchB.Value is not null) |
| | | 499 | | { |
| | | 500 | | matchedPosting = matchB.Value; |
| | | 501 | | // Upgrade in-place if ATS identifiers newly supplied |
| | | 502 | | if (!string.IsNullOrWhiteSpace(trimmedTenant) || !string.IsNullOrWhiteSpace(trimmedReqId)) |
| | | 503 | | { |
| | | 504 | | matchedPosting.UpgradeIdentifiers(trimmedTenant, trimmedReqId, now); |
| | | 505 | | await _context.Postings.UpsertPostingAsync(matchedPosting, cancellationToken); |
| | | 506 | | } |
| | | 507 | | } |
| | | 508 | | } |
| | | 509 | | |
| | | 510 | | // Tier C |
| | | 511 | | if (matchedPosting is null && !string.IsNullOrWhiteSpace(dedupKeyC)) |
| | | 512 | | { |
| | | 513 | | var matchC = await _context.Postings.GetByDedupKeyCAsync(ownerId, dedupKeyC, cancellationToken); |
| | | 514 | | if (matchC.IsSuccess && matchC.Value is not null) |
| | | 515 | | { |
| | | 516 | | matchedPosting = matchC.Value; |
| | | 517 | | } |
| | | 518 | | } |
| | | 519 | | |
| | | 520 | | // Tier D Advisory check |
| | | 521 | | var normalizedTitle = TitleNormalizer.Normalize(command.Title!); |
| | | 522 | | if (matchedPosting is null) |
| | | 523 | | { |
| | | 524 | | var candidatesResult = await _context.Postings.FindCandidatesByCompanyAndTitleAsync( |
| | | 525 | | ownerId, command.CompanyId.Value, normalizedTitle, cancellationToken); |
| | | 526 | | if (candidatesResult.IsSuccess && candidatesResult.Value is not null && candidatesResult.Value.Count > 0) |
| | | 527 | | { |
| | | 528 | | // Concurrency resolution & Tier D deduplication: |
| | | 529 | | // If any candidate matches a definitive key (Tier A/B/C) or matches by company + title with compatible |
| | | 530 | | foreach (var candidate in candidatesResult.Value) |
| | | 531 | | { |
| | | 532 | | var candPostingRes = await _context.Postings.GetByIdAsync(ownerId, candidate.Id, cancellationToken); |
| | | 533 | | if (candPostingRes.IsSuccess && candPostingRes.Value is not null) |
| | | 534 | | { |
| | | 535 | | var cand = candPostingRes.Value; |
| | | 536 | | var isDefinitiveKeyMatch = (!string.IsNullOrWhiteSpace(dedupKeyA) && cand.DedupKeyA == dedupKeyA |
| | | 537 | | || (!string.IsNullOrWhiteSpace(dedupKeyB) && cand.DedupKeyB == dedupKeyB |
| | | 538 | | || (!string.IsNullOrWhiteSpace(dedupKeyC) && cand.DedupKeyC == dedupKeyC |
| | | 539 | | |
| | | 540 | | // Tier D match: identical company + title if candidate has no req, or incoming has no req, or b |
| | | 541 | | var isTierDMatch = string.IsNullOrWhiteSpace(cand.RequisitionId) |
| | | 542 | | || string.IsNullOrWhiteSpace(trimmedReqId) |
| | | 543 | | || string.Equals(cand.RequisitionId, trimmedReqId, StringComparison.OrdinalIgnor |
| | | 544 | | |
| | | 545 | | if (isDefinitiveKeyMatch || isTierDMatch) |
| | | 546 | | { |
| | | 547 | | return await HandleDedupMatchAsync(cand, command, ownerId, now, cancellationToken); |
| | | 548 | | } |
| | | 549 | | } |
| | | 550 | | } |
| | | 551 | | |
| | | 552 | | return Result<PostingRecordResultDto>.Success(new PostingRecordResultDto( |
| | | 553 | | Status: "possible_duplicate", |
| | | 554 | | Candidates: candidatesResult.Value)); |
| | | 555 | | } |
| | | 556 | | } |
| | | 557 | | |
| | | 558 | | // Handle Dedup Match (Tiers A-C) |
| | | 559 | | if (matchedPosting is not null) |
| | | 560 | | { |
| | | 561 | | return await HandleDedupMatchAsync(matchedPosting, command, ownerId, now, cancellationToken); |
| | | 562 | | } |
| | | 563 | | |
| | | 564 | | // Collapse duplicateOfId if supplied |
| | | 565 | | Guid? collapsedDuplicateOfId = command.DuplicateOfId; |
| | | 566 | | if (collapsedDuplicateOfId.HasValue) |
| | | 567 | | { |
| | | 568 | | var rootResult = await ResolveRootDuplicateAsync(ownerId, collapsedDuplicateOfId.Value, cancellationToken); |
| | | 569 | | if (!rootResult.IsSuccess) |
| | | 570 | | { |
| | | 571 | | return Result<PostingRecordResultDto>.Failure(rootResult.Error!.Value); |
| | | 572 | | } |
| | | 573 | | collapsedDuplicateOfId = rootResult.Value; |
| | | 574 | | } |
| | | 575 | | |
| | | 576 | | // Create New Posting |
| | | 577 | | _ = TrackingEnumExtensions.TryParseSourceKind(command.SourceKind, out var sourceKind); |
| | | 578 | | _ = TrackingEnumExtensions.TryParseRemoteType(command.RemoteType, out var remoteType); |
| | | 579 | | _ = TrackingEnumExtensions.TryParseCultureLevel(command.CultureLevel, out var cultureLevel); |
| | | 580 | | _ = TrackingEnumExtensions.TryParseResurfacePolicy(command.ResurfacePolicy, out var resurfacePolicy); |
| | | 581 | | |
| | | 582 | | Compensation? comp = null; |
| | | 583 | | if (command.CompensationMin.HasValue || command.CompensationMax.HasValue || command.CompensationCurrency is not |
| | | 584 | | { |
| | | 585 | | comp = new Compensation( |
| | | 586 | | command.CompensationMin, |
| | | 587 | | command.CompensationMax, |
| | | 588 | | command.CompensationCurrency ?? "USD", |
| | | 589 | | command.CompensationText); |
| | | 590 | | } |
| | | 591 | | |
| | | 592 | | var newPosting = Posting.Create( |
| | | 593 | | ownerId: ownerId, |
| | | 594 | | companyId: command.CompanyId.Value, |
| | | 595 | | title: command.Title!, |
| | | 596 | | sourceKind: sourceKind, |
| | | 597 | | originalUrl: command.Url, |
| | | 598 | | atsTenant: trimmedTenant, |
| | | 599 | | requisitionId: trimmedReqId, |
| | | 600 | | location: command.Location, |
| | | 601 | | remoteType: remoteType, |
| | | 602 | | compensation: comp, |
| | | 603 | | postedDate: command.PostedDate, |
| | | 604 | | score: command.Score, |
| | | 605 | | cultureLevel: cultureLevel, |
| | | 606 | | cultureSummary: command.CultureSummary, |
| | | 607 | | disposition: PostingDisposition.Lead, |
| | | 608 | | resurfacePolicy: resurfacePolicy, |
| | | 609 | | duplicateOfId: collapsedDuplicateOfId, |
| | | 610 | | screeningNoteId: command.ScreeningNoteId, |
| | | 611 | | now: now, |
| | | 612 | | compHighPriority: command.CompHighPriority); |
| | | 613 | | |
| | | 614 | | await _context.Postings.UpsertPostingAsync(newPosting, cancellationToken); |
| | | 615 | | |
| | | 616 | | // Append initial signals if present |
| | | 617 | | if (command.Signals is not null && command.Signals.Count > 0) |
| | | 618 | | { |
| | | 619 | | foreach (var sig in command.Signals) |
| | | 620 | | { |
| | | 621 | | if (TrackingEnumExtensions.TryParseSignalType(sig.SignalType, out var st)) |
| | | 622 | | { |
| | | 623 | | var observedAt = !string.IsNullOrWhiteSpace(sig.ObservedAt) && DateTimeOffset.TryParse(sig.ObservedA |
| | | 624 | | ? obs |
| | | 625 | | : now; |
| | | 626 | | var signalEntity = new PostingSignal( |
| | | 627 | | id: Guid.CreateVersion7(), |
| | | 628 | | ownerId: ownerId, |
| | | 629 | | postingId: newPosting.Id, |
| | | 630 | | signalType: st, |
| | | 631 | | evidence: sig.Evidence, |
| | | 632 | | observedAt: observedAt, |
| | | 633 | | deadlineDate: sig.DeadlineDate); |
| | | 634 | | await _context.Postings.AppendSignalAsync(signalEntity, cancellationToken); |
| | | 635 | | } |
| | | 636 | | } |
| | | 637 | | } |
| | | 638 | | |
| | | 639 | | var auditSummary = new PostingAuditSummary(newPosting.Id, ["title", "company_id", "disposition"], Timestamp: now |
| | | 640 | | await AppendAuditAsync(ownerId, command.Actor, AuditOperation.PostingCreate, newPosting.Id, newPosting.VersionTo |
| | | 641 | | |
| | | 642 | | return Result<PostingRecordResultDto>.Success(new PostingRecordResultDto( |
| | | 643 | | Status: "created", |
| | | 644 | | Posting: MapToDto(newPosting))); |
| | | 645 | | } |
| | | 646 | | |
| | | 647 | | private async Task<Result<PostingRecordResultDto>> HandleDedupMatchAsync( |
| | | 648 | | Posting stored, |
| | | 649 | | RecordPostingCommand command, |
| | | 650 | | string ownerId, |
| | | 651 | | DateTimeOffset now, |
| | | 652 | | CancellationToken cancellationToken) |
| | | 653 | | { |
| | | 654 | | // 1. If Decided (screened_out, closed, rejected) |
| | | 655 | | if (stored.Disposition == PostingDisposition.ScreenedOut || |
| | | 656 | | stored.Disposition == PostingDisposition.Closed || |
| | | 657 | | stored.Disposition == PostingDisposition.Rejected) |
| | | 658 | | { |
| | | 659 | | var canReopen = stored.ResurfacePolicy == ResurfacePolicy.IfReopened && |
| | | 660 | | stored.Disposition != PostingDisposition.Rejected; |
| | | 661 | | |
| | | 662 | | return Result<PostingRecordResultDto>.Success(new PostingRecordResultDto( |
| | | 663 | | Status: "already_decided", |
| | | 664 | | Posting: MapToDto(stored), |
| | | 665 | | PriorReason: stored.DispositionReason, |
| | | 666 | | CanReopen: canReopen)); |
| | | 667 | | } |
| | | 668 | | |
| | | 669 | | // 2. Active posting: Check for differing supplied fields (Differences list) |
| | | 670 | | var differences = new List<PostingDifference>(); |
| | | 671 | | if (!string.IsNullOrWhiteSpace(command.Location) && command.Location.Trim() != stored.Location) |
| | | 672 | | { |
| | | 673 | | differences.Add(new PostingDifference("location", stored.Location, command.Location.Trim())); |
| | | 674 | | } |
| | | 675 | | |
| | | 676 | | if (!string.IsNullOrWhiteSpace(command.RemoteType) && |
| | | 677 | | Enum.TryParse<RemoteType>(command.RemoteType, true, out var reqRt) && |
| | | 678 | | reqRt != stored.RemoteType) |
| | | 679 | | { |
| | | 680 | | differences.Add(new PostingDifference("remote_type", stored.RemoteType.ToString().ToLowerInvariant(), reqRt. |
| | | 681 | | } |
| | | 682 | | |
| | | 683 | | if (command.CompensationMin.HasValue && command.CompensationMin != stored.Compensation.Min) |
| | | 684 | | { |
| | | 685 | | differences.Add(new PostingDifference("compensation_min", stored.Compensation.Min, command.CompensationMin.V |
| | | 686 | | } |
| | | 687 | | |
| | | 688 | | if (command.CompensationMax.HasValue && command.CompensationMax != stored.Compensation.Max) |
| | | 689 | | { |
| | | 690 | | differences.Add(new PostingDifference("compensation_max", stored.Compensation.Max, command.CompensationMax.V |
| | | 691 | | } |
| | | 692 | | |
| | | 693 | | if (command.CompHighPriority.HasValue && command.CompHighPriority.Value != stored.CompHighPriority) |
| | | 694 | | { |
| | | 695 | | differences.Add(new PostingDifference("comp_high_priority", stored.CompHighPriority, command.CompHighPriorit |
| | | 696 | | } |
| | | 697 | | |
| | | 698 | | // 3. Append any newly observed signals not already recorded today with identical type and evidence |
| | | 699 | | var appendedSignals = false; |
| | | 700 | | if (command.Signals is not null && command.Signals.Count > 0) |
| | | 701 | | { |
| | | 702 | | var existingSignalsResult = await _context.Postings.GetSignalsAsync(ownerId, stored.Id, cancellationToken); |
| | | 703 | | var existingSignals = (existingSignalsResult.IsSuccess && existingSignalsResult.Value is not null) |
| | | 704 | | ? existingSignalsResult.Value |
| | | 705 | | : Array.Empty<PostingSignal>(); |
| | | 706 | | |
| | | 707 | | foreach (var sig in command.Signals) |
| | | 708 | | { |
| | | 709 | | if (TrackingEnumExtensions.TryParseSignalType(sig.SignalType, out var st)) |
| | | 710 | | { |
| | | 711 | | var observedAt = !string.IsNullOrWhiteSpace(sig.ObservedAt) && DateTimeOffset.TryParse(sig.ObservedA |
| | | 712 | | ? obs |
| | | 713 | | : now; |
| | | 714 | | var sigUtcDate = DateOnly.FromDateTime(observedAt.UtcDateTime); |
| | | 715 | | |
| | | 716 | | // Duplicate check: same signalType, same evidence, same UTC day |
| | | 717 | | var alreadyPresent = existingSignals.Any(e => |
| | | 718 | | e.SignalType == st && |
| | | 719 | | string.Equals(e.Evidence?.Trim(), sig.Evidence?.Trim(), StringComparison.Ordinal) && |
| | | 720 | | DateOnly.FromDateTime(e.ObservedAt.UtcDateTime) == sigUtcDate); |
| | | 721 | | |
| | | 722 | | if (!alreadyPresent) |
| | | 723 | | { |
| | | 724 | | var signalEntity = new PostingSignal( |
| | | 725 | | id: Guid.CreateVersion7(), |
| | | 726 | | ownerId: ownerId, |
| | | 727 | | postingId: stored.Id, |
| | | 728 | | signalType: st, |
| | | 729 | | evidence: sig.Evidence.Trim(), |
| | | 730 | | observedAt: observedAt, |
| | | 731 | | deadlineDate: sig.DeadlineDate); |
| | | 732 | | await _context.Postings.AppendSignalAsync(signalEntity, cancellationToken); |
| | | 733 | | appendedSignals = true; |
| | | 734 | | } |
| | | 735 | | } |
| | | 736 | | } |
| | | 737 | | |
| | | 738 | | if (appendedSignals) |
| | | 739 | | { |
| | | 740 | | var auditSummary = new PostingAuditSummary(stored.Id, ["signals"], Timestamp: now); |
| | | 741 | | await AppendAuditAsync(ownerId, command.Actor, AuditOperation.PostingSignalAppend, stored.Id, stored.Ver |
| | | 742 | | } |
| | | 743 | | } |
| | | 744 | | |
| | | 745 | | // 4. UTC date comparison for last_verified_at bump |
| | | 746 | | var storedUtcDate = DateOnly.FromDateTime(stored.LastVerifiedAt.UtcDateTime); |
| | | 747 | | var currentUtcDate = DateOnly.FromDateTime(now.UtcDateTime); |
| | | 748 | | |
| | | 749 | | if (storedUtcDate != currentUtcDate) |
| | | 750 | | { |
| | | 751 | | stored.UpdateLastVerified(now); |
| | | 752 | | await _context.Postings.UpsertPostingAsync(stored, cancellationToken); |
| | | 753 | | |
| | | 754 | | var auditSummary = new PostingAuditSummary(stored.Id, ["last_verified_at"], Timestamp: now); |
| | | 755 | | await AppendAuditAsync(ownerId, command.Actor, AuditOperation.PostingVerifiedBump, stored.Id, stored.Version |
| | | 756 | | } |
| | | 757 | | |
| | | 758 | | return Result<PostingRecordResultDto>.Success(new PostingRecordResultDto( |
| | | 759 | | Status: "already_tracked", |
| | | 760 | | Posting: MapToDto(stored), |
| | | 761 | | Differences: differences.Count > 0 ? differences : null)); |
| | | 762 | | } |
| | | 763 | | |
| | | 764 | | private async Task<Result<Guid>> ResolveRootDuplicateAsync(string ownerId, Guid duplicateOfId, CancellationToken can |
| | | 765 | | { |
| | | 766 | | var visited = new HashSet<Guid>(); |
| | | 767 | | var currentId = duplicateOfId; |
| | | 768 | | |
| | | 769 | | while (true) |
| | | 770 | | { |
| | | 771 | | if (!visited.Add(currentId)) |
| | | 772 | | { |
| | | 773 | | return Result<Guid>.Failure(ErrorCode.ValidationError, "Circular duplicate reference chain detected."); |
| | | 774 | | } |
| | | 775 | | |
| | | 776 | | var next = await _context.Postings.GetByIdAsync(ownerId, currentId, cancellationToken); |
| | | 777 | | if (!next.IsSuccess || next.Value is null) |
| | | 778 | | { |
| | | 779 | | // Target duplicate doesn't exist or is root |
| | | 780 | | return Result<Guid>.Success(currentId); |
| | | 781 | | } |
| | | 782 | | |
| | | 783 | | if (!next.Value.DuplicateOfId.HasValue) |
| | | 784 | | { |
| | | 785 | | return Result<Guid>.Success(currentId); |
| | | 786 | | } |
| | | 787 | | |
| | | 788 | | currentId = next.Value.DuplicateOfId.Value; |
| | | 789 | | } |
| | | 790 | | } |
| | | 791 | | |
| | | 792 | | private Task AppendAuditAsync( |
| | | 793 | | string ownerId, |
| | | 794 | | string actor, |
| | | 795 | | string operation, |
| | | 796 | | Guid postingId, |
| | | 797 | | Guid versionToken, |
| | | 798 | | PostingAuditSummary summary, |
| | | 799 | | CancellationToken cancellationToken) |
| | | 800 | | { |
| | | 801 | | var isCreate = operation == AuditOperation.PostingCreate; |
| | | 802 | | var details = AuditDetails.ForEntity( |
| | | 803 | | changedFields: summary.ChangedFieldNames, |
| | | 804 | | before: isCreate ? null : new Dictionary<string, object?>(), |
| | | 805 | | after: new Dictionary<string, object?> |
| | | 806 | | { |
| | | 807 | | ["changed_field_count"] = summary.ChangedFieldNames.Count |
| | | 808 | | }); |
| | | 809 | | |
| | | 810 | | var entry = AuditLogEntry.CreateForTracking( |
| | | 811 | | ownerId: ownerId, |
| | | 812 | | actor: actor, |
| | | 813 | | operation: operation, |
| | | 814 | | entityType: "posting", |
| | | 815 | | entityId: postingId, |
| | | 816 | | resultingVersionToken: versionToken, |
| | | 817 | | occurredAtUtc: summary.Timestamp.UtcDateTime, |
| | | 818 | | details: details); |
| | | 819 | | |
| | | 820 | | return _context.AppendAuditEntryAsync(entry, cancellationToken); |
| | | 821 | | } |
| | | 822 | | |
| | | 823 | | private static PostingDto MapToDto(Posting p) => |
| | | 824 | | new( |
| | | 825 | | Id: p.Id, |
| | | 826 | | CompanyId: p.CompanyId, |
| | | 827 | | Title: p.Title, |
| | | 828 | | NormalizedTitle: p.NormalizedTitle, |
| | | 829 | | Disposition: p.Disposition.ToSnakeCase(), |
| | | 830 | | ResurfacePolicy: p.ResurfacePolicy.ToSnakeCase(), |
| | | 831 | | VersionToken: p.VersionToken, |
| | | 832 | | Location: p.Location, |
| | | 833 | | RemoteType: p.RemoteType.ToSnakeCase(), |
| | | 834 | | Score: p.Score, |
| | | 835 | | CultureLevel: p.CultureLevel.ToSnakeCase(), |
| | | 836 | | LastVerifiedAt: p.LastVerifiedAt, |
| | | 837 | | CompHighPriority: p.CompHighPriority); |
| | | 838 | | } |