< Summary

Information
Class: RoleRadar.Application.Tracking.Commands.RecordPostingCommandHandler
Assembly: RoleRadar.Application
File(s): /home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Tracking/Commands/RecordPostingCommand.cs
Line coverage
87%
Covered lines: 278
Uncovered lines: 40
Coverable lines: 318
Total lines: 838
Line coverage: 87.4%
Branch coverage
72%
Covered branches: 182
Total branches: 252
Branch coverage: 72.2%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)50%44100%
HandleAsync()100%66100%
HandleExplicitUpdateAsync()30.3%4096657.14%
HandleIngestOrCreateAsync()91.34%10510495.61%
HandleDedupMatchAsync()77.77%555493.65%
ResolveRootDuplicateAsync()62.5%8883.33%
AppendAuditAsync(...)100%22100%
MapToDto(...)100%11100%

File(s)

/home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Tracking/Commands/RecordPostingCommand.cs

#LineLine coverage
 1using System.Globalization;
 2using System.Text.Json;
 3using System.Text.Json.Serialization;
 4using RoleRadar.Application.Abstractions;
 5using RoleRadar.Domain.Audit;
 6using RoleRadar.Domain.Common;
 7using RoleRadar.Domain.Tracking;
 8
 9namespace RoleRadar.Application.Tracking.Commands;
 10
 11public 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))]
 27public sealed record SignalInputDto(
 28    string SignalType,
 29    string Evidence = "reported by agent",
 30    string? ObservedAt = null,
 31    string? DeadlineDate = null);
 32
 33public 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
 127public 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
 135public 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
 162public sealed class RecordPostingCommandValidator : ICommandValidator<RecordPostingCommand>
 163{
 164    public ResultError? Validate(RecordPostingCommand command)
 165    {
 166        ArgumentNullException.ThrowIfNull(command);
 167
 168        var actorError = CommandActor.Validate(command.Actor);
 169        if (actorError is not null)
 170        {
 171            return actorError;
 172        }
 173
 174        // Explicit update mode
 175        if (command.PostingId.HasValue)
 176        {
 177            if (!command.VersionToken.HasValue)
 178            {
 179                return new ResultError(ErrorCode.StaleVersionToken, "VersionToken is required when updating a posting.")
 180            }
 181
 182            if (command.Title is not null && (string.IsNullOrWhiteSpace(command.Title) || command.Title.Trim().Length > 
 183            {
 184                return new ResultError(ErrorCode.ValidationError, $"Title must be 1..{Posting.MaxTitleLength} characters
 185            }
 186
 187            if (command.Url is not null && command.Url.Length > Posting.MaxUrlLength)
 188            {
 189                return new ResultError(ErrorCode.ValidationError, $"Url cannot exceed {Posting.MaxUrlLength} characters.
 190            }
 191
 192            if (command.Score.HasValue && (command.Score.Value < 0.0m || command.Score.Value > 10.0m))
 193            {
 194                return new ResultError(ErrorCode.ValidationError, "Score must be between 0.0 and 10.0.");
 195            }
 196
 197            if (command.Signals is not null)
 198            {
 199                foreach (var sig in command.Signals)
 200                {
 201                    if (sig is null)
 202                    {
 203                        return new ResultError(ErrorCode.ValidationError, "Signal item cannot be null.");
 204                    }
 205
 206                    if (!TrackingEnumExtensions.TryParseSignalType(sig.SignalType, out _))
 207                    {
 208                        return new ResultError(ErrorCode.ValidationError, $"Invalid signalType '{sig.SignalType}'.");
 209                    }
 210
 211                    if (!string.IsNullOrWhiteSpace(sig.DeadlineDate))
 212                    {
 213                        if (!DateOnly.TryParseExact(sig.DeadlineDate.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture,
 214                        {
 215                            return new ResultError(ErrorCode.ValidationError, "Deadline date must be in YYYY-MM-DD forma
 216                        }
 217                    }
 218
 219                    if (string.IsNullOrWhiteSpace(sig.Evidence) || sig.Evidence.Trim().Length > 500)
 220                    {
 221                        return new ResultError(ErrorCode.ValidationError, "Signal evidence is required and cannot exceed
 222                    }
 223                }
 224            }
 225
 226            return null;
 227        }
 228
 229        // Create / Ingest mode
 230        if (!command.CompanyId.HasValue || command.CompanyId.Value == Guid.Empty)
 231        {
 232            return new ResultError(ErrorCode.ValidationError, "CompanyId is required for new posting.");
 233        }
 234
 235        if (string.IsNullOrWhiteSpace(command.Title))
 236        {
 237            return new ResultError(ErrorCode.ValidationError, "Title is required and cannot be blank.");
 238        }
 239
 240        if (command.Title.Trim().Length > Posting.MaxTitleLength)
 241        {
 242            return new ResultError(ErrorCode.ValidationError, $"Title cannot exceed {Posting.MaxTitleLength} characters.
 243        }
 244
 245        if (command.Url is not null && command.Url.Length > Posting.MaxUrlLength)
 246        {
 247            return new ResultError(ErrorCode.ValidationError, $"Url cannot exceed {Posting.MaxUrlLength} characters.");
 248        }
 249
 250        if (command.Score.HasValue && (command.Score.Value < 0.0m || command.Score.Value > 10.0m))
 251        {
 252            return new ResultError(ErrorCode.ValidationError, "Score must be between 0.0 and 10.0.");
 253        }
 254
 255        if (command.Signals is not null)
 256        {
 257            foreach (var sig in command.Signals)
 258            {
 259                if (sig is null)
 260                {
 261                    return new ResultError(ErrorCode.ValidationError, "Signal item cannot be null.");
 262                }
 263
 264                if (!TrackingEnumExtensions.TryParseSignalType(sig.SignalType, out _))
 265                {
 266                    return new ResultError(ErrorCode.ValidationError, $"Invalid signalType '{sig.SignalType}'.");
 267                }
 268
 269                if (!string.IsNullOrWhiteSpace(sig.DeadlineDate))
 270                {
 271                    if (!DateOnly.TryParseExact(sig.DeadlineDate.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, Dat
 272                    {
 273                        return new ResultError(ErrorCode.ValidationError, "Deadline date must be in YYYY-MM-DD format.")
 274                    }
 275                }
 276
 277                if (string.IsNullOrWhiteSpace(sig.Evidence) || sig.Evidence.Trim().Length > 500)
 278                {
 279                    return new ResultError(ErrorCode.ValidationError, "Signal evidence is required and cannot exceed 500
 280                }
 281            }
 282        }
 283
 284        return null;
 285    }
 286}
 287
 288public sealed class RecordPostingCommandHandler : ICommandHandler<RecordPostingCommand, PostingRecordResultDto>
 289{
 36290    private static readonly RecordPostingCommandValidator Validator = new();
 291    private readonly ITrackingTransactionContext _context;
 292    private readonly IUtcClock _clock;
 293
 1550294    public RecordPostingCommandHandler(ITrackingTransactionContext context, IUtcClock clock)
 295    {
 1550296        _context = context ?? throw new ArgumentNullException(nameof(context));
 1550297        _clock = clock ?? throw new ArgumentNullException(nameof(clock));
 1550298    }
 299
 300    public async Task<Result<PostingRecordResultDto>> HandleAsync(
 301        RecordPostingCommand command,
 302        CancellationToken cancellationToken = default)
 303    {
 5360304        ArgumentNullException.ThrowIfNull(command);
 305
 5360306        var valError = Validator.Validate(command);
 5360307        if (valError is not null)
 308        {
 10309            return Result<PostingRecordResultDto>.Failure(valError.Value);
 310        }
 311
 5350312        var ownerId = string.IsNullOrWhiteSpace(command.OwnerId)
 5350313            ? OwnerId.Default.Value
 5350314            : new OwnerId(command.OwnerId).Value;
 5350315        var now = _clock.UtcNow;
 316
 317        // 1. Explicit Update Mode
 5350318        if (command.PostingId.HasValue)
 319        {
 12320            return await HandleExplicitUpdateAsync(command, ownerId, now, cancellationToken);
 321        }
 322
 323        // 2. Ingest / Create Mode
 5338324        return await HandleIngestOrCreateAsync(command, ownerId, now, cancellationToken);
 5328325    }
 326
 327    private async Task<Result<PostingRecordResultDto>> HandleExplicitUpdateAsync(
 328        RecordPostingCommand command,
 329        string ownerId,
 330        DateTimeOffset now,
 331        CancellationToken cancellationToken)
 332    {
 12333        var postingResult = await _context.Postings.GetByIdAsync(ownerId, command.PostingId!.Value, cancellationToken);
 12334        if (!postingResult.IsSuccess || postingResult.Value is null)
 335        {
 0336            return Result<PostingRecordResultDto>.Failure(ErrorCode.NotFound, "Posting not found.");
 337        }
 338
 12339        var posting = postingResult.Value;
 12340        if (posting.VersionToken != command.VersionToken!.Value)
 341        {
 4342            return Result<PostingRecordResultDto>.Failure(ErrorCode.StaleVersionToken, "Posting version token mismatch o
 343        }
 344
 8345        if (command.CompanyId.HasValue && command.CompanyId.Value != posting.CompanyId)
 346        {
 0347            var companyCheck = await _context.Companies.GetByIdAsync(ownerId, command.CompanyId.Value, cancellationToken
 0348            if (!companyCheck.IsSuccess || companyCheck.Value is null)
 349            {
 0350                return Result<PostingRecordResultDto>.Failure(ErrorCode.ValidationError, $"Target company '{command.Comp
 351            }
 352        }
 353
 8354        SourceKind? sk = null;
 8355        if (TrackingEnumExtensions.TryParseSourceKind(command.SourceKind, out var parsedSk))
 356        {
 0357            sk = parsedSk;
 358        }
 359
 8360        RemoteType? rt = null;
 8361        if (TrackingEnumExtensions.TryParseRemoteType(command.RemoteType, out var parsedRt))
 362        {
 2363            rt = parsedRt;
 364        }
 365
 8366        CultureLevel? cl = null;
 8367        if (TrackingEnumExtensions.TryParseCultureLevel(command.CultureLevel, out var parsedCl))
 368        {
 0369            cl = parsedCl;
 370        }
 371
 8372        Compensation? comp = null;
 8373        if (command.CompensationMin.HasValue || command.CompensationMax.HasValue || command.CompensationCurrency is not 
 374        {
 0375            var existingComp = posting.Compensation;
 0376            comp = new Compensation(
 0377                command.CompensationMin ?? existingComp?.Min,
 0378                command.CompensationMax ?? existingComp?.Max,
 0379                command.CompensationCurrency ?? existingComp?.Currency ?? "USD",
 0380                command.CompensationText ?? existingComp?.Text);
 381        }
 382
 383        // Duplicate collapsing if duplicateOfId passed
 8384        Guid? collapsedDuplicateOfId = command.DuplicateOfId;
 8385        if (collapsedDuplicateOfId.HasValue)
 386        {
 0387            if (collapsedDuplicateOfId.Value == posting.Id)
 388            {
 0389                return Result<PostingRecordResultDto>.Failure(ErrorCode.ValidationError, "A posting cannot be a duplicat
 390            }
 0391            var rootResult = await ResolveRootDuplicateAsync(ownerId, collapsedDuplicateOfId.Value, cancellationToken);
 0392            if (!rootResult.IsSuccess)
 393            {
 0394                return Result<PostingRecordResultDto>.Failure(rootResult.Error!.Value);
 395            }
 0396            collapsedDuplicateOfId = rootResult.Value;
 397        }
 398
 8399        var changedFields = posting.ApplyExplicitUpdate(
 8400            command.CompanyId,
 8401            command.Title,
 8402            command.Url,
 8403            sk,
 8404            command.AtsTenant,
 8405            command.RequisitionId,
 8406            command.Location,
 8407            rt,
 8408            comp,
 8409            command.PostedDate,
 8410            command.Score,
 8411            cl,
 8412            command.CultureSummary,
 8413            collapsedDuplicateOfId,
 8414            command.ScreeningNoteId,
 8415            now,
 8416            command.CompHighPriority);
 417
 8418        await _context.Postings.UpsertPostingAsync(posting, cancellationToken);
 419
 8420        if (command.Signals is not null && command.Signals.Count > 0)
 421        {
 0422            foreach (var sig in command.Signals)
 423            {
 0424                if (TrackingEnumExtensions.TryParseSignalType(sig.SignalType, out var st))
 425                {
 0426                    var observedAt = !string.IsNullOrWhiteSpace(sig.ObservedAt) && DateTimeOffset.TryParse(sig.ObservedA
 0427                        ? obs
 0428                        : now;
 0429                    var signalEntity = new PostingSignal(
 0430                        id: Guid.CreateVersion7(),
 0431                        ownerId: ownerId,
 0432                        postingId: posting.Id,
 0433                        signalType: st,
 0434                        evidence: sig.Evidence,
 0435                        observedAt: observedAt,
 0436                        deadlineDate: sig.DeadlineDate);
 0437                    await _context.Postings.AppendSignalAsync(signalEntity, cancellationToken);
 0438                    changedFields.Add("signals");
 439                }
 440            }
 441        }
 8442        if (changedFields.Count > 0)
 443        {
 8444            var summary = new PostingAuditSummary(posting.Id, changedFields, Timestamp: now);
 8445            await AppendAuditAsync(ownerId, command.Actor, AuditOperation.PostingUpdate, posting.Id, posting.VersionToke
 446        }
 447
 8448        return Result<PostingRecordResultDto>.Success(new PostingRecordResultDto(
 8449            Status: "updated",
 8450            Posting: MapToDto(posting)));
 12451    }
 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
 5338460        var companyCheck = await _context.Companies.GetByIdAsync(ownerId, command.CompanyId!.Value, cancellationToken);
 5338461        if (!companyCheck.IsSuccess || companyCheck.Value is null)
 462        {
 2463            return Result<PostingRecordResultDto>.Failure(ErrorCode.ValidationError, $"Target company '{command.CompanyI
 464        }
 465
 5336466        var trimmedTenant = string.IsNullOrWhiteSpace(command.AtsTenant) ? null : command.AtsTenant.Trim();
 5336467        var trimmedReqId = string.IsNullOrWhiteSpace(command.RequisitionId) ? null : command.RequisitionId.Trim();
 5336468        if (trimmedReqId is not null && !trimmedReqId.Any(char.IsDigit))
 469        {
 18470            trimmedReqId = null;
 471        }
 5336472        var normalizedUrl = UrlNormalizer.Normalize(command.Url);
 473
 5336474        string? dedupKeyA = (!string.IsNullOrWhiteSpace(trimmedTenant) && !string.IsNullOrWhiteSpace(trimmedReqId))
 5336475            ? $"{trimmedTenant}|{trimmedReqId}"
 5336476            : null;
 5336477        string? dedupKeyB = normalizedUrl;
 5336478        string? dedupKeyC = (string.IsNullOrWhiteSpace(trimmedTenant) && !string.IsNullOrWhiteSpace(trimmedReqId))
 5336479            ? $"{command.CompanyId.Value:D}|{trimmedReqId}"
 5336480            : null;
 481
 5336482        Posting? matchedPosting = null;
 483
 484        // Tier A
 5336485        if (!string.IsNullOrWhiteSpace(dedupKeyA))
 486        {
 1940487            var matchA = await _context.Postings.GetByDedupKeyAAsync(ownerId, dedupKeyA, cancellationToken);
 1940488            if (matchA.IsSuccess && matchA.Value is not null)
 489            {
 610490                matchedPosting = matchA.Value;
 491            }
 492        }
 493
 494        // Tier B
 5336495        if (matchedPosting is null && !string.IsNullOrWhiteSpace(dedupKeyB))
 496        {
 1540497            var matchB = await _context.Postings.GetByDedupKeyBAsync(ownerId, dedupKeyB, cancellationToken);
 1540498            if (matchB.IsSuccess && matchB.Value is not null)
 499            {
 636500                matchedPosting = matchB.Value;
 501                // Upgrade in-place if ATS identifiers newly supplied
 636502                if (!string.IsNullOrWhiteSpace(trimmedTenant) || !string.IsNullOrWhiteSpace(trimmedReqId))
 503                {
 2504                    matchedPosting.UpgradeIdentifiers(trimmedTenant, trimmedReqId, now);
 2505                    await _context.Postings.UpsertPostingAsync(matchedPosting, cancellationToken);
 506                }
 507            }
 508        }
 509
 510        // Tier C
 5336511        if (matchedPosting is null && !string.IsNullOrWhiteSpace(dedupKeyC))
 512        {
 1814513            var matchC = await _context.Postings.GetByDedupKeyCAsync(ownerId, dedupKeyC, cancellationToken);
 1814514            if (matchC.IsSuccess && matchC.Value is not null)
 515            {
 816516                matchedPosting = matchC.Value;
 517            }
 518        }
 519
 520        // Tier D Advisory check
 5336521        var normalizedTitle = TitleNormalizer.Normalize(command.Title!);
 5336522        if (matchedPosting is null)
 523        {
 3274524            var candidatesResult = await _context.Postings.FindCandidatesByCompanyAndTitleAsync(
 3274525                ownerId, command.CompanyId.Value, normalizedTitle, cancellationToken);
 3274526            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 
 38530                foreach (var candidate in candidatesResult.Value)
 531                {
 12532                    var candPostingRes = await _context.Postings.GetByIdAsync(ownerId, candidate.Id, cancellationToken);
 12533                    if (candPostingRes.IsSuccess && candPostingRes.Value is not null)
 534                    {
 12535                        var cand = candPostingRes.Value;
 12536                        var isDefinitiveKeyMatch = (!string.IsNullOrWhiteSpace(dedupKeyA) && cand.DedupKeyA == dedupKeyA
 12537                                                || (!string.IsNullOrWhiteSpace(dedupKeyB) && cand.DedupKeyB == dedupKeyB
 12538                                                || (!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
 12541                        var isTierDMatch = string.IsNullOrWhiteSpace(cand.RequisitionId)
 12542                                        || string.IsNullOrWhiteSpace(trimmedReqId)
 12543                                        || string.Equals(cand.RequisitionId, trimmedReqId, StringComparison.OrdinalIgnor
 544
 12545                        if (isDefinitiveKeyMatch || isTierDMatch)
 546                        {
 10547                            return await HandleDedupMatchAsync(cand, command, ownerId, now, cancellationToken);
 548                        }
 549                    }
 550                }
 551
 2552                return Result<PostingRecordResultDto>.Success(new PostingRecordResultDto(
 2553                    Status: "possible_duplicate",
 2554                    Candidates: candidatesResult.Value));
 555            }
 3262556        }
 557
 558        // Handle Dedup Match (Tiers A-C)
 5324559        if (matchedPosting is not null)
 560        {
 2062561            return await HandleDedupMatchAsync(matchedPosting, command, ownerId, now, cancellationToken);
 562        }
 563
 564        // Collapse duplicateOfId if supplied
 3262565        Guid? collapsedDuplicateOfId = command.DuplicateOfId;
 3262566        if (collapsedDuplicateOfId.HasValue)
 567        {
 6568            var rootResult = await ResolveRootDuplicateAsync(ownerId, collapsedDuplicateOfId.Value, cancellationToken);
 6569            if (!rootResult.IsSuccess)
 570            {
 0571                return Result<PostingRecordResultDto>.Failure(rootResult.Error!.Value);
 572            }
 6573            collapsedDuplicateOfId = rootResult.Value;
 574        }
 575
 576        // Create New Posting
 3262577        _ = TrackingEnumExtensions.TryParseSourceKind(command.SourceKind, out var sourceKind);
 3262578        _ = TrackingEnumExtensions.TryParseRemoteType(command.RemoteType, out var remoteType);
 3262579        _ = TrackingEnumExtensions.TryParseCultureLevel(command.CultureLevel, out var cultureLevel);
 3262580        _ = TrackingEnumExtensions.TryParseResurfacePolicy(command.ResurfacePolicy, out var resurfacePolicy);
 581
 3262582        Compensation? comp = null;
 3262583        if (command.CompensationMin.HasValue || command.CompensationMax.HasValue || command.CompensationCurrency is not 
 584        {
 6585            comp = new Compensation(
 6586                command.CompensationMin,
 6587                command.CompensationMax,
 6588                command.CompensationCurrency ?? "USD",
 6589                command.CompensationText);
 590        }
 591
 3262592        var newPosting = Posting.Create(
 3262593            ownerId: ownerId,
 3262594            companyId: command.CompanyId.Value,
 3262595            title: command.Title!,
 3262596            sourceKind: sourceKind,
 3262597            originalUrl: command.Url,
 3262598            atsTenant: trimmedTenant,
 3262599            requisitionId: trimmedReqId,
 3262600            location: command.Location,
 3262601            remoteType: remoteType,
 3262602            compensation: comp,
 3262603            postedDate: command.PostedDate,
 3262604            score: command.Score,
 3262605            cultureLevel: cultureLevel,
 3262606            cultureSummary: command.CultureSummary,
 3262607            disposition: PostingDisposition.Lead,
 3262608            resurfacePolicy: resurfacePolicy,
 3262609            duplicateOfId: collapsedDuplicateOfId,
 3262610            screeningNoteId: command.ScreeningNoteId,
 3262611            now: now,
 3262612            compHighPriority: command.CompHighPriority);
 613
 3262614        await _context.Postings.UpsertPostingAsync(newPosting, cancellationToken);
 615
 616        // Append initial signals if present
 3230617        if (command.Signals is not null && command.Signals.Count > 0)
 618        {
 92619            foreach (var sig in command.Signals)
 620            {
 30621                if (TrackingEnumExtensions.TryParseSignalType(sig.SignalType, out var st))
 622                {
 30623                    var observedAt = !string.IsNullOrWhiteSpace(sig.ObservedAt) && DateTimeOffset.TryParse(sig.ObservedA
 30624                        ? obs
 30625                        : now;
 30626                    var signalEntity = new PostingSignal(
 30627                        id: Guid.CreateVersion7(),
 30628                        ownerId: ownerId,
 30629                        postingId: newPosting.Id,
 30630                        signalType: st,
 30631                        evidence: sig.Evidence,
 30632                        observedAt: observedAt,
 30633                        deadlineDate: sig.DeadlineDate);
 30634                    await _context.Postings.AppendSignalAsync(signalEntity, cancellationToken);
 635                }
 636            }
 637        }
 638
 3230639        var auditSummary = new PostingAuditSummary(newPosting.Id, ["title", "company_id", "disposition"], Timestamp: now
 3230640        await AppendAuditAsync(ownerId, command.Actor, AuditOperation.PostingCreate, newPosting.Id, newPosting.VersionTo
 641
 3230642        return Result<PostingRecordResultDto>.Success(new PostingRecordResultDto(
 3230643            Status: "created",
 3230644            Posting: MapToDto(newPosting)));
 5306645    }
 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)
 2072655        if (stored.Disposition == PostingDisposition.ScreenedOut ||
 2072656            stored.Disposition == PostingDisposition.Closed ||
 2072657            stored.Disposition == PostingDisposition.Rejected)
 658        {
 14659            var canReopen = stored.ResurfacePolicy == ResurfacePolicy.IfReopened &&
 14660                            stored.Disposition != PostingDisposition.Rejected;
 661
 14662            return Result<PostingRecordResultDto>.Success(new PostingRecordResultDto(
 14663                Status: "already_decided",
 14664                Posting: MapToDto(stored),
 14665                PriorReason: stored.DispositionReason,
 14666                CanReopen: canReopen));
 667        }
 668
 669        // 2. Active posting: Check for differing supplied fields (Differences list)
 2058670        var differences = new List<PostingDifference>();
 2058671        if (!string.IsNullOrWhiteSpace(command.Location) && command.Location.Trim() != stored.Location)
 672        {
 0673            differences.Add(new PostingDifference("location", stored.Location, command.Location.Trim()));
 674        }
 675
 2058676        if (!string.IsNullOrWhiteSpace(command.RemoteType) &&
 2058677            Enum.TryParse<RemoteType>(command.RemoteType, true, out var reqRt) &&
 2058678            reqRt != stored.RemoteType)
 679        {
 0680            differences.Add(new PostingDifference("remote_type", stored.RemoteType.ToString().ToLowerInvariant(), reqRt.
 681        }
 682
 2058683        if (command.CompensationMin.HasValue && command.CompensationMin != stored.Compensation.Min)
 684        {
 0685            differences.Add(new PostingDifference("compensation_min", stored.Compensation.Min, command.CompensationMin.V
 686        }
 687
 2058688        if (command.CompensationMax.HasValue && command.CompensationMax != stored.Compensation.Max)
 689        {
 0690            differences.Add(new PostingDifference("compensation_max", stored.Compensation.Max, command.CompensationMax.V
 691        }
 692
 2058693        if (command.CompHighPriority.HasValue && command.CompHighPriority.Value != stored.CompHighPriority)
 694        {
 2695            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
 2058699        var appendedSignals = false;
 2058700        if (command.Signals is not null && command.Signals.Count > 0)
 701        {
 10702            var existingSignalsResult = await _context.Postings.GetSignalsAsync(ownerId, stored.Id, cancellationToken);
 10703            var existingSignals = (existingSignalsResult.IsSuccess && existingSignalsResult.Value is not null)
 10704                ? existingSignalsResult.Value
 10705                : Array.Empty<PostingSignal>();
 706
 40707            foreach (var sig in command.Signals)
 708            {
 10709                if (TrackingEnumExtensions.TryParseSignalType(sig.SignalType, out var st))
 710                {
 10711                    var observedAt = !string.IsNullOrWhiteSpace(sig.ObservedAt) && DateTimeOffset.TryParse(sig.ObservedA
 10712                        ? obs
 10713                        : now;
 10714                    var sigUtcDate = DateOnly.FromDateTime(observedAt.UtcDateTime);
 715
 716                    // Duplicate check: same signalType, same evidence, same UTC day
 10717                    var alreadyPresent = existingSignals.Any(e =>
 22718                        e.SignalType == st &&
 22719                        string.Equals(e.Evidence?.Trim(), sig.Evidence?.Trim(), StringComparison.Ordinal) &&
 22720                        DateOnly.FromDateTime(e.ObservedAt.UtcDateTime) == sigUtcDate);
 721
 10722                    if (!alreadyPresent)
 723                    {
 6724                        var signalEntity = new PostingSignal(
 6725                            id: Guid.CreateVersion7(),
 6726                            ownerId: ownerId,
 6727                            postingId: stored.Id,
 6728                            signalType: st,
 6729                            evidence: sig.Evidence.Trim(),
 6730                            observedAt: observedAt,
 6731                            deadlineDate: sig.DeadlineDate);
 6732                        await _context.Postings.AppendSignalAsync(signalEntity, cancellationToken);
 6733                        appendedSignals = true;
 734                    }
 735                }
 736            }
 737
 10738            if (appendedSignals)
 739            {
 6740                var auditSummary = new PostingAuditSummary(stored.Id, ["signals"], Timestamp: now);
 6741                await AppendAuditAsync(ownerId, command.Actor, AuditOperation.PostingSignalAppend, stored.Id, stored.Ver
 742            }
 10743        }
 744
 745        // 4. UTC date comparison for last_verified_at bump
 2058746        var storedUtcDate = DateOnly.FromDateTime(stored.LastVerifiedAt.UtcDateTime);
 2058747        var currentUtcDate = DateOnly.FromDateTime(now.UtcDateTime);
 748
 2058749        if (storedUtcDate != currentUtcDate)
 750        {
 4751            stored.UpdateLastVerified(now);
 4752            await _context.Postings.UpsertPostingAsync(stored, cancellationToken);
 753
 4754            var auditSummary = new PostingAuditSummary(stored.Id, ["last_verified_at"], Timestamp: now);
 4755            await AppendAuditAsync(ownerId, command.Actor, AuditOperation.PostingVerifiedBump, stored.Id, stored.Version
 756        }
 757
 2058758        return Result<PostingRecordResultDto>.Success(new PostingRecordResultDto(
 2058759            Status: "already_tracked",
 2058760            Posting: MapToDto(stored),
 2058761            Differences: differences.Count > 0 ? differences : null));
 2072762    }
 763
 764    private async Task<Result<Guid>> ResolveRootDuplicateAsync(string ownerId, Guid duplicateOfId, CancellationToken can
 765    {
 6766        var visited = new HashSet<Guid>();
 6767        var currentId = duplicateOfId;
 768
 2769        while (true)
 770        {
 8771            if (!visited.Add(currentId))
 772            {
 0773                return Result<Guid>.Failure(ErrorCode.ValidationError, "Circular duplicate reference chain detected.");
 774            }
 775
 8776            var next = await _context.Postings.GetByIdAsync(ownerId, currentId, cancellationToken);
 8777            if (!next.IsSuccess || next.Value is null)
 778            {
 779                // Target duplicate doesn't exist or is root
 0780                return Result<Guid>.Success(currentId);
 781            }
 782
 8783            if (!next.Value.DuplicateOfId.HasValue)
 784            {
 6785                return Result<Guid>.Success(currentId);
 786            }
 787
 2788            currentId = next.Value.DuplicateOfId.Value;
 789        }
 6790    }
 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    {
 3248801        var isCreate = operation == AuditOperation.PostingCreate;
 3248802        var details = AuditDetails.ForEntity(
 3248803            changedFields: summary.ChangedFieldNames,
 3248804            before: isCreate ? null : new Dictionary<string, object?>(),
 3248805            after: new Dictionary<string, object?>
 3248806            {
 3248807                ["changed_field_count"] = summary.ChangedFieldNames.Count
 3248808            });
 809
 3248810        var entry = AuditLogEntry.CreateForTracking(
 3248811            ownerId: ownerId,
 3248812            actor: actor,
 3248813            operation: operation,
 3248814            entityType: "posting",
 3248815            entityId: postingId,
 3248816            resultingVersionToken: versionToken,
 3248817            occurredAtUtc: summary.Timestamp.UtcDateTime,
 3248818            details: details);
 819
 3248820        return _context.AppendAuditEntryAsync(entry, cancellationToken);
 821    }
 822
 823    private static PostingDto MapToDto(Posting p) =>
 5310824        new(
 5310825            Id: p.Id,
 5310826            CompanyId: p.CompanyId,
 5310827            Title: p.Title,
 5310828            NormalizedTitle: p.NormalizedTitle,
 5310829            Disposition: p.Disposition.ToSnakeCase(),
 5310830            ResurfacePolicy: p.ResurfacePolicy.ToSnakeCase(),
 5310831            VersionToken: p.VersionToken,
 5310832            Location: p.Location,
 5310833            RemoteType: p.RemoteType.ToSnakeCase(),
 5310834            Score: p.Score,
 5310835            CultureLevel: p.CultureLevel.ToSnakeCase(),
 5310836            LastVerifiedAt: p.LastVerifiedAt,
 5310837            CompHighPriority: p.CompHighPriority);
 838}