< Summary

Information
Class: RoleRadar.Application.Tracking.Import.Pipeline.WatchlistCompaniesStep
Assembly: RoleRadar.Application
File(s): /home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Tracking/Import/Pipeline/WatchlistCompaniesStep.cs
Line coverage
75%
Covered lines: 116
Uncovered lines: 37
Coverable lines: 153
Total lines: 229
Line coverage: 75.8%
Branch coverage
62%
Covered branches: 46
Total branches: 74
Branch coverage: 62.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()60%2386063.3%
<ExecuteAsync()25%4496.29%
MapStatus(...)75%10870%
FallbackTier(...)100%210%

File(s)

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

#LineLine coverage
 1using System.Net;
 2using RoleRadar.Application.Abstractions;
 3using RoleRadar.Domain.Audit;
 4using RoleRadar.Domain.Common;
 5using RoleRadar.Domain.Tracking;
 6
 7namespace RoleRadar.Application.Tracking.Import.Pipeline;
 8
 9public sealed class WatchlistCompaniesStep : ITrackerImportStep
 10{
 11    private const string ImportActor = "cli-import-tracker";
 12    private readonly ICsvParser _csvParser;
 13    private readonly ITrackingTransactionContext _context;
 14
 4815    public WatchlistCompaniesStep(ICsvParser csvParser, ITrackingTransactionContext context)
 16    {
 4817        _csvParser = csvParser ?? throw new ArgumentNullException(nameof(csvParser));
 4818        _context = context ?? throw new ArgumentNullException(nameof(context));
 4819    }
 20
 21    public async Task<Result<bool>> ExecuteAsync(TrackerImportContext context, CancellationToken cancellationToken = def
 22    {
 4823        ArgumentNullException.ThrowIfNull(context);
 24
 4825        var filePath = Path.Combine(context.BundleDirectory, "watchlist-companies.csv");
 4826        var recon = context.Summary.GetOrCreateFileReconciliation("watchlist-companies.csv");
 27
 4828        if (!File.Exists(filePath))
 29        {
 230            recon.IsAbsent = true;
 231            return Result<bool>.Success(true);
 32        }
 33
 4634        recon.IsAbsent = false;
 35
 4636        var content = await File.ReadAllTextAsync(filePath, cancellationToken);
 4637        if (string.IsNullOrWhiteSpace(content))
 38        {
 239            recon.RecordErrored();
 240            context.Summary.Errors.Add(new TrackerImportRowError(
 241                "watchlist-companies.csv",
 242                1,
 243                ErrorCode.ValidationError.ToString(),
 244                "File is present but empty."));
 245            return Result<bool>.Failure(ErrorCode.ValidationError, "watchlist-companies.csv is present but empty.");
 46        }
 47
 4448        using var headerReader = new StringReader(content);
 4449        var headers = _csvParser.ReadHeader(headerReader);
 4450        var headerValidation = CsvHeaderValidator.Validate("watchlist-companies.csv", headers, CsvHeaderValidator.Watchl
 4451        if (!headerValidation.IsSuccess)
 52        {
 053            recon.RecordErrored();
 054            context.Summary.Errors.Add(new TrackerImportRowError(
 055                "watchlist-companies.csv",
 056                1,
 057                ErrorCode.ValidationError.ToString(),
 058                headerValidation.Error!.Value.Message));
 059            return Result<bool>.Failure(headerValidation.Error!.Value);
 60        }
 61
 4462        using var reader = new StringReader(content);
 20863        foreach (var row in _csvParser.Read(reader, hasHeader: true))
 64        {
 6065            cancellationToken.ThrowIfCancellationRequested();
 6066            recon.RecordRead();
 67
 68            try
 69            {
 12070                if (!row.Fields.Any(f => !string.IsNullOrWhiteSpace(f)))
 71                {
 072                    recon.RecordSkipped("empty_row");
 073                    continue;
 74                }
 75
 6076                context.Summary.RecordFieldRead("watchlist-companies.csv", "company", !string.IsNullOrWhiteSpace(row["co
 6077                context.Summary.RecordFieldRead("watchlist-companies.csv", "proposed_status", !string.IsNullOrWhiteSpace
 6078                context.Summary.RecordFieldRead("watchlist-companies.csv", "text", !string.IsNullOrWhiteSpace(row["text"
 6079                context.Summary.RecordFieldRead("watchlist-companies.csv", "decision", !string.IsNullOrWhiteSpace(row["d
 6080                context.Summary.RecordFieldRead("watchlist-companies.csv", "corrected_notes", !string.IsNullOrWhiteSpace
 81
 6082                var companyName = TrackerImportTextSanitizer.SanitizePlainText(row["company"])?.Trim();
 6083                if (string.IsNullOrWhiteSpace(companyName))
 84                {
 85                    // If row has any non-blank field, missing company is a validation error
 086                    context.Summary.Errors.Add(new TrackerImportRowError(
 087                        "watchlist-companies.csv",
 088                        row.LineNumber,
 089                        ErrorCode.ValidationError.ToString(),
 090                        "Missing required 'company' column value."));
 091                    recon.RecordErrored();
 092                    continue;
 93                }
 94
 6095                var decision = TrackerImportTextSanitizer.SanitizePlainText(row["decision"])?.Trim();
 6096                if (string.Equals(decision, "skip", StringComparison.OrdinalIgnoreCase))
 97                {
 498                    context.Summary.CompaniesUnchanged++;
 499                    recon.RecordSkipped("decision_skip");
 4100                    continue;
 101                }
 102
 56103                if (!string.IsNullOrWhiteSpace(decision))
 104                {
 4105                    context.Summary.Errors.Add(new TrackerImportRowError(
 4106                        "watchlist-companies.csv",
 4107                        row.LineNumber,
 4108                        ErrorCode.ValidationError.ToString(),
 4109                        $"Invalid decision value '{decision}'. Expected blank or 'skip'."));
 4110                    recon.RecordErrored();
 4111                    continue;
 112                }
 113
 52114                var proposedStatus = (TrackerImportTextSanitizer.SanitizePlainText(row["proposed_status"]) ?? TrackerImp
 52115                var status = MapStatus(proposedStatus, context);
 116
 52117                var rawNotes = TrackerImportTextSanitizer.SanitizeFreeText(!string.IsNullOrWhiteSpace(row["corrected_not
 52118                    ? row["corrected_notes"]!.Trim()
 52119                    : (!string.IsNullOrWhiteSpace(row["text"])
 52120                        ? row["text"]!.Trim()
 52121                        : row["notes"]?.Trim() ?? string.Empty));
 122
 52123                var canonicalName = context.CompanyAliases.TryGetValue(companyName, out var alias) ? alias : companyName
 124
 125                // Enforce domain limits via shared limiter
 52126                canonicalName = TrackerImportFieldLimiter.LimitRequired(canonicalName, TrackerImportFieldLimiter.Company
 52127                var notes = TrackerImportFieldLimiter.LimitCompanyDescription(rawNotes, context.Summary) ?? string.Empty
 128
 52129                var existing = await _context.Companies.GetByNormalizedNameAsync(context.OwnerId, canonicalName, cancell
 52130                if (existing.IsSuccess && existing.Value is not null)
 131                {
 8132                    var existingCompany = existing.Value;
 8133                    context.CanonicalCompanies[canonicalName] = existingCompany;
 8134                    context.Summary.CompaniesUnchanged++;
 8135                    recon.RecordUnchanged();
 8136                    continue;
 137                }
 138
 44139                Company? createdCompany = null;
 44140                var rowResult = await _context.ExecuteInTransactionAsync(async (txCtx, ct) =>
 44141                {
 44142                    var company = Company.Create(
 44143                        ownerId: context.OwnerId,
 44144                        name: canonicalName,
 44145                        status: status,
 44146                        description: notes);
 44147
 44148                    var upsertResult = await txCtx.Companies.UpsertCompanyAsync(company, ct);
 44149                    if (!upsertResult.IsSuccess)
 44150                    {
 0151                        return Result<bool>.Failure(upsertResult.Error ?? new ResultError(ErrorCode.ValidationError, "Fa
 44152                    }
 44153
 44154                    var auditEntry = AuditLogEntry.CreateForTracking(
 44155                        ownerId: context.OwnerId,
 44156                        actor: ImportActor,
 44157                        operation: AuditOperation.ImportCompanyCreate,
 44158                        entityType: "company",
 44159                        entityId: company.Id,
 44160                        resultingVersionToken: company.VersionToken,
 44161                        occurredAtUtc: DateTime.UtcNow,
 44162                        details: new AuditDetails(
 44163                            ChangedFields: ["name", "status", "description"],
 44164                            After: new Dictionary<string, object?>
 44165                            {
 44166                                ["name"] = company.Name,
 44167                                ["status"] = company.Status.ToString()
 44168                            }));
 44169
 44170                    await txCtx.AppendAuditEntryAsync(auditEntry, ct);
 44171                    createdCompany = company;
 44172                    return Result<bool>.Success(true);
 88173                }, cancellationToken);
 174
 44175                if (!rowResult.IsSuccess)
 176                {
 0177                    context.Summary.Errors.Add(new TrackerImportRowError(
 0178                        "watchlist-companies.csv",
 0179                        row.LineNumber,
 0180                        rowResult.Error?.Code.ToString() ?? ErrorCode.ValidationError.ToString(),
 0181                        rowResult.Error?.Message ?? "Failed to save company"));
 0182                    recon.RecordErrored();
 0183                    continue;
 184                }
 185
 44186                if (createdCompany is not null)
 187                {
 44188                    context.CanonicalCompanies[canonicalName] = createdCompany;
 44189                    context.Summary.CompaniesCreated++;
 44190                    recon.RecordCreated();
 191                }
 44192            }
 0193            catch (Exception ex) when (ex is not OperationCanceledException)
 194            {
 0195                context.Summary.Errors.Add(new TrackerImportRowError(
 0196                    "watchlist-companies.csv",
 0197                    row.LineNumber,
 0198                    ErrorCode.ValidationError.ToString(),
 0199                    ex.Message));
 0200                recon.RecordErrored();
 0201            }
 44202        }
 203
 44204        return Result<bool>.Success(true);
 48205    }
 206
 207    private static CompanyStatus MapStatus(string? tier, TrackerImportContext context)
 208    {
 52209        if (string.IsNullOrWhiteSpace(tier))
 210        {
 0211            return CompanyStatus.Neutral;
 212        }
 213
 52214        return tier.Trim().ToLowerInvariant() switch
 52215        {
 34216            "target" => CompanyStatus.Target,
 8217            "watch" => CompanyStatus.Watch,
 10218            "avoid" => CompanyStatus.Avoid,
 0219            "neutral" => CompanyStatus.Neutral,
 0220            _ => FallbackTier(context, tier)
 52221        };
 222    }
 223
 224    private static CompanyStatus FallbackTier(TrackerImportContext context, string rawTier)
 225    {
 0226        context.Summary.RecordUnmappedValue("tier", rawTier);
 0227        return CompanyStatus.Neutral;
 228    }
 229}