< Summary

Information
Class: RoleRadar.Application.Tracking.Commands.RecordApplicationCommandHandler
Assembly: RoleRadar.Application
File(s): /home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Tracking/Commands/ApplicationCommands.cs
Line coverage
90%
Covered lines: 163
Uncovered lines: 18
Coverable lines: 181
Total lines: 404
Line coverage: 90%
Branch coverage
78%
Covered branches: 45
Total branches: 57
Branch coverage: 78.9%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)75%44100%
HandleAsync()75%4496.15%
<HandleAsync()66.66%7666.66%
HandleCreateAsync()85%212087.05%
HandleAppendEventAsync()82.35%171790%
IsDuplicateKeyException(...)50%66100%

File(s)

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

#LineLine coverage
 1using System.Globalization;
 2using RoleRadar.Application.Abstractions;
 3using RoleRadar.Domain.Audit;
 4using RoleRadar.Domain.Common;
 5using RoleRadar.Domain.Tracking;
 6using ApplicationEntity = RoleRadar.Domain.Tracking.Application;
 7
 8namespace RoleRadar.Application.Tracking.Commands;
 9
 10public sealed record ApplicationEventInputDto(
 11    string EventType,
 12    string EventDate,
 13    string? EventSource = null,
 14    string? Notes = null);
 15
 16public sealed record RecordApplicationCommand(
 17    Guid PostingId,
 18    string Action,
 19    string Actor,
 20    string? SubmittedDate = null,
 21    decimal? DesiredSalaryMin = null,
 22    decimal? DesiredSalaryMax = null,
 23    string? DesiredSalaryCurrency = null,
 24    string? TargetStartDate = null,
 25    string? ResumeVariant = null,
 26    string? ResumePointer = null,
 27    Guid? ReferralContactId = null,
 28    string? ConfirmationCode = null,
 29    bool OverrideDecided = false,
 30    string? OverrideReason = null,
 31    ApplicationEventInputDto? Event = null,
 32    string? OwnerId = null) : ICommand<ApplicationRecordResultDto>;
 33
 34public sealed record ApplicationRecordResultDto(
 35    Guid ApplicationId,
 36    Guid PostingId,
 37    string CurrentOutcome,
 38    bool OverrideApplied,
 39    int EventCount,
 40    DateTimeOffset UpdatedAtUtc);
 41
 42public sealed class RecordApplicationCommandValidator : ICommandValidator<RecordApplicationCommand>
 43{
 44    public ResultError? Validate(RecordApplicationCommand command)
 45    {
 46        ArgumentNullException.ThrowIfNull(command);
 47
 48        var actorError = CommandActor.Validate(command.Actor);
 49        if (actorError is not null)
 50        {
 51            return actorError;
 52        }
 53
 54        if (command.PostingId == Guid.Empty)
 55        {
 56            return new ResultError(ErrorCode.ValidationError, "Posting ID cannot be empty.");
 57        }
 58
 59        if (string.IsNullOrWhiteSpace(command.Action))
 60        {
 61            return new ResultError(ErrorCode.ValidationError, "Action is required ('create' or 'append_event').");
 62        }
 63
 64        var action = command.Action.Trim().ToLowerInvariant();
 65        if (action == "create")
 66        {
 67            if (string.IsNullOrWhiteSpace(command.SubmittedDate))
 68            {
 69                return new ResultError(ErrorCode.ValidationError, "SubmittedDate is required when action is 'create'.");
 70            }
 71
 72            if (!DateOnly.TryParseExact(command.SubmittedDate.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTi
 73            {
 74                return new ResultError(ErrorCode.ValidationError, $"SubmittedDate must be in YYYY-MM-DD format: '{comman
 75            }
 76
 77            if (string.IsNullOrWhiteSpace(command.ResumeVariant) ||
 78                !TrackingEnumExtensions.TryParseResumeVariant(command.ResumeVariant, out _))
 79            {
 80                return new ResultError(ErrorCode.ValidationError, "ResumeVariant is required for 'create' ('tailored', '
 81            }
 82
 83            if (command.OverrideDecided && string.IsNullOrWhiteSpace(command.OverrideReason))
 84            {
 85                return new ResultError(ErrorCode.ValidationError, "Reopen-and-apply override requires an explicit non-em
 86            }
 87        }
 88        else if (action == "append_event")
 89        {
 90            if (command.Event is null)
 91            {
 92                return new ResultError(ErrorCode.ValidationError, "Event payload is required when action is 'append_even
 93            }
 94
 95            if (string.IsNullOrWhiteSpace(command.Event.EventType) ||
 96                !TrackingEnumExtensions.TryParseApplicationEventType(command.Event.EventType, out _))
 97            {
 98                return new ResultError(ErrorCode.ValidationError, $"Invalid eventType '{command.Event.EventType}'.");
 99            }
 100
 101            if (string.IsNullOrWhiteSpace(command.Event.EventDate) ||
 102                !DateOnly.TryParseExact(command.Event.EventDate.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, Date
 103            {
 104                return new ResultError(ErrorCode.ValidationError, $"EventDate must be in YYYY-MM-DD format: '{command.Ev
 105            }
 106        }
 107        else
 108        {
 109            return new ResultError(ErrorCode.ValidationError, $"Unknown action '{command.Action}'. Expected 'create' or 
 110        }
 111
 112        return null;
 113    }
 114}
 115
 116public sealed class RecordApplicationCommandHandler : ICommandHandler<RecordApplicationCommand, ApplicationRecordResultD
 117{
 28118    private static readonly RecordApplicationCommandValidator Validator = new();
 119    private readonly ITrackingTransactionContext _context;
 120    private readonly IUtcClock _clock;
 121
 390122    public RecordApplicationCommandHandler(ITrackingTransactionContext context, IUtcClock? clock = null)
 123    {
 390124        _context = context ?? throw new ArgumentNullException(nameof(context));
 390125        _clock = clock ?? SystemUtcClock.Instance;
 390126    }
 127
 128    public async Task<Result<ApplicationRecordResultDto>> HandleAsync(
 129        RecordApplicationCommand command,
 130        CancellationToken cancellationToken = default)
 131    {
 136132        ArgumentNullException.ThrowIfNull(command);
 133
 136134        var valError = Validator.Validate(command);
 136135        if (valError is not null)
 136        {
 0137            return Result<ApplicationRecordResultDto>.Failure(valError.Value);
 138        }
 139
 136140        var action = command.Action.Trim().ToLowerInvariant();
 136141        var ownerId = string.IsNullOrWhiteSpace(command.OwnerId)
 136142            ? OwnerId.Default.Value
 136143            : new OwnerId(command.OwnerId).Value;
 136144        var now = _clock.UtcNow;
 145
 136146        return await _context.Companies.ExecuteInTransactionAsync(async (ctx, ct) =>
 136147        {
 136148            try
 136149            {
 136150                var postRes = await ctx.Postings.GetByIdAsync(ownerId, command.PostingId, ct);
 136151                if (!postRes.IsSuccess || postRes.Value is null)
 136152                {
 0153                    return Result<ApplicationRecordResultDto>.Failure(ErrorCode.NotFound, "Posting not found.");
 136154                }
 136155
 136156                var posting = postRes.Value;
 136157
 136158                if (action == "create")
 136159                {
 102160                    return await HandleCreateAsync(ctx, posting, command, ownerId, now, ct);
 136161                }
 136162                else
 136163                {
 34164                    return await HandleAppendEventAsync(ctx, posting, command, ownerId, now, ct);
 136165                }
 136166            }
 10167            catch (Exception ex) when (IsDuplicateKeyException(ex))
 136168            {
 0169                return Result<ApplicationRecordResultDto>.Failure(
 0170                    ErrorCode.InvalidTransition,
 0171                    "An application already exists for this posting or state transition conflict occurred.");
 136172            }
 262173        }, cancellationToken);
 126174    }
 175
 176    private static async Task<Result<ApplicationRecordResultDto>> HandleCreateAsync(
 177        ITrackingTransactionContext ctx,
 178        Posting posting,
 179        RecordApplicationCommand command,
 180        string ownerId,
 181        DateTimeOffset now,
 182        CancellationToken cancellationToken)
 183    {
 102184        var existingAppRes = await ctx.Applications.GetByPostingIdAsync(ownerId, posting.Id, cancellationToken);
 102185        if (existingAppRes.IsSuccess && existingAppRes.Value is not null)
 186        {
 14187            return Result<ApplicationRecordResultDto>.Failure(
 14188                ErrorCode.InvalidTransition,
 14189                "An application already exists for this posting.");
 190        }
 191
 88192        var isOverride = false;
 88193        if (posting.Disposition == PostingDisposition.Applied)
 194        {
 2195            return Result<ApplicationRecordResultDto>.Failure(
 2196                ErrorCode.InvalidTransition,
 2197                "Posting is already in applied status.");
 198        }
 199
 86200        if (posting.Disposition == PostingDisposition.Rejected)
 201        {
 0202            return Result<ApplicationRecordResultDto>.Failure(
 0203                ErrorCode.InvalidTransition,
 0204                "Cannot apply to rejected posting without explicit reopen.");
 205        }
 206
 86207        if (posting.Disposition is PostingDisposition.ScreenedOut or PostingDisposition.Closed)
 208        {
 8209            if (!command.OverrideDecided)
 210            {
 4211                return Result<ApplicationRecordResultDto>.Failure(
 4212                    ErrorCode.InvalidTransition,
 4213                    $"Cannot apply to decided posting in '{posting.Disposition.ToSnakeCase()}' status without overrideDe
 214            }
 215
 4216            if (string.IsNullOrWhiteSpace(command.OverrideReason))
 217            {
 0218                return Result<ApplicationRecordResultDto>.Failure(
 0219                    ErrorCode.ValidationError,
 0220                    "Reopen-and-apply override requires an explicit non-empty overrideReason.");
 221            }
 222
 4223            isOverride = true;
 224        }
 225
 82226        _ = TrackingEnumExtensions.TryParseResumeVariant(command.ResumeVariant, out var variant);
 82227        var salary = new DesiredSalary(
 82228            command.DesiredSalaryMin,
 82229            command.DesiredSalaryMax,
 82230            command.DesiredSalaryCurrency ?? "USD");
 231
 232        ApplicationEntity application;
 233        try
 234        {
 82235            application = ApplicationEntity.Create(
 82236                ownerId: ownerId,
 82237                postingId: posting.Id,
 82238                submittedDate: command.SubmittedDate!,
 82239                resumeVariant: variant,
 82240                desiredSalary: salary,
 82241                targetStartDate: command.TargetStartDate,
 82242                resumePointer: command.ResumePointer,
 82243                referralContactId: command.ReferralContactId,
 82244                confirmationCode: command.ConfirmationCode,
 82245                now: now);
 82246        }
 0247        catch (ArgumentException ex)
 248        {
 0249            return Result<ApplicationRecordResultDto>.Failure(ErrorCode.ValidationError, ex.Message);
 250        }
 251
 82252        var initialEvent = ApplicationEvent.Create(
 82253            ownerId: ownerId,
 82254            applicationId: application.Id,
 82255            eventDate: command.SubmittedDate!,
 82256            eventType: ApplicationEventType.Applied,
 82257            eventSource: "application_record",
 82258            notes: isOverride ? $"Application submitted with override: {command.OverrideReason}" : "Application submitte
 82259            now: now);
 260
 82261        var priorDisposition = posting.Disposition.ToSnakeCase();
 82262        var priorPolicy = posting.ResurfacePolicy.ToSnakeCase();
 263
 82264        posting.TransitionToApplied(now);
 265
 82266        await ctx.Postings.UpsertPostingAsync(posting, cancellationToken);
 72267        await ctx.Applications.UpsertApplicationAsync(application, cancellationToken);
 72268        await ctx.Applications.AppendEventAsync(initialEvent, cancellationToken);
 269
 72270        var details = AuditDetails.ForEntity(
 72271            changedFields: ["posting_id", "submitted_date", "resume_variant", "outcome"],
 72272            before: null,
 72273            after: new Dictionary<string, object?>
 72274            {
 72275                ["posting_id"] = posting.Id,
 72276                ["submitted_date"] = command.SubmittedDate,
 72277                ["outcome"] = application.Outcome.ToSnakeCase(),
 72278                ["override_applied"] = isOverride
 72279            });
 280
 72281        var auditEntry = AuditLogEntry.CreateForTracking(
 72282            ownerId: ownerId,
 72283            actor: command.Actor,
 72284            operation: AuditOperation.ApplicationCreate,
 72285            entityType: "application",
 72286            entityId: application.Id,
 72287            resultingVersionToken: application.VersionToken,
 72288            occurredAtUtc: now.UtcDateTime,
 72289            details: details);
 290
 72291        await ctx.AppendAuditEntryAsync(auditEntry, cancellationToken);
 292
 72293        return Result<ApplicationRecordResultDto>.Success(new ApplicationRecordResultDto(
 72294            ApplicationId: application.Id,
 72295            PostingId: posting.Id,
 72296            CurrentOutcome: "applied",
 72297            OverrideApplied: isOverride,
 72298            EventCount: 1,
 72299            UpdatedAtUtc: now));
 92300    }
 301
 302    private static async Task<Result<ApplicationRecordResultDto>> HandleAppendEventAsync(
 303        ITrackingTransactionContext ctx,
 304        Posting posting,
 305        RecordApplicationCommand command,
 306        string ownerId,
 307        DateTimeOffset now,
 308        CancellationToken cancellationToken)
 309    {
 34310        var appRes = await ctx.Applications.GetByPostingIdAsync(ownerId, posting.Id, cancellationToken);
 34311        if (!appRes.IsSuccess || appRes.Value is null)
 312        {
 0313            return Result<ApplicationRecordResultDto>.Failure(
 0314                ErrorCode.NotFound,
 0315                "Application not found for posting.");
 316        }
 317
 34318        var app = appRes.Value;
 34319        _ = TrackingEnumExtensions.TryParseApplicationEventType(command.Event!.EventType, out var eventType);
 320
 321        ApplicationEvent appEvent;
 322        try
 323        {
 34324            appEvent = ApplicationEvent.Create(
 34325                ownerId: ownerId,
 34326                applicationId: app.Id,
 34327                eventDate: command.Event.EventDate,
 34328                eventType: eventType,
 34329                eventSource: command.Event.EventSource,
 34330                notes: command.Event.Notes,
 34331                now: now);
 34332        }
 0333        catch (ArgumentException ex)
 334        {
 0335            return Result<ApplicationRecordResultDto>.Failure(ErrorCode.ValidationError, ex.Message);
 336        }
 337
 34338        app.ApplyEvent(eventType, command.Event.Notes, now);
 339
 340        // Synchronize posting disposition unless posting is already in a terminal/decided state
 34341        if (posting.Disposition is not PostingDisposition.Rejected and not PostingDisposition.Closed)
 342        {
 343            switch (eventType)
 344            {
 345                case ApplicationEventType.Offer:
 346                    // Non-terminal; posting stays in applied
 347                    break;
 348
 349                case ApplicationEventType.Note:
 350                    // A remark or correction: never reaches the posting.
 351                    break;
 352
 353                case ApplicationEventType.Rejected:
 6354                    posting.SynchronizeFromApplicationEvent(PostingDisposition.Rejected, command.Event.Notes, now);
 6355                    break;
 356
 357                case ApplicationEventType.OfferAccepted:
 358                case ApplicationEventType.OfferDeclined:
 359                case ApplicationEventType.Withdrawn:
 6360                    posting.SynchronizeFromApplicationEvent(PostingDisposition.Closed, command.Event.Notes, now);
 361                    break;
 362            }
 363        }
 364
 34365        await ctx.Postings.UpsertPostingAsync(posting, cancellationToken);
 34366        await ctx.Applications.UpsertApplicationAsync(app, cancellationToken);
 34367        await ctx.Applications.AppendEventAsync(appEvent, cancellationToken);
 368
 34369        var eventsRes = await ctx.Applications.GetEventsAsync(ownerId, app.Id, cancellationToken);
 34370        var eventCount = eventsRes.IsSuccess ? eventsRes.Value!.Count : 1;
 371
 34372        var details = AuditDetails.ForEntity(
 34373            changedFields: ["outcome"],
 34374            before: new Dictionary<string, object?> { ["outcome"] = app.Outcome.ToSnakeCase() },
 34375            after: new Dictionary<string, object?> { ["event_type"] = eventType.ToSnakeCase(), ["event_date"] = command.
 376
 34377        var auditEntry = AuditLogEntry.CreateForTracking(
 34378            ownerId: ownerId,
 34379            actor: command.Actor,
 34380            operation: AuditOperation.ApplicationEventAppend,
 34381            entityType: "application",
 34382            entityId: app.Id,
 34383            resultingVersionToken: app.VersionToken,
 34384            occurredAtUtc: now.UtcDateTime,
 34385            details: details);
 386
 34387        await ctx.AppendAuditEntryAsync(auditEntry, cancellationToken);
 388
 34389        return Result<ApplicationRecordResultDto>.Success(new ApplicationRecordResultDto(
 34390            ApplicationId: app.Id,
 34391            PostingId: posting.Id,
 34392            CurrentOutcome: app.Outcome.ToSnakeCase(),
 34393            OverrideApplied: false,
 34394            EventCount: eventCount,
 34395            UpdatedAtUtc: now));
 34396    }
 397
 398    private static bool IsDuplicateKeyException(Exception ex)
 399    {
 10400        return ex.Message.Contains("E11000", StringComparison.OrdinalIgnoreCase)
 10401            || ex.Message.Contains("duplicate key", StringComparison.OrdinalIgnoreCase)
 10402            || (ex.InnerException is not null && IsDuplicateKeyException(ex.InnerException));
 403    }
 404}