< Summary

Information
Class: RoleRadar.Application.Tracking.Import.Pipeline.ApplicationsStep
Assembly: RoleRadar.Application
File(s): /home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Tracking/Import/Pipeline/ApplicationsStep.cs
Line coverage
90%
Covered lines: 463
Uncovered lines: 50
Coverable lines: 513
Total lines: 812
Line coverage: 90.2%
Branch coverage
73%
Covered branches: 275
Total branches: 376
Branch coverage: 73.1%
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()61.62%2778670.43%
<ExecuteAsync()100%11100%
<ExecuteAsync()100%22100%
ProcessStandaloneNoteAsync()48.07%535292%
ProcessApplicationAsync()75.66%24922692.3%
TrackDateInference(...)87.5%88100%

File(s)

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

#LineLine coverage
 1using System.Globalization;
 2using System.Net;
 3using RoleRadar.Application.Abstractions;
 4using RoleRadar.Domain.Audit;
 5using RoleRadar.Domain.Common;
 6using RoleRadar.Domain.Notes;
 7using RoleRadar.Domain.Tracking;
 8
 9namespace RoleRadar.Application.Tracking.Import.Pipeline;
 10
 11public sealed class ApplicationsStep : ITrackerImportStep
 12{
 13    private const string ImportActor = "cli-import-tracker";
 14    private readonly ICsvParser _csvParser;
 15    private readonly ITrackingTransactionContext _context;
 16    private readonly Func<int, Task>? _faultInjectionHook;
 17
 6618    public ApplicationsStep(
 6619        ICsvParser csvParser,
 6620        ITrackingTransactionContext context,
 6621        Func<int, Task>? faultInjectionHook = null)
 22    {
 6623        _csvParser = csvParser ?? throw new ArgumentNullException(nameof(csvParser));
 6624        _context = context ?? throw new ArgumentNullException(nameof(context));
 6625        _faultInjectionHook = faultInjectionHook;
 6626    }
 27
 28    public async Task<Result<bool>> ExecuteAsync(TrackerImportContext context, CancellationToken cancellationToken = def
 29    {
 6630        ArgumentNullException.ThrowIfNull(context);
 31
 6632        var filePath = Path.Combine(context.BundleDirectory, "applications.csv");
 6633        var recon = context.Summary.GetOrCreateFileReconciliation("applications.csv");
 34
 6635        if (!File.Exists(filePath))
 36        {
 237            recon.IsAbsent = true;
 238            return Result<bool>.Success(true);
 39        }
 40
 6441        recon.IsAbsent = false;
 42
 6443        var content = await File.ReadAllTextAsync(filePath, cancellationToken);
 6444        if (string.IsNullOrWhiteSpace(content))
 45        {
 246            recon.RecordErrored();
 247            context.Summary.Errors.Add(new TrackerImportRowError(
 248                "applications.csv",
 249                1,
 250                ErrorCode.ValidationError.ToString(),
 251                "File is present but empty."));
 252            return Result<bool>.Failure(ErrorCode.ValidationError, "applications.csv is present but empty.");
 53        }
 54
 6255        using var headerReader = new StringReader(content);
 6256        var headers = _csvParser.ReadHeader(headerReader);
 6257        var headerValidation = CsvHeaderValidator.Validate("applications.csv", headers, CsvHeaderValidator.ApplicationsH
 6258        if (!headerValidation.IsSuccess)
 59        {
 260            recon.RecordErrored();
 261            context.Summary.Errors.Add(new TrackerImportRowError(
 262                "applications.csv",
 263                1,
 264                ErrorCode.ValidationError.ToString(),
 265                headerValidation.Error!.Value.Message));
 266            return Result<bool>.Failure(headerValidation.Error!.Value);
 67        }
 68
 6069        _standaloneNoteOrdinal = 0;
 70
 6071        using var reader = new StringReader(content);
 6072        var defaultDate = context.DefaultDate ?? DateOnly.FromDateTime(DateTime.UtcNow);
 73
 28874        foreach (var row in _csvParser.Read(reader, hasHeader: true))
 75        {
 8476            cancellationToken.ThrowIfCancellationRequested();
 8477            recon.RecordRead();
 78
 285679            foreach (var def in SourceFieldCatalog.ByFile["applications.csv"])
 80            {
 134481                var val = TrackerImportTextSanitizer.SanitizePlainText(row[def.Field])?.Trim();
 134482                context.Summary.RecordFieldRead("applications.csv", def.Field, !string.IsNullOrWhiteSpace(val));
 83            }
 84
 85            try
 86            {
 16887                if (!row.Fields.Any(f => !string.IsNullOrWhiteSpace(f)))
 88                {
 089                    recon.RecordSkipped("empty_row");
 090                    continue;
 91                }
 92
 8493                var decision = row["decision"]?.Trim();
 8494                if (string.Equals(decision, "skip", StringComparison.OrdinalIgnoreCase))
 95                {
 096                    context.Summary.ApplicationsUnchanged++;
 097                    recon.RecordSkipped("decision_skip");
 098                    continue;
 99                }
 100
 84101                if (!string.IsNullOrWhiteSpace(decision))
 102                {
 0103                    context.Summary.Errors.Add(new TrackerImportRowError(
 0104                        "applications.csv",
 0105                        row.LineNumber,
 0106                        ErrorCode.ValidationError.ToString(),
 0107                        $"Invalid decision value '{decision}'. Expected blank or 'skip'."));
 0108                    recon.RecordErrored();
 0109                    continue;
 110                }
 111
 112                // Flag detection for people
 84113                var peopleDetected = row["people_detected"]?.Trim();
 84114                var reviewFlags = row["review_flags"]?.Trim();
 84115                var containsPeopleCol = row["contains_people"]?.Trim();
 84116                var containsPeople = (!string.IsNullOrWhiteSpace(reviewFlags) &&
 84117                                      reviewFlags.Contains("contains_people", StringComparison.OrdinalIgnoreCase)) ||
 84118                                     (!string.IsNullOrWhiteSpace(containsPeopleCol) &&
 84119                                      (containsPeopleCol.Equals("true", StringComparison.OrdinalIgnoreCase) ||
 84120                                       containsPeopleCol.Contains("contains_people", StringComparison.OrdinalIgnoreCase)
 121
 84122                if (!string.IsNullOrWhiteSpace(peopleDetected) || containsPeople)
 123                {
 14124                    var details = !string.IsNullOrWhiteSpace(peopleDetected) ? peopleDetected : "Contains people flagged
 14125                    context.Summary.PeopleDetected.Add($"[applications.csv:{row.LineNumber}] {details}");
 126                }
 127
 84128                var kind = row["kind"]?.Trim();
 129
 130                // 1. Standalone Note branch
 84131                if (string.Equals(kind, "standalone_note", StringComparison.OrdinalIgnoreCase))
 132                {
 28133                    var noteCreated = false;
 28134                    var noteResult = await _context.ExecuteInTransactionAsync(async (txCtx, ct) =>
 28135                    {
 28136                        noteCreated = await ProcessStandaloneNoteAsync(context, row, defaultDate, ct);
 28137                        return Result<bool>.Success(true);
 56138                    }, cancellationToken);
 139
 28140                    if (!noteResult.IsSuccess)
 141                    {
 0142                        context.Summary.Errors.Add(new TrackerImportRowError(
 0143                            "applications.csv",
 0144                            row.LineNumber,
 0145                            noteResult.Error?.Code.ToString() ?? ErrorCode.ValidationError.ToString(),
 0146                            noteResult.Error?.Message ?? "Failed to save note"));
 0147                        recon.RecordErrored();
 148                    }
 28149                    else if (noteCreated)
 150                    {
 20151                        recon.RecordCreated();
 152                    }
 153                    else
 154                    {
 8155                        recon.RecordUnchanged();
 156                    }
 28157                    continue;
 158                }
 159
 160                // 2. Application branch validation
 56161                var rawCompany = TrackerImportTextSanitizer.SanitizePlainText(row["company"])?.Trim();
 56162                var rawTitle = (TrackerImportTextSanitizer.SanitizePlainText(row["title"]) ?? TrackerImportTextSanitizer
 56163                if (string.IsNullOrWhiteSpace(rawCompany) || string.IsNullOrWhiteSpace(rawTitle))
 164                {
 0165                    context.Summary.Errors.Add(new TrackerImportRowError(
 0166                        "applications.csv",
 0167                        row.LineNumber,
 0168                        ErrorCode.ValidationError.ToString(),
 0169                        "Missing required company or title."));
 0170                    recon.RecordErrored();
 0171                    continue;
 172                }
 173
 56174                var appCreated = false;
 56175                var appResult = await _context.ExecuteInTransactionAsync(async (txCtx, ct) =>
 56176                {
 56177                    var res = await ProcessApplicationAsync(context, row, defaultDate, reviewFlags, ct);
 52178                    if (!res.IsSuccess)
 56179                    {
 2180                        return res;
 56181                    }
 50182                    appCreated = res.Value;
 50183                    return Result<bool>.Success(true);
 108184                }, cancellationToken);
 185
 56186                if (!appResult.IsSuccess)
 187                {
 6188                    context.Summary.Errors.Add(new TrackerImportRowError(
 6189                        "applications.csv",
 6190                        row.LineNumber,
 6191                        appResult.Error?.Code.ToString() ?? ErrorCode.ValidationError.ToString(),
 6192                        appResult.Error?.Message ?? "Failed to save application"));
 6193                    recon.RecordErrored();
 194                }
 50195                else if (appCreated)
 196                {
 46197                    recon.RecordCreated();
 198                }
 199                else
 200                {
 4201                    recon.RecordUnchanged();
 202                }
 56203            }
 0204            catch (Exception ex) when (ex is not OperationCanceledException)
 205            {
 0206                context.Summary.Errors.Add(new TrackerImportRowError(
 0207                    "applications.csv",
 0208                    row.LineNumber,
 0209                    ErrorCode.ValidationError.ToString(),
 0210                    ex.Message));
 0211                recon.RecordErrored();
 0212            }
 56213        }
 214
 60215        return Result<bool>.Success(true);
 66216    }
 217
 218    private int _standaloneNoteOrdinal;
 219
 220    private async Task<bool> ProcessStandaloneNoteAsync(
 221        TrackerImportContext context,
 222        ICsvRecord row,
 223        DateOnly defaultDate,
 224        CancellationToken cancellationToken)
 225    {
 28226        _standaloneNoteOrdinal++;
 28227        var company = TrackerImportTextSanitizer.SanitizePlainText(row["company"])?.Trim();
 28228        var title = (TrackerImportTextSanitizer.SanitizePlainText(row["title"]) ?? TrackerImportTextSanitizer.SanitizePl
 28229        var appliedOn = (TrackerImportTextSanitizer.SanitizePlainText(row["applied_on"]) ?? TrackerImportTextSanitizer.S
 28230        var raw = TrackerImportTextSanitizer.SanitizeFreeText(row["raw"])?.Trim();
 28231        var correctedNotes = TrackerImportTextSanitizer.SanitizeFreeText(row["corrected_notes"])?.Trim();
 28232        var notes = TrackerImportTextSanitizer.SanitizeFreeText(row["notes"])?.Trim();
 28233        var rawBody = !string.IsNullOrWhiteSpace(correctedNotes)
 28234            ? correctedNotes
 28235            : (!string.IsNullOrWhiteSpace(notes) ? notes : (!string.IsNullOrWhiteSpace(raw) ? raw : "Standalone note"));
 236
 28237        var body = TrackerImportFieldLimiter.LimitNoteBody(rawBody, context.Summary) ?? "Standalone note";
 238
 28239        var dateOutcome = DateInferenceRule.Resolve(appliedOn, defaultDate);
 28240        TrackDateInference(context, dateOutcome);
 241
 242        string fullTitle;
 28243        if (!string.IsNullOrWhiteSpace(company) && !string.IsNullOrWhiteSpace(title))
 244        {
 16245            fullTitle = $"{company} - {title}";
 246        }
 12247        else if (!string.IsNullOrWhiteSpace(company))
 248        {
 0249            var rawSnippet = !string.IsNullOrWhiteSpace(raw) ? raw : (!string.IsNullOrWhiteSpace(notes) ? notes : "Note"
 0250            var snippet = rawSnippet.Length > 40 ? rawSnippet[..40].Trim() : rawSnippet.Trim();
 0251            fullTitle = $"{company} - Imported note {_standaloneNoteOrdinal}: {snippet}";
 252        }
 12253        else if (!string.IsNullOrWhiteSpace(title))
 254        {
 0255            fullTitle = title;
 256        }
 257        else
 258        {
 12259            var rawSnippet = !string.IsNullOrWhiteSpace(raw) ? raw : (!string.IsNullOrWhiteSpace(notes) ? notes : (!stri
 12260            var snippet = rawSnippet.Length > 40 ? rawSnippet[..40].Trim() : rawSnippet.Trim();
 12261            fullTitle = $"Imported note {_standaloneNoteOrdinal}: {snippet}";
 262        }
 263
 28264        fullTitle = TrackerImportFieldLimiter.LimitNoteTitle(fullTitle, context.Summary) ?? $"Imported note {_standalone
 265
 28266        var existingNoteRes = await _context.NoteExistsAsync(context.OwnerId, fullTitle, "job-search", cancellationToken
 28267        if (existingNoteRes.IsSuccess && existingNoteRes.Value)
 268        {
 8269            return false;
 270        }
 271
 20272        var noteDateStr = dateOutcome.ResolvedDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
 20273        var note = Note.Create(
 20274            ownerId: context.OwnerId,
 20275            title: fullTitle,
 20276            body: body,
 20277            tags: ["tracker-import"],
 20278            area: "job-search",
 20279            provenance: new ProvenanceMarker(RoleRadar.Domain.Notes.ProvenanceKind.Stated, noteDateStr, null),
 20280            createdAtUtc: dateOutcome.ResolvedDate.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc));
 281
 20282        await _context.UpsertNoteAsync(note, cancellationToken);
 283
 20284        var audit = AuditLogEntry.CreateForImportCreate(
 20285            ownerId: context.OwnerId,
 20286            actor: ImportActor,
 20287            targetNoteId: note.Id,
 20288            resultingVersionToken: note.VersionToken,
 20289            resolvedDefaultDate: defaultDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
 20290            occurredAtUtc: DateTime.UtcNow,
 20291            afterSummary: AuditContentSummary.FromNote(note));
 292
 20293        await _context.AppendAuditEntryAsync(audit, cancellationToken);
 20294        context.Summary.StandaloneNotesCreated++;
 20295        return true;
 28296    }
 297
 298    private async Task<Result<bool>> ProcessApplicationAsync(
 299        TrackerImportContext context,
 300        ICsvRecord row,
 301        DateOnly defaultDate,
 302        string? reviewFlags,
 303        CancellationToken cancellationToken)
 304    {
 56305        var rawCompanyName = TrackerImportTextSanitizer.SanitizePlainText(row["company"])?.Trim();
 56306        var rawTitle = (TrackerImportTextSanitizer.SanitizePlainText(row["title"]) ?? TrackerImportTextSanitizer.Sanitiz
 56307        var rawReq = (TrackerImportTextSanitizer.SanitizePlainText(row["req"]) ?? TrackerImportTextSanitizer.SanitizePla
 56308        var appliedOn = (TrackerImportTextSanitizer.SanitizePlainText(row["applied_on"]) ?? TrackerImportTextSanitizer.S
 56309        var rejectedStr = TrackerImportTextSanitizer.SanitizePlainText(row["rejected"])?.Trim();
 56310        var isRejected = false;
 56311        if (!string.IsNullOrWhiteSpace(rejectedStr))
 312        {
 54313            var s = rejectedStr.Trim().ToLowerInvariant();
 54314            if (s is "true" or "yes" or "1" or "t" or "y")
 315            {
 12316                isRejected = true;
 317            }
 42318            else if (s is "false" or "no" or "0" or "f" or "n")
 319            {
 40320                isRejected = false;
 321            }
 322            else
 323            {
 2324                context.Summary.RecordUnmappedValue("rejected", rejectedStr);
 325            }
 326        }
 56327        var rejectedDateMd = TrackerImportTextSanitizer.SanitizePlainText(row["rejected_date_md"])?.Trim();
 328
 56329        var companyName = TrackerImportFieldLimiter.LimitCompanyName(rawCompanyName, context.Summary);
 56330        var title = TrackerImportFieldLimiter.LimitTitle(rawTitle, context.Summary) ?? "Role";
 56331        var req = TrackerImportFieldLimiter.LimitRequisitionId(rawReq, context.Summary);
 332
 333        // Also limit optional free-text inputs for referral, fit, resume_variant
 56334        var referralRaw = TrackerImportTextSanitizer.SanitizePlainText(row["referral"])?.Trim();
 56335        TrackerImportFieldLimiter.LimitReferral(referralRaw, context.Summary);
 56336        var isReferral = false;
 56337        if (!string.IsNullOrWhiteSpace(referralRaw))
 338        {
 36339            var s = referralRaw.Trim().ToLowerInvariant();
 36340            if (s is "true" or "yes" or "1" or "t" or "y")
 341            {
 10342                isReferral = true;
 343            }
 26344            else if (s is "false" or "no" or "0" or "f" or "n")
 345            {
 24346                isReferral = false;
 347            }
 348            else
 349            {
 2350                context.Summary.RecordUnmappedValue("referral", referralRaw);
 351            }
 352        }
 353
 56354        var fitRaw = TrackerImportTextSanitizer.SanitizePlainText(row["fit"])?.Trim();
 56355        TrackerImportFieldLimiter.LimitFit(fitRaw, context.Summary);
 56356        decimal? fitScore = null;
 56357        string? fitNoteText = null;
 56358        if (!string.IsNullOrWhiteSpace(fitRaw))
 359        {
 36360            var cleanFit = fitRaw.TrimEnd('.');
 36361            if (decimal.TryParse(cleanFit, NumberStyles.Any, CultureInfo.InvariantCulture, out var parsedScore) &&
 36362                parsedScore is >= 0.0m and <= 10.0m)
 363            {
 6364                fitScore = parsedScore;
 365            }
 366            else
 367            {
 30368                context.Summary.RecordUnmappedValue("fit", fitRaw);
 369            }
 36370            fitNoteText = $"fit: {cleanFit}";
 36371            context.Summary.MappedToEventNotes++;
 372        }
 373
 56374        string? referralNoteText = null;
 56375        if (isReferral)
 376        {
 10377            referralNoteText = "referral=true";
 10378            context.Summary.MappedToEventNotes++;
 379        }
 380
 56381        var rvRaw = TrackerImportFieldLimiter.LimitResumeVariant(TrackerImportTextSanitizer.SanitizePlainText(row["resum
 382        ResumeVariant resumeVariant;
 56383        string? resumeVariantNoteText = null;
 56384        if (string.IsNullOrWhiteSpace(rvRaw))
 385        {
 20386            resumeVariant = ResumeVariant.AsIs;
 20387            resumeVariantNoteText = "resume variant unspecified";
 20388            context.Summary.ResumeVariantsDefaulted++;
 389        }
 36390        else if (TrackingEnumExtensions.TryParseResumeVariant(rvRaw, out var parsedRv))
 391        {
 30392            resumeVariant = parsedRv;
 393        }
 394        else
 395        {
 6396            context.Summary.RecordUnmappedValue("resume_variant", rvRaw);
 6397            resumeVariant = ResumeVariant.AsIs;
 6398            resumeVariantNoteText = "resume variant unspecified";
 6399            context.Summary.ResumeVariantsDefaulted++;
 400        }
 401
 56402        var rawSalary = TrackerImportTextSanitizer.SanitizePlainText(row["desired_salary"])?.Trim();
 56403        DesiredSalary? desiredSalary = null;
 56404        string? unparseableSalaryNote = null;
 56405        if (!string.IsNullOrWhiteSpace(rawSalary))
 406        {
 46407            if (decimal.TryParse(rawSalary, NumberStyles.Any, CultureInfo.InvariantCulture, out var directDecimal) && di
 408            {
 2409                desiredSalary = new DesiredSalary(directDecimal, directDecimal, "USD");
 410            }
 411            else
 412            {
 44413                var (salMin, salMax) = PostingsJsonStep.TryParseCompensationRange(rawSalary);
 44414                if (salMin.HasValue)
 415                {
 40416                    desiredSalary = new DesiredSalary(salMin.Value, salMax ?? salMin.Value, "USD");
 417                }
 418                else
 419                {
 4420                    context.Summary.RecordUnmappedValue("desired_salary", rawSalary);
 4421                    unparseableSalaryNote = $"desired_salary: {rawSalary}";
 422                }
 423            }
 424        }
 425
 56426        var dateOutcome = DateInferenceRule.Resolve(appliedOn, defaultDate);
 56427        TrackDateInference(context, dateOutcome);
 428
 56429        ResolvedDateOutcome? rejectedDateOutcome = null;
 56430        if (isRejected)
 431        {
 12432            var res = DateInferenceRule.Resolve(rejectedDateMd, defaultDate);
 12433            rejectedDateOutcome = res;
 12434            TrackDateInference(context, res);
 435        }
 436
 56437        var isDateStatedFlag = !string.IsNullOrWhiteSpace(reviewFlags) &&
 56438                               reviewFlags.Contains("date_is_stated_not_submitted", StringComparison.OrdinalIgnoreCase);
 439
 56440        var statedFlagText = isDateStatedFlag ? "date_is_stated_not_submitted" : null;
 56441        var rawNotes = TrackerImportTextSanitizer.SanitizeFreeText(!string.IsNullOrWhiteSpace(row["corrected_notes"]) ? 
 392442        var combinedNotes = string.Join("; ", new[] { statedFlagText, fitNoteText, referralNoteText, unparseableSalaryNo
 443
 56444        var canonicalCompany = !string.IsNullOrWhiteSpace(companyName) && context.CompanyAliases.TryGetValue(companyName
 56445            ? alias
 56446            : companyName;
 447
 448        // Resolve matching posting: req first, then company + title (only if candidate has no req or matching req)
 56449        Posting? foundPosting = null;
 56450        if (!string.IsNullOrWhiteSpace(req))
 451        {
 40452            if (!string.IsNullOrWhiteSpace(canonicalCompany) && context.PostingsByCompanyAndReq.TryGetValue($"{canonical
 453            {
 8454                foundPosting = byReq;
 455            }
 32456            else if (!string.IsNullOrWhiteSpace(canonicalCompany))
 457            {
 32458                Company? cObj = null;
 32459                if (context.CanonicalCompanies.TryGetValue(canonicalCompany, out var foundComp))
 460                {
 10461                    cObj = foundComp;
 462                }
 463                else
 464                {
 22465                    var existingCompRes = await _context.Companies.GetByNormalizedNameAsync(context.OwnerId, canonicalCo
 22466                    if (existingCompRes.IsSuccess && existingCompRes.Value is not null)
 467                    {
 0468                        cObj = existingCompRes.Value;
 469                    }
 470                }
 471
 32472                if (cObj is not null)
 473                {
 10474                    var dedupC = $"{cObj.Id:D}|{req.Trim()}";
 10475                    var byCRes = await _context.Postings.GetByDedupKeyCAsync(context.OwnerId, dedupC, cancellationToken)
 10476                    if (byCRes.IsSuccess && byCRes.Value is not null)
 477                    {
 0478                        foundPosting = byCRes.Value;
 479                    }
 480                }
 32481            }
 482        }
 483
 56484        if (foundPosting is null && !string.IsNullOrWhiteSpace(canonicalCompany) && !string.IsNullOrWhiteSpace(title))
 485        {
 48486            var titleKey = $"{canonicalCompany}|{TitleNormalizer.Normalize(title)}";
 48487            if (context.PostingsByCompanyAndTitle.TryGetValue(titleKey, out var byTitle))
 488            {
 24489                if (string.IsNullOrWhiteSpace(byTitle.RequisitionId) || string.Equals(byTitle.RequisitionId, req, String
 490                {
 24491                    foundPosting = byTitle;
 492                }
 493            }
 494            else
 495            {
 24496                Company? cObj = null;
 24497                if (context.CanonicalCompanies.TryGetValue(canonicalCompany, out var foundComp))
 498                {
 2499                    cObj = foundComp;
 500                }
 501                else
 502                {
 22503                    var existingCompRes = await _context.Companies.GetByNormalizedNameAsync(context.OwnerId, canonicalCo
 22504                    if (existingCompRes.IsSuccess && existingCompRes.Value is not null)
 505                    {
 0506                        cObj = existingCompRes.Value;
 507                    }
 508                }
 509
 24510                if (cObj is not null)
 511                {
 2512                    var candRes = await _context.Postings.FindCandidatesByCompanyAndTitleAsync(context.OwnerId, cObj.Id,
 2513                    if (candRes.IsSuccess && candRes.Value is { Count: > 0 } candidates)
 514                    {
 0515                        foreach (var c in candidates)
 516                        {
 0517                            var byIdRes = await _context.Postings.GetByIdAsync(context.OwnerId, c.Id, cancellationToken)
 0518                            if (byIdRes.IsSuccess && byIdRes.Value is not null)
 519                            {
 0520                                if (string.IsNullOrWhiteSpace(byIdRes.Value.RequisitionId) || string.Equals(byIdRes.Valu
 521                                {
 0522                                    foundPosting = byIdRes.Value;
 0523                                    break;
 524                                }
 525                            }
 526                        }
 527                    }
 528                }
 24529            }
 530        }
 531
 532        Guid postingId;
 56533        var appliedDateTime = dateOutcome.ResolvedDate.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
 534
 56535        if (foundPosting is not null)
 536        {
 32537            foundPosting.TransitionToApplied(appliedDateTime);
 32538            if (isRejected)
 539            {
 8540                var rejDateTime = (rejectedDateOutcome?.ResolvedDate ?? dateOutcome.ResolvedDate)
 8541                    .ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
 8542                foundPosting.SynchronizeFromApplicationEvent(PostingDisposition.Rejected, "Rejected", rejDateTime);
 543            }
 544
 32545            await _context.Postings.UpsertPostingAsync(foundPosting, cancellationToken);
 546
 32547            var auditPosting = AuditLogEntry.CreateForTracking(
 32548                ownerId: context.OwnerId,
 32549                actor: ImportActor,
 32550                operation: AuditOperation.ImportPostingTransition,
 32551                entityType: "posting",
 32552                entityId: foundPosting.Id,
 32553                resultingVersionToken: foundPosting.VersionToken,
 32554                occurredAtUtc: DateTime.UtcNow,
 32555                details: new AuditDetails(
 32556                    ChangedFields: ["disposition"],
 32557                    After: new Dictionary<string, object?>
 32558                    {
 32559                        ["disposition"] = foundPosting.Disposition.ToString()
 32560                    }));
 561
 32562            await _context.AppendAuditEntryAsync(auditPosting, cancellationToken);
 32563            context.Summary.PostingsUpdated++;
 32564            context.ClaimedPostingIds.Add(foundPosting.Id);
 565
 32566            if (context.Summary.UnclaimedAppliedPostingTitles.Remove(foundPosting.Title))
 567            {
 18568                context.Summary.UnclaimedAppliedPostings = context.Summary.UnclaimedAppliedPostingTitles.Count;
 569            }
 570
 32571            postingId = foundPosting.Id;
 32572            context.IndexPosting(foundPosting, canonicalCompany);
 573        }
 574        else
 575        {
 576            // Auto-create company and posting if missing
 24577            var companyId = Guid.NewGuid();
 24578            if (!string.IsNullOrWhiteSpace(canonicalCompany))
 579            {
 24580                if (!context.CanonicalCompanies.TryGetValue(canonicalCompany, out var company))
 581                {
 22582                    var existingComp = await _context.Companies.GetByNormalizedNameAsync(context.OwnerId, canonicalCompa
 22583                    if (existingComp.IsSuccess && existingComp.Value is not null)
 584                    {
 0585                        company = existingComp.Value;
 586                    }
 587                    else
 588                    {
 22589                        company = Company.Create(
 22590                            ownerId: context.OwnerId,
 22591                            name: canonicalCompany,
 22592                            status: CompanyStatus.Neutral,
 22593                            description: string.Empty);
 594
 22595                        await _context.Companies.UpsertCompanyAsync(company, cancellationToken);
 596
 22597                        var auditC = AuditLogEntry.CreateForTracking(
 22598                            ownerId: context.OwnerId,
 22599                            actor: ImportActor,
 22600                            operation: AuditOperation.ImportCompanyCreate,
 22601                            entityType: "company",
 22602                            entityId: company.Id,
 22603                            resultingVersionToken: company.VersionToken,
 22604                            occurredAtUtc: DateTime.UtcNow,
 22605                            details: new AuditDetails(
 22606                                ChangedFields: ["name", "status"],
 22607                                After: new Dictionary<string, object?>
 22608                                {
 22609                                    ["name"] = company.Name,
 22610                                    ["status"] = company.Status.ToString()
 22611                                }));
 612
 22613                        await _context.AppendAuditEntryAsync(auditC, cancellationToken);
 22614                        context.Summary.CompaniesCreated++;
 22615                        context.Summary.AutoCreatedCompanies.Add(canonicalCompany);
 616                    }
 617
 22618                    context.CanonicalCompanies[canonicalCompany] = company;
 619                }
 620
 24621                companyId = company.Id;
 24622            }
 623
 24624            var newPosting = Posting.Create(
 24625                ownerId: context.OwnerId,
 24626                companyId: companyId,
 24627                title: title,
 24628                sourceKind: SourceKind.Aggregator,
 24629                originalUrl: null,
 24630                requisitionId: req,
 24631                remoteType: RemoteType.Unknown,
 24632                score: fitScore,
 24633                disposition: isRejected ? PostingDisposition.Rejected : PostingDisposition.Applied,
 24634                dispositionReason: isRejected ? "Rejected" : null,
 24635                now: appliedDateTime);
 636
 24637            await _context.Postings.UpsertPostingAsync(newPosting, cancellationToken);
 638
 24639            var auditP = AuditLogEntry.CreateForTracking(
 24640                ownerId: context.OwnerId,
 24641                actor: ImportActor,
 24642                operation: AuditOperation.ImportPostingCreate,
 24643                entityType: "posting",
 24644                entityId: newPosting.Id,
 24645                resultingVersionToken: newPosting.VersionToken,
 24646                occurredAtUtc: DateTime.UtcNow,
 24647                details: new AuditDetails(
 24648                    ChangedFields: ["title", "disposition"],
 24649                    After: new Dictionary<string, object?>
 24650                    {
 24651                        ["title"] = newPosting.Title,
 24652                        ["disposition"] = newPosting.Disposition.ToString()
 24653                    }));
 654
 24655            await _context.AppendAuditEntryAsync(auditP, cancellationToken);
 24656            context.Summary.PostingsCreated++;
 24657            postingId = newPosting.Id;
 24658            context.IndexPosting(newPosting, canonicalCompany);
 24659        }
 660
 56661        if (!context.ClaimedPostingIdsInRun.Add(postingId))
 662        {
 2663            return Result<bool>.Failure(
 2664                ErrorCode.ValidationError,
 2665                "Conflicting application: multiple application rows resolve to the same posting.");
 666        }
 667
 54668        var submittedDateStr = dateOutcome.ResolvedDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
 54669        var outcome = isRejected ? ApplicationOutcome.Rejected : ApplicationOutcome.Applied;
 54670        var outcomeReasonRaw = isRejected ? (!string.IsNullOrWhiteSpace(combinedNotes) ? combinedNotes : "Rejected") : n
 54671        var outcomeReason = TrackerImportFieldLimiter.LimitOutcomeReason(outcomeReasonRaw, context.Summary);
 672
 54673        var existingAppRes = await _context.Applications.GetByPostingIdAsync(context.OwnerId, postingId, cancellationTok
 54674        if (existingAppRes.IsSuccess && existingAppRes.Value is not null)
 675        {
 4676            var existingApp = existingAppRes.Value;
 4677            var isIdentical =
 4678                string.Equals(existingApp.SubmittedDate, submittedDateStr, StringComparison.Ordinal) &&
 4679                existingApp.ResumeVariant == resumeVariant &&
 4680                existingApp.Outcome == outcome;
 681
 4682            if (isIdentical)
 683            {
 4684                context.Summary.ApplicationsUnchanged++;
 4685                return Result<bool>.Success(false);
 686            }
 687
 0688            return Result<bool>.Failure(
 0689                ErrorCode.ValidationError,
 0690                "Conflicting application: existing application for posting has conflicting data.");
 691        }
 692
 50693        var application = RoleRadar.Domain.Tracking.Application.Create(
 50694            ownerId: context.OwnerId,
 50695            postingId: postingId,
 50696            submittedDate: submittedDateStr,
 50697            resumeVariant: resumeVariant,
 50698            desiredSalary: desiredSalary,
 50699            outcome: outcome,
 50700            outcomeReason: outcomeReason,
 50701            now: appliedDateTime);
 702
 48703        await _context.Applications.UpsertApplicationAsync(application, cancellationToken);
 704
 48705        if (_faultInjectionHook is not null)
 706        {
 6707            await _faultInjectionHook(row.LineNumber);
 708        }
 709
 46710        var auditApp = AuditLogEntry.CreateForTracking(
 46711            ownerId: context.OwnerId,
 46712            actor: ImportActor,
 46713            operation: AuditOperation.ImportApplicationCreate,
 46714            entityType: "application",
 46715            entityId: application.Id,
 46716            resultingVersionToken: application.VersionToken,
 46717            occurredAtUtc: DateTime.UtcNow,
 46718            details: new AuditDetails(
 46719                ChangedFields: ["posting_id", "submitted_date", "outcome"],
 46720                After: new Dictionary<string, object?>
 46721                {
 46722                    ["posting_id"] = application.PostingId.ToString(),
 46723                    ["submitted_date"] = application.SubmittedDate,
 46724                    ["outcome"] = application.Outcome.ToString()
 46725                }));
 726
 46727        await _context.AppendAuditEntryAsync(auditApp, cancellationToken);
 46728        context.Summary.ApplicationsCreated++;
 729
 730        // Add applied event
 46731        var appliedNotes = TrackerImportFieldLimiter.LimitEventNotes(
 46732            !string.IsNullOrWhiteSpace(combinedNotes) ? combinedNotes : null,
 46733            context.Summary);
 734
 46735        var appliedEvent = ApplicationEvent.Create(
 46736            ownerId: context.OwnerId,
 46737            applicationId: application.Id,
 46738            eventDate: submittedDateStr,
 46739            eventType: ApplicationEventType.Applied,
 46740            notes: appliedNotes,
 46741            now: appliedDateTime);
 742
 46743        await _context.Applications.AppendEventAsync(appliedEvent, cancellationToken);
 744
 46745        var auditEvt1 = AuditLogEntry.CreateForTracking(
 46746            ownerId: context.OwnerId,
 46747            actor: ImportActor,
 46748            operation: AuditOperation.ImportApplicationEventAppend,
 46749            entityType: "application_event",
 46750            entityId: appliedEvent.Id,
 46751            resultingVersionToken: application.VersionToken,
 46752            occurredAtUtc: DateTime.UtcNow,
 46753            details: new AuditDetails(
 46754                ChangedFields: ["event_type", "event_date"],
 46755                After: new Dictionary<string, object?>
 46756                {
 46757                    ["event_type"] = appliedEvent.EventType.ToString(),
 46758                    ["event_date"] = appliedEvent.EventDate
 46759                }));
 760
 46761        await _context.AppendAuditEntryAsync(auditEvt1, cancellationToken);
 762
 763        // Add rejected event if rejected
 46764        if (isRejected)
 765        {
 12766            var rejDateStr = (rejectedDateOutcome?.ResolvedDate ?? dateOutcome.ResolvedDate).ToString("yyyy-MM-dd", Cult
 12767            var rejDateTime = (rejectedDateOutcome?.ResolvedDate ?? dateOutcome.ResolvedDate)
 12768                .ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
 769
 12770            var rejectedNotes = TrackerImportFieldLimiter.LimitEventNotes(
 12771                !string.IsNullOrWhiteSpace(rawNotes) ? rawNotes : "Rejected",
 12772                context.Summary);
 773
 12774            var rejectedEvent = ApplicationEvent.Create(
 12775                ownerId: context.OwnerId,
 12776                applicationId: application.Id,
 12777                eventDate: rejDateStr,
 12778                eventType: ApplicationEventType.Rejected,
 12779                notes: rejectedNotes,
 12780                now: rejDateTime);
 781
 12782            await _context.Applications.AppendEventAsync(rejectedEvent, cancellationToken);
 783
 12784            var auditEvt2 = AuditLogEntry.CreateForTracking(
 12785                ownerId: context.OwnerId,
 12786                actor: ImportActor,
 12787                operation: AuditOperation.ImportApplicationEventAppend,
 12788                entityType: "application_event",
 12789                entityId: rejectedEvent.Id,
 12790                resultingVersionToken: application.VersionToken,
 12791                occurredAtUtc: DateTime.UtcNow,
 12792                details: new AuditDetails(
 12793                    ChangedFields: ["event_type", "event_date"],
 12794                    After: new Dictionary<string, object?>
 12795                    {
 12796                        ["event_type"] = rejectedEvent.EventType.ToString(),
 12797                        ["event_date"] = rejectedEvent.EventDate
 12798                    }));
 799
 12800            await _context.AppendAuditEntryAsync(auditEvt2, cancellationToken);
 12801        }
 802
 46803        return Result<bool>.Success(true);
 52804    }
 805
 806    private static void TrackDateInference(TrackerImportContext context, ResolvedDateOutcome outcome)
 807    {
 96808        if (outcome.Kind == DateResolutionKind.DefaultedBlank) context.Summary.DatesDefaulted++;
 102809        if (outcome.Kind is DateResolutionKind.InferredRollback or DateResolutionKind.InferredSameYear) context.Summary.
 102810        if (outcome.IsFlagged) context.Summary.DatesFlagged++;
 96811    }
 812}