< Summary

Information
Class: RoleRadar.Application.Tracking.Import.Commands.ImportTrackerCommand
Assembly: RoleRadar.Application
File(s): /home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Tracking/Import/Commands/ImportTrackerCommand.cs
Line coverage
100%
Covered lines: 6
Uncovered lines: 0
Coverable lines: 6
Total lines: 161
Line coverage: 100%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_BundleDirectory()100%11100%
get_DefaultDate()100%11100%
get_Apply()100%11100%
get_ReportPath()100%11100%
get_OwnerId()100%11100%

File(s)

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

#LineLine coverage
 1using RoleRadar.Application.Abstractions;
 2using RoleRadar.Application.Tracking.Import.Pipeline;
 3using RoleRadar.Application.Tracking.Import.Report;
 4using RoleRadar.Domain.Common;
 5
 6namespace RoleRadar.Application.Tracking.Import.Commands;
 7
 428public sealed record ImportTrackerCommand(
 1389    string BundleDirectory,
 9010    DateOnly? DefaultDate = null,
 8011    bool Apply = false,
 9012    string? ReportPath = null,
 8213    string? OwnerId = null);
 14
 15public interface ITrackerImportCoordinator
 16{
 17    Task<Result<TrackerImportSummary>> ExecuteAsync(ImportTrackerCommand command, CancellationToken cancellationToken = 
 18}
 19
 20public sealed class TrackerImportCoordinator : ITrackerImportCoordinator
 21{
 22    private readonly ITrackerScratchManager _scratchManager;
 23    private readonly ITrackingContextFactory _contextFactory;
 24    private readonly ICsvParser _csvParser;
 25    private readonly ITrackerImportPipelineFactory _pipelineFactory;
 26
 27    public TrackerImportCoordinator(
 28        ITrackerScratchManager scratchManager,
 29        ITrackingContextFactory contextFactory,
 30        ICsvParser csvParser,
 31        ITrackerImportPipelineFactory pipelineFactory)
 32    {
 33        _scratchManager = scratchManager ?? throw new ArgumentNullException(nameof(scratchManager));
 34        _contextFactory = contextFactory ?? throw new ArgumentNullException(nameof(contextFactory));
 35        _csvParser = csvParser ?? throw new ArgumentNullException(nameof(csvParser));
 36        _pipelineFactory = pipelineFactory ?? throw new ArgumentNullException(nameof(pipelineFactory));
 37    }
 38
 39    public async Task<Result<TrackerImportSummary>> ExecuteAsync(
 40        ImportTrackerCommand command,
 41        CancellationToken cancellationToken = default)
 42    {
 43        ArgumentNullException.ThrowIfNull(command);
 44
 45        if (string.IsNullOrWhiteSpace(command.BundleDirectory) || !Directory.Exists(command.BundleDirectory))
 46        {
 47            return Result<TrackerImportSummary>.Failure(
 48                ErrorCode.ValidationError,
 49                $"Bundle directory not found: '{command.BundleDirectory}'.");
 50        }
 51
 52        // Validate --report path does not reside in a git work tree
 53        if (!string.IsNullOrWhiteSpace(command.ReportPath))
 54        {
 55            if (TrackerImportReportGenerator.IsInsideGitWorkTree(command.ReportPath))
 56            {
 57                return Result<TrackerImportSummary>.Failure(
 58                    ErrorCode.ValidationError,
 59                    $"Refusing to write report to '{command.ReportPath}': report path must not reside inside a git worki
 60            }
 61        }
 62
 63        // Pre-scan for missing dates when --default-date is omitted
 64        if (command.DefaultDate is null)
 65        {
 66            var dateCheckResult = CheckForMissingOrPartialDates(command.BundleDirectory);
 67            if (dateCheckResult is not null)
 68            {
 69                return Result<TrackerImportSummary>.Failure(dateCheckResult.Value);
 70            }
 71        }
 72
 73        var ownerId = string.IsNullOrWhiteSpace(command.OwnerId)
 74            ? OwnerId.Default.Value
 75            : new OwnerId(command.OwnerId).Value;
 76
 77        var targetDbName = _contextFactory.TargetDatabaseName;
 78
 79        Result<TrackerImportSummary> runResult;
 80        if (!command.Apply)
 81        {
 82            // Dry-run mode: ephemerally isolated inside scratch database
 83            await _scratchManager.CleanupOrphanedScratchDatabasesAsync(targetDbName, cancellationToken: cancellationToke
 84
 85            await using var scratchScope = await _scratchManager.CreateScopeAsync(targetDbName, cancellationToken);
 86            runResult = await RunPipelineAsync(scratchScope.ScratchDatabaseName, ownerId, command, isDryRun: true, cance
 87        }
 88        else
 89        {
 90            // Apply mode: commits persistent writes to target database
 91            runResult = await RunPipelineAsync(targetDbName, ownerId, command, isDryRun: false, cancellationToken);
 92        }
 93
 94        if (runResult.IsSuccess && !string.IsNullOrWhiteSpace(command.ReportPath))
 95        {
 96            await TrackerImportReportGenerator.GenerateReportAsync(command.ReportPath, command, runResult.Value!, cancel
 97        }
 98
 99        return runResult;
 100    }
 101
 102    private async Task<Result<TrackerImportSummary>> RunPipelineAsync(
 103        string databaseName,
 104        string ownerId,
 105        ImportTrackerCommand command,
 106        bool isDryRun,
 107        CancellationToken cancellationToken)
 108    {
 109        var context = new TrackerImportContext
 110        {
 111            OwnerId = ownerId,
 112            BundleDirectory = command.BundleDirectory,
 113            DefaultDate = command.DefaultDate,
 114            Apply = command.Apply,
 115            Summary = { IsDryRun = isDryRun }
 116        };
 117
 118        var trackingContext = _contextFactory.CreateContext(databaseName);
 119        var pipeline = _pipelineFactory.CreatePipeline(trackingContext);
 120
 121        return await pipeline.ExecuteAsync(context, cancellationToken);
 122    }
 123
 124
 125
 126    private ResultError? CheckForMissingOrPartialDates(string bundleDirectory)
 127    {
 128        var filesToCheck = new[] { "appendix-rows.csv", "applications.csv" };
 129
 130        foreach (var file in filesToCheck)
 131        {
 132            var fullPath = Path.Combine(bundleDirectory, file);
 133            if (!File.Exists(fullPath))
 134            {
 135                continue;
 136            }
 137
 138            using var reader = new StreamReader(fullPath);
 139            var partialDateCount = 0;
 140
 141            foreach (var row in _csvParser.Read(reader, hasHeader: true))
 142            {
 143                var addedMd = row["applied_on"] ?? row["added_md"] ?? row["applied_date_md"] ?? row["rejected_date_md"];
 144                if (string.IsNullOrWhiteSpace(addedMd) ||
 145                    (!addedMd.Trim().StartsWith("20", StringComparison.Ordinal) && !addedMd.Trim().StartsWith("19", Stri
 146                {
 147                    partialDateCount++;
 148                }
 149            }
 150
 151            if (partialDateCount > 0)
 152            {
 153                return new ResultError(
 154                    ErrorCode.ValidationError,
 155                    $"Missing required --default-date: {file} has {partialDateCount} rows with undated or partial date f
 156            }
 157        }
 158
 159        return null;
 160    }
 161}