< Summary

Information
Class: RoleRadar.Application.Tracking.Import.Pipeline.PostingsJsonStep
Assembly: RoleRadar.Application
File(s): /home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Tracking/Import/Pipeline/PostingsJsonStep.cs
Line coverage
88%
Covered lines: 575
Uncovered lines: 72
Coverable lines: 647
Total lines: 856
Line coverage: 88.8%
Branch coverage
75%
Covered branches: 300
Total branches: 400
Branch coverage: 75%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)50%44100%
ExecuteAsync()69.04%31921086.5%
<ExecuteAsync()70.76%17813085.88%
TryParseCompensationRange(...)100%1212100%
ParseCompNumber(...)75%9877.77%
get_Type()100%11100%
ParseGhostSignals(...)84.37%323297.43%
FallbackCultureLevel(...)100%11100%
FallbackRemoteType(...)100%210%

File(s)

/home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Tracking/Import/Pipeline/PostingsJsonStep.cs

#LineLine coverage
 1using System.Globalization;
 2using System.Net;
 3using System.Text.Json;
 4using System.Text.RegularExpressions;
 5using RoleRadar.Application.Abstractions;
 6using RoleRadar.Domain.Audit;
 7using RoleRadar.Domain.Common;
 8using RoleRadar.Domain.Notes;
 9using RoleRadar.Domain.Tracking;
 10
 11namespace RoleRadar.Application.Tracking.Import.Pipeline;
 12
 13public sealed class PostingsJsonStep : ITrackerImportStep
 14{
 15    private const string ImportActor = "cli-import-tracker";
 16    private readonly ITrackingTransactionContext _context;
 17    private readonly CriteriaSeedingStep _criteriaStep;
 18
 7219    public PostingsJsonStep(ITrackingTransactionContext context, CriteriaSeedingStep criteriaStep)
 20    {
 7221        _context = context ?? throw new ArgumentNullException(nameof(context));
 7222        _criteriaStep = criteriaStep ?? throw new ArgumentNullException(nameof(criteriaStep));
 7223    }
 24
 25    public async Task<Result<bool>> ExecuteAsync(TrackerImportContext context, CancellationToken cancellationToken = def
 26    {
 7827        ArgumentNullException.ThrowIfNull(context);
 28
 7829        var filePath = Path.Combine(context.BundleDirectory, "postings.json");
 7830        var recon = context.Summary.GetOrCreateFileReconciliation("postings.json");
 31
 7832        if (!File.Exists(filePath))
 33        {
 034            recon.IsAbsent = true;
 035            return Result<bool>.Success(true);
 36        }
 37
 7838        recon.IsAbsent = false;
 39
 7840        var json = await File.ReadAllTextAsync(filePath, cancellationToken);
 7841        if (string.IsNullOrWhiteSpace(json))
 42        {
 443            recon.RecordErrored();
 444            context.Summary.Errors.Add(new TrackerImportRowError(
 445                "postings.json",
 446                1,
 447                ErrorCode.ValidationError.ToString(),
 448                "File is present but empty."));
 449            return Result<bool>.Failure(ErrorCode.ValidationError, "postings.json is present but empty.");
 50        }
 51
 52        JsonDocument doc;
 53        try
 54        {
 7455            doc = JsonDocument.Parse(json);
 7256        }
 257        catch (JsonException ex)
 58        {
 259            recon.RecordErrored();
 260            context.Summary.Errors.Add(new TrackerImportRowError(
 261                "postings.json",
 262                1,
 263                ErrorCode.ValidationError.ToString(),
 264                "Malformed JSON: " + ex.Message));
 265            return Result<bool>.Failure(ErrorCode.ValidationError, "postings.json contains malformed JSON.");
 66        }
 67
 7268        using (doc)
 69        {
 7270            if (doc.RootElement.ValueKind != JsonValueKind.Object && doc.RootElement.ValueKind != JsonValueKind.Array)
 71            {
 272                recon.RecordErrored();
 273                context.Summary.Errors.Add(new TrackerImportRowError(
 274                    "postings.json",
 275                    1,
 276                    ErrorCode.ValidationError.ToString(),
 277                    "Root must be a JSON object keyed by slug (or JSON array)."));
 278                return Result<bool>.Failure(ErrorCode.ValidationError, "postings.json root must be a JSON object keyed b
 79            }
 80
 81            IEnumerable<(string? Slug, JsonElement Element)> entries;
 7082            if (doc.RootElement.ValueKind == JsonValueKind.Object)
 83            {
 18084                entries = doc.RootElement.EnumerateObject().Select(p => ((string?)TrackerImportTextSanitizer.SanitizePla
 85            }
 86            else
 87            {
 288                entries = doc.RootElement.EnumerateArray().Select(e =>
 289                {
 290                    string? slug = e.TryGetProperty("slug", out var sProp) && sProp.GetString() is { } ss ? TrackerImpor
 291                    return (slug, e);
 292                });
 93            }
 94
 7095            var defaultDate = context.DefaultDate ?? DateOnly.FromDateTime(DateTime.UtcNow);
 7096            var entryOrdinal = 0;
 97
 36898            foreach (var (slug, element) in entries)
 99            {
 114100                cancellationToken.ThrowIfCancellationRequested();
 114101                entryOrdinal++;
 114102                recon.RecordRead();
 103
 4560104                foreach (var def in SourceFieldCatalog.ByFile["postings.json"])
 105                {
 2166106                    var isNonEmpty = false;
 2166107                    if (element.TryGetProperty(def.Field, out var prop) && prop.ValueKind != JsonValueKind.Null && prop.
 108                    {
 810109                        if (prop.ValueKind == JsonValueKind.String)
 110                        {
 692111                            isNonEmpty = !string.IsNullOrWhiteSpace(prop.GetString());
 112                        }
 118113                        else if (prop.ValueKind is JsonValueKind.True or JsonValueKind.False or JsonValueKind.Number)
 114                        {
 118115                            isNonEmpty = true;
 116                        }
 117                    }
 2166118                    context.Summary.RecordFieldRead("postings.json", def.Field, isNonEmpty);
 119                }
 120
 114121                if (element.ValueKind != JsonValueKind.Object)
 122                {
 0123                    context.Summary.Errors.Add(new TrackerImportRowError(
 0124                        "postings.json",
 0125                        entryOrdinal,
 0126                        ErrorCode.ValidationError.ToString(),
 0127                        "Posting entry must be a JSON object"));
 0128                    recon.RecordErrored();
 0129                    continue;
 130                }
 131
 132                try
 133                {
 114134                    var rawTitle = element.TryGetProperty("title", out var titleProp) && titleProp.GetString() is { } ts
 114135                        ? TrackerImportTextSanitizer.SanitizePlainText(ts)?.Trim()
 114136                        : null;
 114137                    var rawCompanyName = element.TryGetProperty("company", out var compProp) && compProp.GetString() is 
 114138                        ? TrackerImportTextSanitizer.SanitizePlainText(cs)?.Trim()
 114139                        : null;
 140
 114141                    if (string.IsNullOrWhiteSpace(rawTitle) || string.IsNullOrWhiteSpace(rawCompanyName))
 142                    {
 4143                        context.Summary.Errors.Add(new TrackerImportRowError(
 4144                            "postings.json",
 4145                            entryOrdinal,
 4146                            ErrorCode.ValidationError.ToString(),
 4147                            "Missing required title or company"));
 4148                        recon.RecordErrored();
 4149                        continue;
 150                    }
 151
 110152                    var title = TrackerImportFieldLimiter.LimitTitle(rawTitle, context.Summary)!;
 110153                    var canonicalName = context.CompanyAliases.TryGetValue(rawCompanyName, out var alias) ? alias : rawC
 110154                    canonicalName = TrackerImportFieldLimiter.LimitCompanyName(canonicalName, context.Summary)!;
 155
 156                    // 2. Parse Culture and CultureLevel
 110157                    string? cultureSummary = null;
 110158                    if (element.TryGetProperty("culture", out var cultProp) && cultProp.GetString() is { } cultStr)
 159                    {
 34160                        var decodedCult = TrackerImportTextSanitizer.SanitizeFreeText(cultStr);
 34161                        cultureSummary = TrackerImportFieldLimiter.LimitCultureSummary(decodedCult, context.Summary);
 162                    }
 163
 110164                    var cultureLevel = CultureLevel.Unknown;
 110165                    if (element.TryGetProperty("cultureLevel", out var cultLvlProp) && cultLvlProp.GetString() is { } cu
 166                    {
 30167                        var decodedCultLvl = TrackerImportTextSanitizer.SanitizePlainText(cultLvlStr);
 30168                        if (!string.IsNullOrWhiteSpace(decodedCultLvl))
 169                        {
 30170                            var s = decodedCultLvl.Trim().ToLowerInvariant().Replace('-', '_').Replace(' ', '_');
 30171                            cultureLevel = s switch
 30172                            {
 16173                                "stable" => CultureLevel.Stable,
 8174                                "moderate" => CultureLevel.Moderate,
 4175                                "high_risk" or "highrisk" => CultureLevel.HighRisk,
 0176                                "unknown" => CultureLevel.Unknown,
 2177                                _ => FallbackCultureLevel(context, cultLvlStr)
 30178                            };
 179                        }
 180                    }
 181
 110182                    var remoteType = RemoteType.Unknown;
 110183                    if (element.TryGetProperty("remoteType", out var remProp) && remProp.GetString() is { } remStr)
 184                    {
 0185                        var decodedRem = TrackerImportTextSanitizer.SanitizePlainText(remStr);
 0186                        if (!string.IsNullOrWhiteSpace(decodedRem))
 187                        {
 0188                            var s = decodedRem.Trim().ToLowerInvariant().Replace('-', '_').Replace(' ', '_');
 0189                            remoteType = s switch
 0190                            {
 0191                                "remote" => RemoteType.Remote,
 0192                                "hybrid" => RemoteType.Hybrid,
 0193                                "onsite" => RemoteType.Onsite,
 0194                                "unknown" => RemoteType.Unknown,
 0195                                _ => FallbackRemoteType(context, remStr)
 0196                            };
 197                        }
 198                    }
 199
 200                    // 3. Parse Score (flag and store empty if out of range, do not clamp)
 110201                    double? score = null;
 110202                    if (element.TryGetProperty("score", out var scoreProp) && scoreProp.TryGetDouble(out var rawScore))
 203                    {
 44204                        if (rawScore is < 0.0 or > 10.0)
 205                        {
 12206                            score = null;
 12207                            context.Summary.DatesFlagged++; // Track out of range score flag
 208                        }
 209                        else
 210                        {
 32211                            score = rawScore;
 212                        }
 213                    }
 214
 215                    // 4. Parse Dates
 110216                    var addedRaw = element.TryGetProperty("added", out var addedProp) && addedProp.GetString() is { } as
 110217                        ? TrackerImportTextSanitizer.SanitizePlainText(as1)?.Trim()
 110218                        : (element.TryGetProperty("first", out var firstProp) && firstProp.GetString() is { } as2 ? Trac
 219
 110220                    var dateOutcome = DateInferenceRule.Resolve(addedRaw, defaultDate);
 172221                    if (dateOutcome.Kind == DateResolutionKind.DefaultedBlank) context.Summary.DatesDefaulted++;
 110222                    if (dateOutcome.Kind is DateResolutionKind.InferredRollback or DateResolutionKind.InferredSameYear) 
 110223                    if (dateOutcome.IsFlagged) context.Summary.DatesFlagged++;
 224
 110225                    var rawCompText = element.TryGetProperty("comp", out var cProp) && cProp.GetString() is { } cp
 110226                        ? TrackerImportTextSanitizer.SanitizePlainText(cp)?.Trim()
 110227                        : null;
 110228                    var compText = TrackerImportFieldLimiter.LimitCompensationText(rawCompText, context.Summary);
 110229                    var (compMin, compMax) = TryParseCompensationRange(compText);
 230
 110231                    bool? compHigh = null;
 110232                    if (element.TryGetProperty("compHigh", out var chProp) &&
 110233                        chProp.ValueKind is JsonValueKind.True or JsonValueKind.False)
 234                    {
 22235                        compHigh = chProp.GetBoolean();
 236                    }
 237
 110238                    var rawReqId = element.TryGetProperty("req_id", out var reqProp) && reqProp.GetString() is { } rs1
 110239                        ? TrackerImportTextSanitizer.SanitizePlainText(rs1)?.Trim()
 110240                        : (element.TryGetProperty("requisitionId", out var reqProp2) && reqProp2.GetString() is { } rs2 
 110241                    var reqId = TrackerImportFieldLimiter.LimitRequisitionId(rawReqId, context.Summary);
 242
 110243                    var rawUrl = element.TryGetProperty("href", out var hrefProp) && hrefProp.GetString() is { } us1
 110244                        ? TrackerImportTextSanitizer.SanitizePlainText(us1)?.Trim()
 110245                        : (element.TryGetProperty("url", out var urlProp) && urlProp.GetString() is { } us2 ? TrackerImp
 110246                    var url = TrackerImportFieldLimiter.LimitUrl(rawUrl, context.Summary);
 247
 110248                    var rawLoc = element.TryGetProperty("loc", out var locProp) && locProp.GetString() is { } ls1
 110249                        ? TrackerImportTextSanitizer.SanitizePlainText(ls1)?.Trim()
 110250                        : (element.TryGetProperty("location", out var locProp2) && locProp2.GetString() is { } ls2 ? Tra
 110251                    var location = TrackerImportFieldLimiter.LimitLocation(rawLoc, context.Summary);
 252
 110253                    var sourceKind = SourceKind.Aggregator;
 110254                    if (element.TryGetProperty("source", out var srcProp) && srcProp.GetString() is { } srcStr &&
 110255                        TrackingEnumExtensions.TryParseSourceKind(TrackerImportTextSanitizer.SanitizePlainText(srcStr)?.
 256                    {
 0257                        sourceKind = parsedSrc;
 258                    }
 259
 110260                    var rawPosted = element.TryGetProperty("posted", out var pProp) && pProp.GetString() is { } ps
 110261                        ? TrackerImportTextSanitizer.SanitizePlainText(ps)?.Trim()
 110262                        : null;
 263
 110264                    var rawNote = element.TryGetProperty("note", out var noteProp) && noteProp.GetString() is { } ns
 110265                        ? TrackerImportTextSanitizer.SanitizeFreeText(ns)?.Trim()
 110266                        : null;
 267
 110268                    var candidateSignals = ParseGhostSignals(element, context);
 269
 270                    // Postings with status "applied" are imported with disposition "scored"
 110271                    var rawStatus = element.TryGetProperty("status", out var stProp) && stProp.GetString() is { } stStr
 110272                        ? TrackerImportTextSanitizer.SanitizePlainText(stStr)?.Trim()
 110273                        : null;
 110274                    var originalWasApplied = string.Equals(rawStatus, "applied", StringComparison.OrdinalIgnoreCase);
 275
 276                    // 1. Resolve or auto-create company, and 2. Save posting atomically inside one transaction per row
 110277                    var autoCreatedCompany = false;
 110278                    var isNewlyCreated = false;
 110279                    var signalsCreatedInRow = 0;
 110280                    var notesCreatedInRow = 0;
 110281                    Company? newCompany = null;
 110282                    Company? updatedCompany = null;
 110283                    Posting? newPosting = null;
 284
 110285                    var parentText = element.TryGetProperty("parent", out var parentProp) && parentProp.GetString() is {
 110286                        ? TrackerImportTextSanitizer.SanitizeFreeText(parStr)?.Trim()
 110287                        : null;
 288
 110289                    var rowResult = await _context.ExecuteInTransactionAsync(async (txCtx, ct) =>
 110290                    {
 110291                        signalsCreatedInRow = 0;
 110292                        notesCreatedInRow = 0;
 110293                        Company? resolvedCompany = null;
 110294                        if (!context.CanonicalCompanies.TryGetValue(canonicalName, out resolvedCompany))
 110295                        {
 58296                            var existing = await txCtx.Companies.GetByNormalizedNameAsync(context.OwnerId, canonicalName
 58297                            if (existing.IsSuccess && existing.Value is not null)
 110298                            {
 16299                                resolvedCompany = existing.Value;
 110300                            }
 110301                            else
 110302                            {
 42303                                string description = string.Empty;
 42304                                if (!string.IsNullOrWhiteSpace(parentText))
 110305                                {
 14306                                    if (parentText.Length <= Company.MaxDescriptionLength)
 110307                                    {
 14308                                        description = parentText;
 110309                                    }
 110310                                    else
 110311                                    {
 0312                                        context.Summary.RecordFieldTruncation("company_description");
 110313                                    }
 110314                                }
 110315
 42316                                resolvedCompany = Company.Create(
 42317                                    ownerId: context.OwnerId,
 42318                                    name: canonicalName,
 42319                                    status: CompanyStatus.Neutral,
 42320                                    description: description);
 110321
 42322                                var saveCompany = await txCtx.Companies.UpsertCompanyAsync(resolvedCompany, ct);
 42323                                if (!saveCompany.IsSuccess)
 110324                                {
 0325                                    return Result<bool>.Failure(saveCompany.Error ?? new ResultError(ErrorCode.Validatio
 110326                                }
 110327
 42328                                var audit = AuditLogEntry.CreateForTracking(
 42329                                    ownerId: context.OwnerId,
 42330                                    actor: ImportActor,
 42331                                    operation: AuditOperation.ImportCompanyCreate,
 42332                                    entityType: "company",
 42333                                    entityId: resolvedCompany.Id,
 42334                                    resultingVersionToken: resolvedCompany.VersionToken,
 42335                                    occurredAtUtc: DateTime.UtcNow,
 42336                                    details: new AuditDetails(
 42337                                        ChangedFields: ["name", "status", "description"],
 42338                                        After: new Dictionary<string, object?>
 42339                                        {
 42340                                            ["name"] = resolvedCompany.Name,
 42341                                            ["status"] = resolvedCompany.Status.ToString(),
 42342                                            ["description"] = resolvedCompany.Description
 42343                                        }));
 42344                                await txCtx.AppendAuditEntryAsync(audit, ct);
 42345                                autoCreatedCompany = true;
 42346                                newCompany = resolvedCompany;
 110347                            }
 110348                        }
 110349
 110350                        if (!autoCreatedCompany && resolvedCompany is not null)
 110351                        {
 68352                            updatedCompany = resolvedCompany;
 68353                            if (!string.IsNullOrWhiteSpace(parentText))
 110354                            {
 18355                                var currentDesc = resolvedCompany.Description;
 18356                                if (string.IsNullOrWhiteSpace(currentDesc))
 110357                                {
 0358                                    if (parentText.Length <= Company.MaxDescriptionLength)
 110359                                    {
 0360                                        resolvedCompany.Update(description: parentText);
 0361                                        var updateRes = await txCtx.Companies.UpsertCompanyAsync(resolvedCompany, ct);
 0362                                        if (!updateRes.IsSuccess)
 110363                                        {
 0364                                            return Result<bool>.Failure(updateRes.Error ?? new ResultError(ErrorCode.Val
 110365                                        }
 110366
 0367                                        var audit = AuditLogEntry.CreateForTracking(
 0368                                            ownerId: context.OwnerId,
 0369                                            actor: ImportActor,
 0370                                            operation: AuditOperation.ImportCompanyUpdate,
 0371                                            entityType: "company",
 0372                                            entityId: resolvedCompany.Id,
 0373                                            resultingVersionToken: resolvedCompany.VersionToken,
 0374                                            occurredAtUtc: DateTime.UtcNow,
 0375                                            details: new AuditDetails(
 0376                                                ChangedFields: ["description"],
 0377                                                After: new Dictionary<string, object?>
 0378                                                {
 0379                                                    ["description"] = resolvedCompany.Description
 0380                                                }));
 0381                                        await txCtx.AppendAuditEntryAsync(audit, ct);
 110382                                    }
 110383                                    else
 110384                                    {
 0385                                        context.Summary.RecordFieldTruncation("company_description");
 110386                                    }
 110387                                }
 18388                                else if (!currentDesc.Contains(parentText, StringComparison.OrdinalIgnoreCase))
 110389                                {
 10390                                    var trimmed = currentDesc.TrimEnd();
 10391                                    var candidate = trimmed.EndsWith(';') || trimmed.EndsWith('.')
 10392                                        ? $"{trimmed} {parentText}"
 10393                                        : $"{trimmed}; {parentText}";
 110394
 10395                                    if (candidate.Length <= Company.MaxDescriptionLength)
 110396                                    {
 8397                                        resolvedCompany.Update(description: candidate);
 8398                                        var updateRes = await txCtx.Companies.UpsertCompanyAsync(resolvedCompany, ct);
 8399                                        if (!updateRes.IsSuccess)
 110400                                        {
 0401                                            return Result<bool>.Failure(updateRes.Error ?? new ResultError(ErrorCode.Val
 110402                                        }
 110403
 8404                                        var audit = AuditLogEntry.CreateForTracking(
 8405                                            ownerId: context.OwnerId,
 8406                                            actor: ImportActor,
 8407                                            operation: AuditOperation.ImportCompanyUpdate,
 8408                                            entityType: "company",
 8409                                            entityId: resolvedCompany.Id,
 8410                                            resultingVersionToken: resolvedCompany.VersionToken,
 8411                                            occurredAtUtc: DateTime.UtcNow,
 8412                                            details: new AuditDetails(
 8413                                                ChangedFields: ["description"],
 8414                                                After: new Dictionary<string, object?>
 8415                                                {
 8416                                                    ["description"] = resolvedCompany.Description
 8417                                                }));
 8418                                        await txCtx.AppendAuditEntryAsync(audit, ct);
 110419                                    }
 110420                                    else
 110421                                    {
 2422                                        context.Summary.RecordFieldTruncation("company_description");
 110423                                    }
 110424                                }
 110425                            }
 110426                        }
 110427
 110428                        // Check existing posting
 110429                        Posting? existingPosting = null;
 110430                        if (!string.IsNullOrWhiteSpace(url))
 110431                        {
 60432                            var normUrl = UrlNormalizer.Normalize(url);
 60433                            if (normUrl is not null)
 110434                            {
 60435                                var byUrlRes = await txCtx.Postings.GetByDedupKeyBAsync(context.OwnerId, normUrl, ct);
 60436                                if (byUrlRes.IsSuccess && byUrlRes.Value is not null)
 110437                                {
 8438                                    existingPosting = byUrlRes.Value;
 110439                                }
 110440                            }
 110441                        }
 110442
 110443                        if (existingPosting is null && !string.IsNullOrWhiteSpace(reqId) && resolvedCompany is not null)
 110444                        {
 2445                            if (context.PostingsByCompanyAndReq.TryGetValue($"{canonicalName}|{reqId}", out var cachedBy
 110446                            {
 0447                                existingPosting = cachedByReq;
 110448                            }
 110449                            else
 110450                            {
 2451                                var dedupC = $"{resolvedCompany.Id:D}|{reqId.Trim()}";
 2452                                var byCRes = await txCtx.Postings.GetByDedupKeyCAsync(context.OwnerId, dedupC, ct);
 2453                                if (byCRes.IsSuccess && byCRes.Value is not null)
 110454                                {
 0455                                    existingPosting = byCRes.Value;
 110456                                }
 110457                            }
 110458                        }
 110459
 110460                        if (existingPosting is null && resolvedCompany is not null)
 110461                        {
 102462                            var normTitle = TitleNormalizer.Normalize(title);
 102463                            if (context.PostingsByCompanyAndTitle.TryGetValue($"{canonicalName}|{normTitle}", out var ca
 110464                            {
 4465                                existingPosting = cached;
 110466                            }
 110467                            else
 110468                            {
 98469                                var candRes = await txCtx.Postings.FindCandidatesByCompanyAndTitleAsync(context.OwnerId,
 98470                                if (candRes.IsSuccess && candRes.Value is { Count: > 0 } candidates)
 110471                                {
 16472                                    var byIdRes = await txCtx.Postings.GetByIdAsync(context.OwnerId, candidates[0].Id, c
 16473                                    if (byIdRes.IsSuccess && byIdRes.Value is not null)
 110474                                    {
 16475                                        existingPosting = byIdRes.Value;
 110476                                    }
 110477                                }
 110478                            }
 110479                        }
 110480
 110481                        if (existingPosting is not null)
 110482                        {
 28483                            newPosting = existingPosting;
 28484                            isNewlyCreated = false;
 110485                        }
 110486                        else
 110487                        {
 82488                            Guid? screeningNoteId = null;
 82489                            if (!string.IsNullOrWhiteSpace(rawNote) && resolvedCompany is not null)
 110490                            {
 24491                                var noteTitle = TrackerImportFieldLimiter.LimitNoteTitle($"Assessment: {canonicalName} -
 24492                                    ?? $"Assessment: {canonicalName} - {title}";
 24493                                var noteBody = TrackerImportFieldLimiter.LimitNoteBody(rawNote, context.Summary) ?? stri
 110494
 24495                                var existingNoteRes = await txCtx.GetNoteIdByTitleAndAreaAsync(context.OwnerId, noteTitl
 24496                                if (existingNoteRes.IsSuccess && existingNoteRes.Value.HasValue)
 110497                                {
 0498                                    screeningNoteId = existingNoteRes.Value.Value;
 110499                                }
 110500                                else
 110501                                {
 24502                                    var noteDateStr = dateOutcome.ResolvedDate.ToString("yyyy-MM-dd", CultureInfo.Invari
 24503                                    var note = Note.Create(
 24504                                        ownerId: context.OwnerId,
 24505                                        title: noteTitle,
 24506                                        body: noteBody,
 24507                                        tags: ["imported"],
 24508                                        area: "job-search",
 24509                                        provenance: new ProvenanceMarker(RoleRadar.Domain.Notes.ProvenanceKind.Stated, n
 24510                                        createdAtUtc: dateOutcome.ResolvedDate.ToDateTime(TimeOnly.MinValue, DateTimeKin
 110511
 24512                                    var saveNote = await txCtx.UpsertNoteAsync(note, ct);
 24513                                    if (!saveNote.IsSuccess)
 110514                                    {
 0515                                        return Result<bool>.Failure(saveNote.Error ?? new ResultError(ErrorCode.Validati
 110516                                    }
 110517
 24518                                    var noteAudit = AuditLogEntry.CreateForImportCreate(
 24519                                        ownerId: context.OwnerId,
 24520                                        actor: ImportActor,
 24521                                        targetNoteId: note.Id,
 24522                                        resultingVersionToken: note.VersionToken,
 24523                                        resolvedDefaultDate: defaultDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCul
 24524                                        occurredAtUtc: DateTime.UtcNow,
 24525                                        afterSummary: AuditContentSummary.FromNote(note));
 24526                                    await txCtx.AppendAuditEntryAsync(noteAudit, ct);
 110527
 24528                                    screeningNoteId = note.Id;
 24529                                    notesCreatedInRow++;
 24530                                }
 24531                            }
 110532
 82533                            var posting = Posting.Create(
 82534                                ownerId: context.OwnerId,
 82535                                companyId: resolvedCompany?.Id ?? Guid.NewGuid(),
 82536                                title: title,
 82537                                sourceKind: sourceKind,
 82538                                originalUrl: url,
 82539                                atsTenant: null,
 82540                                requisitionId: reqId,
 82541                                location: location,
 82542                                remoteType: remoteType,
 82543                                compensation: compText != null ? new Compensation(compMin, compMax, "USD", compText) : n
 82544                                postedDate: rawPosted,
 82545                                score: (decimal?)score,
 82546                                cultureLevel: cultureLevel,
 82547                                cultureSummary: cultureSummary,
 82548                                disposition: PostingDisposition.Scored,
 82549                                screeningNoteId: screeningNoteId,
 82550                                now: dateOutcome.ResolvedDate.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc),
 82551                                compHighPriority: compHigh);
 110552
 82553                            var savePosting = await txCtx.Postings.UpsertPostingAsync(posting, ct);
 82554                            if (!savePosting.IsSuccess)
 110555                            {
 0556                                return Result<bool>.Failure(savePosting.Error ?? new ResultError(ErrorCode.ValidationErr
 110557                            }
 110558
 82559                            var changedFields = new List<string> { "title", "company_id", "disposition" };
 82560                            var afterDetails = new Dictionary<string, object?>
 82561                            {
 82562                                ["title"] = posting.Title,
 82563                                ["disposition"] = posting.Disposition.ToString()
 82564                            };
 82565                            if (!string.IsNullOrWhiteSpace(slug))
 110566                            {
 82567                                changedFields.Add("slug");
 82568                                afterDetails["slug"] = slug;
 110569                            }
 82570                            if (!string.IsNullOrWhiteSpace(rawNote))
 110571                            {
 24572                                changedFields.Add("note");
 24573                                afterDetails["note"] = rawNote;
 110574                            }
 82575                            if (screeningNoteId.HasValue)
 110576                            {
 24577                                changedFields.Add("screening_note_id");
 24578                                afterDetails["screening_note_id"] = screeningNoteId.Value;
 110579                            }
 110580
 82581                            var auditP = AuditLogEntry.CreateForTracking(
 82582                                ownerId: context.OwnerId,
 82583                                actor: ImportActor,
 82584                                operation: AuditOperation.ImportPostingCreate,
 82585                                entityType: "posting",
 82586                                entityId: posting.Id,
 82587                                resultingVersionToken: posting.VersionToken,
 82588                                occurredAtUtc: DateTime.UtcNow,
 82589                                details: new AuditDetails(
 82590                                    ChangedFields: changedFields,
 82591                                    After: afterDetails));
 82592                            await txCtx.AppendAuditEntryAsync(auditP, ct);
 110593
 82594                            newPosting = posting;
 82595                            isNewlyCreated = true;
 82596                        }
 110597
 110598                        if (candidateSignals.Count > 0 && newPosting is not null)
 110599                        {
 40600                            var signalsRes = await txCtx.Postings.GetSignalsAsync(context.OwnerId, newPosting.Id, ct);
 40601                            var existingSignals = signalsRes.IsSuccess && signalsRes.Value is not null
 40602                                ? signalsRes.Value
 40603                                : Array.Empty<PostingSignal>();
 110604
 200605                            foreach (var sig in candidateSignals)
 110606                            {
 60607                                var alreadyPresent = existingSignals.Any(e =>
 92608                                    e.SignalType == sig.Type &&
 92609                                    string.Equals(e.DeadlineDate, sig.DeadlineDate, StringComparison.Ordinal));
 110610
 60611                                if (!alreadyPresent)
 110612                                {
 36613                                    var signalEntity = new PostingSignal(
 36614                                        id: Guid.CreateVersion7(),
 36615                                        ownerId: context.OwnerId,
 36616                                        postingId: newPosting.Id,
 36617                                        signalType: sig.Type,
 36618                                        evidence: sig.Evidence,
 36619                                        observedAt: dateOutcome.ResolvedDate.ToDateTime(TimeOnly.MinValue, DateTimeKind.
 36620                                        deadlineDate: sig.DeadlineDate);
 36621                                    var appendRes = await txCtx.Postings.AppendSignalAsync(signalEntity, ct);
 36622                                    if (!appendRes.IsSuccess)
 110623                                    {
 0624                                        return Result<bool>.Failure(appendRes.Error ?? new ResultError(ErrorCode.Validat
 110625                                    }
 110626
 36627                                    var changed = new List<string> { "signals" };
 36628                                    var afterDetails = new Dictionary<string, object?>
 36629                                    {
 36630                                        ["signal_type"] = sig.Type.ToString()
 36631                                    };
 36632                                    if (sig.DeadlineDate is not null)
 110633                                    {
 6634                                        changed.Add("deadline_date");
 6635                                        afterDetails["deadline_date"] = sig.DeadlineDate;
 110636                                    }
 110637
 36638                                    var signalAudit = AuditLogEntry.CreateForTracking(
 36639                                        ownerId: context.OwnerId,
 36640                                        actor: ImportActor,
 36641                                        operation: AuditOperation.ImportPostingSignalAppend,
 36642                                        entityType: "posting",
 36643                                        entityId: newPosting.Id,
 36644                                        resultingVersionToken: newPosting.VersionToken,
 36645                                        occurredAtUtc: DateTime.UtcNow,
 36646                                        details: new AuditDetails(
 36647                                            ChangedFields: changed,
 36648                                            After: afterDetails));
 36649                                    await txCtx.AppendAuditEntryAsync(signalAudit, ct);
 36650                                    signalsCreatedInRow++;
 110651                                }
 60652                            }
 40653                        }
 110654
 110655                        return Result<bool>.Success(true);
 220656                    }, cancellationToken);
 657
 110658                    if (!rowResult.IsSuccess)
 659                    {
 0660                        context.Summary.Errors.Add(new TrackerImportRowError(
 0661                            "postings.json",
 0662                            entryOrdinal,
 0663                            rowResult.Error?.Code.ToString() ?? ErrorCode.ValidationError.ToString(),
 0664                            rowResult.Error?.Message ?? "Failed to save posting"));
 0665                        recon.RecordErrored();
 0666                        continue;
 667                    }
 668
 110669                    context.Summary.SignalsCreated += signalsCreatedInRow;
 110670                    context.Summary.ScreeningNotesCreated += notesCreatedInRow;
 671
 110672                    if (autoCreatedCompany && newCompany is not null)
 673                    {
 42674                        context.CanonicalCompanies[canonicalName] = newCompany;
 42675                        context.Summary.CompaniesCreated++;
 42676                        context.Summary.AutoCreatedCompanies.Add(canonicalName);
 677                    }
 68678                    else if (updatedCompany is not null)
 679                    {
 68680                        context.CanonicalCompanies[canonicalName] = updatedCompany;
 681                    }
 682
 110683                    if (newPosting is not null)
 684                    {
 110685                        context.IndexPosting(newPosting, canonicalName);
 686
 110687                        if (isNewlyCreated)
 688                        {
 82689                            context.Summary.PostingsCreated++;
 82690                            recon.RecordCreated();
 691
 82692                            if (originalWasApplied)
 693                            {
 34694                                context.Summary.UnclaimedAppliedPostingTitles.Add(newPosting.Title);
 34695                                context.Summary.UnclaimedAppliedPostings++;
 696                            }
 697                        }
 698                        else
 699                        {
 28700                            context.Summary.PostingsUnchanged++;
 28701                            recon.RecordUnchanged();
 702                        }
 703                    }
 110704                }
 0705                catch (Exception ex) when (ex is not OperationCanceledException)
 706                {
 0707                    context.Summary.Errors.Add(new TrackerImportRowError(
 0708                        "postings.json",
 0709                        entryOrdinal,
 0710                        ErrorCode.ValidationError.ToString(),
 0711                        ex.Message));
 0712                    recon.RecordErrored();
 0713                }
 110714            }
 70715        }
 716
 70717        return Result<bool>.Success(true);
 78718    }
 719
 720    public static (decimal? Min, decimal? Max) TryParseCompensationRange(string? text)
 721    {
 248722        if (string.IsNullOrWhiteSpace(text)) return (null, null);
 723
 72724        var match = Regex.Match(text, @"(?:^|[^\d])(?:\$)?\s*(?<min>\d+(?:,\d{3})*(?:\.\d+)?)\s*(?<minUnit>k|m)?\s*(?:-|
 72725        if (match.Success)
 726        {
 10727            var minVal = ParseCompNumber(match.Groups["min"].Value, match.Groups["minUnit"].Value, match.Groups["maxUnit
 10728            var maxVal = ParseCompNumber(match.Groups["max"].Value, match.Groups["maxUnit"].Value, null);
 10729            if (minVal.HasValue && maxVal.HasValue)
 730            {
 10731                return (minVal.Value, maxVal.Value);
 732            }
 733        }
 734
 62735        var singleMatch = Regex.Match(text, @"(?:^|[^\d])(?:\$)?\s*(?<val>\d+(?:,\d{3})*(?:\.\d+)?)\s*(?<unit>k|m)?", Re
 62736        if (singleMatch.Success)
 737        {
 58738            var val = ParseCompNumber(singleMatch.Groups["val"].Value, singleMatch.Groups["unit"].Value, null);
 58739            if (val.HasValue)
 740            {
 58741                return (val.Value, null);
 742            }
 743        }
 744
 4745        return (null, null);
 746    }
 747
 748    private static decimal? ParseCompNumber(string numStr, string unit, string? fallbackUnit)
 749    {
 78750        numStr = numStr.Replace(",", "");
 78751        if (!decimal.TryParse(numStr, NumberStyles.Number, CultureInfo.InvariantCulture, out var num))
 0752            return null;
 753
 78754        var effectiveUnit = !string.IsNullOrEmpty(unit) ? unit : fallbackUnit;
 78755        if (string.Equals(effectiveUnit, "k", StringComparison.OrdinalIgnoreCase))
 22756            num *= 1000m;
 56757        else if (string.Equals(effectiveUnit, "m", StringComparison.OrdinalIgnoreCase))
 0758            num *= 1000000m;
 759
 78760        return num;
 761    }
 762
 242763    private readonly record struct ParsedGhostSignal(SignalType Type, string? DeadlineDate, string Evidence);
 764
 765    private static List<ParsedGhostSignal> ParseGhostSignals(JsonElement element, TrackerImportContext context)
 766    {
 110767        var list = new List<ParsedGhostSignal>();
 110768        if (!element.TryGetProperty("ghost", out var ghostProp))
 769        {
 56770            return list;
 771        }
 772
 54773        if (ghostProp.ValueKind == JsonValueKind.True)
 774        {
 12775            list.Add(new ParsedGhostSignal(SignalType.Phantom, null, "Imported ghost flag"));
 12776            return list;
 777        }
 778
 42779        if (ghostProp.ValueKind == JsonValueKind.False)
 780        {
 14781            return list;
 782        }
 783
 28784        if (ghostProp.ValueKind == JsonValueKind.String)
 785        {
 28786            var raw = TrackerImportTextSanitizer.SanitizePlainText(ghostProp.GetString());
 28787            if (string.IsNullOrWhiteSpace(raw))
 788            {
 0789                return list;
 790            }
 791
 28792            var tokens = raw.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
 28793            var seen = new HashSet<(SignalType, string?)>();
 794
 168795            foreach (var rawToken in tokens)
 796            {
 56797                var token = rawToken.Trim();
 56798                if (string.IsNullOrEmpty(token)) continue;
 799
 56800                if (token.StartsWith("deadline:", StringComparison.OrdinalIgnoreCase))
 801                {
 14802                    var dateStr = token["deadline:".Length..].Trim();
 14803                    if (DateOnly.TryParseExact(dateStr, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None,
 804                    {
 10805                        if (seen.Add((SignalType.Deadline, dateStr)))
 806                        {
 10807                            list.Add(new ParsedGhostSignal(SignalType.Deadline, dateStr, $"Imported ghost token: {token}
 808                        }
 809                    }
 810                    else
 811                    {
 4812                        context.Summary.RecordUnmappedValue("ghost", token);
 813                    }
 4814                    continue;
 815                }
 816
 42817                var lower = token.ToLowerInvariant();
 42818                SignalType? matchedType = lower switch
 42819                {
 10820                    "repost" => SignalType.Repost,
 10821                    "nosalary" => SignalType.NoSalary,
 10822                    "parallel" => SignalType.ParallelPosting,
 4823                    "phantom" => SignalType.Phantom,
 4824                    "gone" => SignalType.Gone,
 4825                    _ => null
 42826                };
 827
 42828                if (matchedType is { } st)
 829                {
 38830                    if (seen.Add((st, null)))
 831                    {
 38832                        list.Add(new ParsedGhostSignal(st, null, $"Imported ghost token: {token}"));
 833                    }
 834                }
 835                else
 836                {
 4837                    context.Summary.RecordUnmappedValue("ghost", token);
 838                }
 839            }
 840        }
 841
 28842        return list;
 843    }
 844
 845    private static CultureLevel FallbackCultureLevel(TrackerImportContext context, string rawValue)
 846    {
 2847        context.Summary.RecordUnmappedValue("culture_level", rawValue);
 2848        return CultureLevel.Unknown;
 849    }
 850
 851    private static RemoteType FallbackRemoteType(TrackerImportContext context, string rawValue)
 852    {
 0853        context.Summary.RecordUnmappedValue("remote_type", rawValue);
 0854        return RemoteType.Unknown;
 855    }
 856}