| | | 1 | | using System.Net; |
| | | 2 | | using RoleRadar.Application.Abstractions; |
| | | 3 | | using RoleRadar.Domain.Audit; |
| | | 4 | | using RoleRadar.Domain.Common; |
| | | 5 | | using RoleRadar.Domain.Tracking; |
| | | 6 | | |
| | | 7 | | namespace RoleRadar.Application.Tracking.Import.Pipeline; |
| | | 8 | | |
| | | 9 | | public sealed class WatchlistCompaniesStep : ITrackerImportStep |
| | | 10 | | { |
| | | 11 | | private const string ImportActor = "cli-import-tracker"; |
| | | 12 | | private readonly ICsvParser _csvParser; |
| | | 13 | | private readonly ITrackingTransactionContext _context; |
| | | 14 | | |
| | 48 | 15 | | public WatchlistCompaniesStep(ICsvParser csvParser, ITrackingTransactionContext context) |
| | | 16 | | { |
| | 48 | 17 | | _csvParser = csvParser ?? throw new ArgumentNullException(nameof(csvParser)); |
| | 48 | 18 | | _context = context ?? throw new ArgumentNullException(nameof(context)); |
| | 48 | 19 | | } |
| | | 20 | | |
| | | 21 | | public async Task<Result<bool>> ExecuteAsync(TrackerImportContext context, CancellationToken cancellationToken = def |
| | | 22 | | { |
| | 48 | 23 | | ArgumentNullException.ThrowIfNull(context); |
| | | 24 | | |
| | 48 | 25 | | var filePath = Path.Combine(context.BundleDirectory, "watchlist-companies.csv"); |
| | 48 | 26 | | var recon = context.Summary.GetOrCreateFileReconciliation("watchlist-companies.csv"); |
| | | 27 | | |
| | 48 | 28 | | if (!File.Exists(filePath)) |
| | | 29 | | { |
| | 2 | 30 | | recon.IsAbsent = true; |
| | 2 | 31 | | return Result<bool>.Success(true); |
| | | 32 | | } |
| | | 33 | | |
| | 46 | 34 | | recon.IsAbsent = false; |
| | | 35 | | |
| | 46 | 36 | | var content = await File.ReadAllTextAsync(filePath, cancellationToken); |
| | 46 | 37 | | if (string.IsNullOrWhiteSpace(content)) |
| | | 38 | | { |
| | 2 | 39 | | recon.RecordErrored(); |
| | 2 | 40 | | context.Summary.Errors.Add(new TrackerImportRowError( |
| | 2 | 41 | | "watchlist-companies.csv", |
| | 2 | 42 | | 1, |
| | 2 | 43 | | ErrorCode.ValidationError.ToString(), |
| | 2 | 44 | | "File is present but empty.")); |
| | 2 | 45 | | return Result<bool>.Failure(ErrorCode.ValidationError, "watchlist-companies.csv is present but empty."); |
| | | 46 | | } |
| | | 47 | | |
| | 44 | 48 | | using var headerReader = new StringReader(content); |
| | 44 | 49 | | var headers = _csvParser.ReadHeader(headerReader); |
| | 44 | 50 | | var headerValidation = CsvHeaderValidator.Validate("watchlist-companies.csv", headers, CsvHeaderValidator.Watchl |
| | 44 | 51 | | if (!headerValidation.IsSuccess) |
| | | 52 | | { |
| | 0 | 53 | | recon.RecordErrored(); |
| | 0 | 54 | | context.Summary.Errors.Add(new TrackerImportRowError( |
| | 0 | 55 | | "watchlist-companies.csv", |
| | 0 | 56 | | 1, |
| | 0 | 57 | | ErrorCode.ValidationError.ToString(), |
| | 0 | 58 | | headerValidation.Error!.Value.Message)); |
| | 0 | 59 | | return Result<bool>.Failure(headerValidation.Error!.Value); |
| | | 60 | | } |
| | | 61 | | |
| | 44 | 62 | | using var reader = new StringReader(content); |
| | 208 | 63 | | foreach (var row in _csvParser.Read(reader, hasHeader: true)) |
| | | 64 | | { |
| | 60 | 65 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 60 | 66 | | recon.RecordRead(); |
| | | 67 | | |
| | | 68 | | try |
| | | 69 | | { |
| | 120 | 70 | | if (!row.Fields.Any(f => !string.IsNullOrWhiteSpace(f))) |
| | | 71 | | { |
| | 0 | 72 | | recon.RecordSkipped("empty_row"); |
| | 0 | 73 | | continue; |
| | | 74 | | } |
| | | 75 | | |
| | 60 | 76 | | context.Summary.RecordFieldRead("watchlist-companies.csv", "company", !string.IsNullOrWhiteSpace(row["co |
| | 60 | 77 | | context.Summary.RecordFieldRead("watchlist-companies.csv", "proposed_status", !string.IsNullOrWhiteSpace |
| | 60 | 78 | | context.Summary.RecordFieldRead("watchlist-companies.csv", "text", !string.IsNullOrWhiteSpace(row["text" |
| | 60 | 79 | | context.Summary.RecordFieldRead("watchlist-companies.csv", "decision", !string.IsNullOrWhiteSpace(row["d |
| | 60 | 80 | | context.Summary.RecordFieldRead("watchlist-companies.csv", "corrected_notes", !string.IsNullOrWhiteSpace |
| | | 81 | | |
| | 60 | 82 | | var companyName = TrackerImportTextSanitizer.SanitizePlainText(row["company"])?.Trim(); |
| | 60 | 83 | | if (string.IsNullOrWhiteSpace(companyName)) |
| | | 84 | | { |
| | | 85 | | // If row has any non-blank field, missing company is a validation error |
| | 0 | 86 | | context.Summary.Errors.Add(new TrackerImportRowError( |
| | 0 | 87 | | "watchlist-companies.csv", |
| | 0 | 88 | | row.LineNumber, |
| | 0 | 89 | | ErrorCode.ValidationError.ToString(), |
| | 0 | 90 | | "Missing required 'company' column value.")); |
| | 0 | 91 | | recon.RecordErrored(); |
| | 0 | 92 | | continue; |
| | | 93 | | } |
| | | 94 | | |
| | 60 | 95 | | var decision = TrackerImportTextSanitizer.SanitizePlainText(row["decision"])?.Trim(); |
| | 60 | 96 | | if (string.Equals(decision, "skip", StringComparison.OrdinalIgnoreCase)) |
| | | 97 | | { |
| | 4 | 98 | | context.Summary.CompaniesUnchanged++; |
| | 4 | 99 | | recon.RecordSkipped("decision_skip"); |
| | 4 | 100 | | continue; |
| | | 101 | | } |
| | | 102 | | |
| | 56 | 103 | | if (!string.IsNullOrWhiteSpace(decision)) |
| | | 104 | | { |
| | 4 | 105 | | context.Summary.Errors.Add(new TrackerImportRowError( |
| | 4 | 106 | | "watchlist-companies.csv", |
| | 4 | 107 | | row.LineNumber, |
| | 4 | 108 | | ErrorCode.ValidationError.ToString(), |
| | 4 | 109 | | $"Invalid decision value '{decision}'. Expected blank or 'skip'.")); |
| | 4 | 110 | | recon.RecordErrored(); |
| | 4 | 111 | | continue; |
| | | 112 | | } |
| | | 113 | | |
| | 52 | 114 | | var proposedStatus = (TrackerImportTextSanitizer.SanitizePlainText(row["proposed_status"]) ?? TrackerImp |
| | 52 | 115 | | var status = MapStatus(proposedStatus, context); |
| | | 116 | | |
| | 52 | 117 | | var rawNotes = TrackerImportTextSanitizer.SanitizeFreeText(!string.IsNullOrWhiteSpace(row["corrected_not |
| | 52 | 118 | | ? row["corrected_notes"]!.Trim() |
| | 52 | 119 | | : (!string.IsNullOrWhiteSpace(row["text"]) |
| | 52 | 120 | | ? row["text"]!.Trim() |
| | 52 | 121 | | : row["notes"]?.Trim() ?? string.Empty)); |
| | | 122 | | |
| | 52 | 123 | | var canonicalName = context.CompanyAliases.TryGetValue(companyName, out var alias) ? alias : companyName |
| | | 124 | | |
| | | 125 | | // Enforce domain limits via shared limiter |
| | 52 | 126 | | canonicalName = TrackerImportFieldLimiter.LimitRequired(canonicalName, TrackerImportFieldLimiter.Company |
| | 52 | 127 | | var notes = TrackerImportFieldLimiter.LimitCompanyDescription(rawNotes, context.Summary) ?? string.Empty |
| | | 128 | | |
| | 52 | 129 | | var existing = await _context.Companies.GetByNormalizedNameAsync(context.OwnerId, canonicalName, cancell |
| | 52 | 130 | | if (existing.IsSuccess && existing.Value is not null) |
| | | 131 | | { |
| | 8 | 132 | | var existingCompany = existing.Value; |
| | 8 | 133 | | context.CanonicalCompanies[canonicalName] = existingCompany; |
| | 8 | 134 | | context.Summary.CompaniesUnchanged++; |
| | 8 | 135 | | recon.RecordUnchanged(); |
| | 8 | 136 | | continue; |
| | | 137 | | } |
| | | 138 | | |
| | 44 | 139 | | Company? createdCompany = null; |
| | 44 | 140 | | var rowResult = await _context.ExecuteInTransactionAsync(async (txCtx, ct) => |
| | 44 | 141 | | { |
| | 44 | 142 | | var company = Company.Create( |
| | 44 | 143 | | ownerId: context.OwnerId, |
| | 44 | 144 | | name: canonicalName, |
| | 44 | 145 | | status: status, |
| | 44 | 146 | | description: notes); |
| | 44 | 147 | | |
| | 44 | 148 | | var upsertResult = await txCtx.Companies.UpsertCompanyAsync(company, ct); |
| | 44 | 149 | | if (!upsertResult.IsSuccess) |
| | 44 | 150 | | { |
| | 0 | 151 | | return Result<bool>.Failure(upsertResult.Error ?? new ResultError(ErrorCode.ValidationError, "Fa |
| | 44 | 152 | | } |
| | 44 | 153 | | |
| | 44 | 154 | | var auditEntry = AuditLogEntry.CreateForTracking( |
| | 44 | 155 | | ownerId: context.OwnerId, |
| | 44 | 156 | | actor: ImportActor, |
| | 44 | 157 | | operation: AuditOperation.ImportCompanyCreate, |
| | 44 | 158 | | entityType: "company", |
| | 44 | 159 | | entityId: company.Id, |
| | 44 | 160 | | resultingVersionToken: company.VersionToken, |
| | 44 | 161 | | occurredAtUtc: DateTime.UtcNow, |
| | 44 | 162 | | details: new AuditDetails( |
| | 44 | 163 | | ChangedFields: ["name", "status", "description"], |
| | 44 | 164 | | After: new Dictionary<string, object?> |
| | 44 | 165 | | { |
| | 44 | 166 | | ["name"] = company.Name, |
| | 44 | 167 | | ["status"] = company.Status.ToString() |
| | 44 | 168 | | })); |
| | 44 | 169 | | |
| | 44 | 170 | | await txCtx.AppendAuditEntryAsync(auditEntry, ct); |
| | 44 | 171 | | createdCompany = company; |
| | 44 | 172 | | return Result<bool>.Success(true); |
| | 88 | 173 | | }, cancellationToken); |
| | | 174 | | |
| | 44 | 175 | | if (!rowResult.IsSuccess) |
| | | 176 | | { |
| | 0 | 177 | | context.Summary.Errors.Add(new TrackerImportRowError( |
| | 0 | 178 | | "watchlist-companies.csv", |
| | 0 | 179 | | row.LineNumber, |
| | 0 | 180 | | rowResult.Error?.Code.ToString() ?? ErrorCode.ValidationError.ToString(), |
| | 0 | 181 | | rowResult.Error?.Message ?? "Failed to save company")); |
| | 0 | 182 | | recon.RecordErrored(); |
| | 0 | 183 | | continue; |
| | | 184 | | } |
| | | 185 | | |
| | 44 | 186 | | if (createdCompany is not null) |
| | | 187 | | { |
| | 44 | 188 | | context.CanonicalCompanies[canonicalName] = createdCompany; |
| | 44 | 189 | | context.Summary.CompaniesCreated++; |
| | 44 | 190 | | recon.RecordCreated(); |
| | | 191 | | } |
| | 44 | 192 | | } |
| | 0 | 193 | | catch (Exception ex) when (ex is not OperationCanceledException) |
| | | 194 | | { |
| | 0 | 195 | | context.Summary.Errors.Add(new TrackerImportRowError( |
| | 0 | 196 | | "watchlist-companies.csv", |
| | 0 | 197 | | row.LineNumber, |
| | 0 | 198 | | ErrorCode.ValidationError.ToString(), |
| | 0 | 199 | | ex.Message)); |
| | 0 | 200 | | recon.RecordErrored(); |
| | 0 | 201 | | } |
| | 44 | 202 | | } |
| | | 203 | | |
| | 44 | 204 | | return Result<bool>.Success(true); |
| | 48 | 205 | | } |
| | | 206 | | |
| | | 207 | | private static CompanyStatus MapStatus(string? tier, TrackerImportContext context) |
| | | 208 | | { |
| | 52 | 209 | | if (string.IsNullOrWhiteSpace(tier)) |
| | | 210 | | { |
| | 0 | 211 | | return CompanyStatus.Neutral; |
| | | 212 | | } |
| | | 213 | | |
| | 52 | 214 | | return tier.Trim().ToLowerInvariant() switch |
| | 52 | 215 | | { |
| | 34 | 216 | | "target" => CompanyStatus.Target, |
| | 8 | 217 | | "watch" => CompanyStatus.Watch, |
| | 10 | 218 | | "avoid" => CompanyStatus.Avoid, |
| | 0 | 219 | | "neutral" => CompanyStatus.Neutral, |
| | 0 | 220 | | _ => FallbackTier(context, tier) |
| | 52 | 221 | | }; |
| | | 222 | | } |
| | | 223 | | |
| | | 224 | | private static CompanyStatus FallbackTier(TrackerImportContext context, string rawTier) |
| | | 225 | | { |
| | 0 | 226 | | context.Summary.RecordUnmappedValue("tier", rawTier); |
| | 0 | 227 | | return CompanyStatus.Neutral; |
| | | 228 | | } |
| | | 229 | | } |