< Summary

Information
Class: RoleRadar.Application.Tracking.Commands.ApplicationRecordResultDto
Assembly: RoleRadar.Application
File(s): /home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Tracking/Commands/ApplicationCommands.cs
Line coverage
100%
Covered lines: 7
Uncovered lines: 0
Coverable lines: 7
Total lines: 404
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_ApplicationId()100%11100%
get_PostingId()100%11100%
get_CurrentOutcome()100%11100%
get_OverrideApplied()100%11100%
get_EventCount()100%11100%
get_UpdatedAtUtc()100%11100%

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
 11034public sealed record ApplicationRecordResultDto(
 6835    Guid ApplicationId,
 2036    Guid PostingId,
 3437    string CurrentOutcome,
 2438    bool OverrideApplied,
 2039    int EventCount,
 12440    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{
 118    private static readonly RecordApplicationCommandValidator Validator = new();
 119    private readonly ITrackingTransactionContext _context;
 120    private readonly IUtcClock _clock;
 121
 122    public RecordApplicationCommandHandler(ITrackingTransactionContext context, IUtcClock? clock = null)
 123    {
 124        _context = context ?? throw new ArgumentNullException(nameof(context));
 125        _clock = clock ?? SystemUtcClock.Instance;
 126    }
 127
 128    public async Task<Result<ApplicationRecordResultDto>> HandleAsync(
 129        RecordApplicationCommand command,
 130        CancellationToken cancellationToken = default)
 131    {
 132        ArgumentNullException.ThrowIfNull(command);
 133
 134        var valError = Validator.Validate(command);
 135        if (valError is not null)
 136        {
 137            return Result<ApplicationRecordResultDto>.Failure(valError.Value);
 138        }
 139
 140        var action = command.Action.Trim().ToLowerInvariant();
 141        var ownerId = string.IsNullOrWhiteSpace(command.OwnerId)
 142            ? OwnerId.Default.Value
 143            : new OwnerId(command.OwnerId).Value;
 144        var now = _clock.UtcNow;
 145
 146        return await _context.Companies.ExecuteInTransactionAsync(async (ctx, ct) =>
 147        {
 148            try
 149            {
 150                var postRes = await ctx.Postings.GetByIdAsync(ownerId, command.PostingId, ct);
 151                if (!postRes.IsSuccess || postRes.Value is null)
 152                {
 153                    return Result<ApplicationRecordResultDto>.Failure(ErrorCode.NotFound, "Posting not found.");
 154                }
 155
 156                var posting = postRes.Value;
 157
 158                if (action == "create")
 159                {
 160                    return await HandleCreateAsync(ctx, posting, command, ownerId, now, ct);
 161                }
 162                else
 163                {
 164                    return await HandleAppendEventAsync(ctx, posting, command, ownerId, now, ct);
 165                }
 166            }
 167            catch (Exception ex) when (IsDuplicateKeyException(ex))
 168            {
 169                return Result<ApplicationRecordResultDto>.Failure(
 170                    ErrorCode.InvalidTransition,
 171                    "An application already exists for this posting or state transition conflict occurred.");
 172            }
 173        }, cancellationToken);
 174    }
 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    {
 184        var existingAppRes = await ctx.Applications.GetByPostingIdAsync(ownerId, posting.Id, cancellationToken);
 185        if (existingAppRes.IsSuccess && existingAppRes.Value is not null)
 186        {
 187            return Result<ApplicationRecordResultDto>.Failure(
 188                ErrorCode.InvalidTransition,
 189                "An application already exists for this posting.");
 190        }
 191
 192        var isOverride = false;
 193        if (posting.Disposition == PostingDisposition.Applied)
 194        {
 195            return Result<ApplicationRecordResultDto>.Failure(
 196                ErrorCode.InvalidTransition,
 197                "Posting is already in applied status.");
 198        }
 199
 200        if (posting.Disposition == PostingDisposition.Rejected)
 201        {
 202            return Result<ApplicationRecordResultDto>.Failure(
 203                ErrorCode.InvalidTransition,
 204                "Cannot apply to rejected posting without explicit reopen.");
 205        }
 206
 207        if (posting.Disposition is PostingDisposition.ScreenedOut or PostingDisposition.Closed)
 208        {
 209            if (!command.OverrideDecided)
 210            {
 211                return Result<ApplicationRecordResultDto>.Failure(
 212                    ErrorCode.InvalidTransition,
 213                    $"Cannot apply to decided posting in '{posting.Disposition.ToSnakeCase()}' status without overrideDe
 214            }
 215
 216            if (string.IsNullOrWhiteSpace(command.OverrideReason))
 217            {
 218                return Result<ApplicationRecordResultDto>.Failure(
 219                    ErrorCode.ValidationError,
 220                    "Reopen-and-apply override requires an explicit non-empty overrideReason.");
 221            }
 222
 223            isOverride = true;
 224        }
 225
 226        _ = TrackingEnumExtensions.TryParseResumeVariant(command.ResumeVariant, out var variant);
 227        var salary = new DesiredSalary(
 228            command.DesiredSalaryMin,
 229            command.DesiredSalaryMax,
 230            command.DesiredSalaryCurrency ?? "USD");
 231
 232        ApplicationEntity application;
 233        try
 234        {
 235            application = ApplicationEntity.Create(
 236                ownerId: ownerId,
 237                postingId: posting.Id,
 238                submittedDate: command.SubmittedDate!,
 239                resumeVariant: variant,
 240                desiredSalary: salary,
 241                targetStartDate: command.TargetStartDate,
 242                resumePointer: command.ResumePointer,
 243                referralContactId: command.ReferralContactId,
 244                confirmationCode: command.ConfirmationCode,
 245                now: now);
 246        }
 247        catch (ArgumentException ex)
 248        {
 249            return Result<ApplicationRecordResultDto>.Failure(ErrorCode.ValidationError, ex.Message);
 250        }
 251
 252        var initialEvent = ApplicationEvent.Create(
 253            ownerId: ownerId,
 254            applicationId: application.Id,
 255            eventDate: command.SubmittedDate!,
 256            eventType: ApplicationEventType.Applied,
 257            eventSource: "application_record",
 258            notes: isOverride ? $"Application submitted with override: {command.OverrideReason}" : "Application submitte
 259            now: now);
 260
 261        var priorDisposition = posting.Disposition.ToSnakeCase();
 262        var priorPolicy = posting.ResurfacePolicy.ToSnakeCase();
 263
 264        posting.TransitionToApplied(now);
 265
 266        await ctx.Postings.UpsertPostingAsync(posting, cancellationToken);
 267        await ctx.Applications.UpsertApplicationAsync(application, cancellationToken);
 268        await ctx.Applications.AppendEventAsync(initialEvent, cancellationToken);
 269
 270        var details = AuditDetails.ForEntity(
 271            changedFields: ["posting_id", "submitted_date", "resume_variant", "outcome"],
 272            before: null,
 273            after: new Dictionary<string, object?>
 274            {
 275                ["posting_id"] = posting.Id,
 276                ["submitted_date"] = command.SubmittedDate,
 277                ["outcome"] = application.Outcome.ToSnakeCase(),
 278                ["override_applied"] = isOverride
 279            });
 280
 281        var auditEntry = AuditLogEntry.CreateForTracking(
 282            ownerId: ownerId,
 283            actor: command.Actor,
 284            operation: AuditOperation.ApplicationCreate,
 285            entityType: "application",
 286            entityId: application.Id,
 287            resultingVersionToken: application.VersionToken,
 288            occurredAtUtc: now.UtcDateTime,
 289            details: details);
 290
 291        await ctx.AppendAuditEntryAsync(auditEntry, cancellationToken);
 292
 293        return Result<ApplicationRecordResultDto>.Success(new ApplicationRecordResultDto(
 294            ApplicationId: application.Id,
 295            PostingId: posting.Id,
 296            CurrentOutcome: "applied",
 297            OverrideApplied: isOverride,
 298            EventCount: 1,
 299            UpdatedAtUtc: now));
 300    }
 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    {
 310        var appRes = await ctx.Applications.GetByPostingIdAsync(ownerId, posting.Id, cancellationToken);
 311        if (!appRes.IsSuccess || appRes.Value is null)
 312        {
 313            return Result<ApplicationRecordResultDto>.Failure(
 314                ErrorCode.NotFound,
 315                "Application not found for posting.");
 316        }
 317
 318        var app = appRes.Value;
 319        _ = TrackingEnumExtensions.TryParseApplicationEventType(command.Event!.EventType, out var eventType);
 320
 321        ApplicationEvent appEvent;
 322        try
 323        {
 324            appEvent = ApplicationEvent.Create(
 325                ownerId: ownerId,
 326                applicationId: app.Id,
 327                eventDate: command.Event.EventDate,
 328                eventType: eventType,
 329                eventSource: command.Event.EventSource,
 330                notes: command.Event.Notes,
 331                now: now);
 332        }
 333        catch (ArgumentException ex)
 334        {
 335            return Result<ApplicationRecordResultDto>.Failure(ErrorCode.ValidationError, ex.Message);
 336        }
 337
 338        app.ApplyEvent(eventType, command.Event.Notes, now);
 339
 340        // Synchronize posting disposition unless posting is already in a terminal/decided state
 341        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:
 354                    posting.SynchronizeFromApplicationEvent(PostingDisposition.Rejected, command.Event.Notes, now);
 355                    break;
 356
 357                case ApplicationEventType.OfferAccepted:
 358                case ApplicationEventType.OfferDeclined:
 359                case ApplicationEventType.Withdrawn:
 360                    posting.SynchronizeFromApplicationEvent(PostingDisposition.Closed, command.Event.Notes, now);
 361                    break;
 362            }
 363        }
 364
 365        await ctx.Postings.UpsertPostingAsync(posting, cancellationToken);
 366        await ctx.Applications.UpsertApplicationAsync(app, cancellationToken);
 367        await ctx.Applications.AppendEventAsync(appEvent, cancellationToken);
 368
 369        var eventsRes = await ctx.Applications.GetEventsAsync(ownerId, app.Id, cancellationToken);
 370        var eventCount = eventsRes.IsSuccess ? eventsRes.Value!.Count : 1;
 371
 372        var details = AuditDetails.ForEntity(
 373            changedFields: ["outcome"],
 374            before: new Dictionary<string, object?> { ["outcome"] = app.Outcome.ToSnakeCase() },
 375            after: new Dictionary<string, object?> { ["event_type"] = eventType.ToSnakeCase(), ["event_date"] = command.
 376
 377        var auditEntry = AuditLogEntry.CreateForTracking(
 378            ownerId: ownerId,
 379            actor: command.Actor,
 380            operation: AuditOperation.ApplicationEventAppend,
 381            entityType: "application",
 382            entityId: app.Id,
 383            resultingVersionToken: app.VersionToken,
 384            occurredAtUtc: now.UtcDateTime,
 385            details: details);
 386
 387        await ctx.AppendAuditEntryAsync(auditEntry, cancellationToken);
 388
 389        return Result<ApplicationRecordResultDto>.Success(new ApplicationRecordResultDto(
 390            ApplicationId: app.Id,
 391            PostingId: posting.Id,
 392            CurrentOutcome: app.Outcome.ToSnakeCase(),
 393            OverrideApplied: false,
 394            EventCount: eventCount,
 395            UpdatedAtUtc: now));
 396    }
 397
 398    private static bool IsDuplicateKeyException(Exception ex)
 399    {
 400        return ex.Message.Contains("E11000", StringComparison.OrdinalIgnoreCase)
 401            || ex.Message.Contains("duplicate key", StringComparison.OrdinalIgnoreCase)
 402            || (ex.InnerException is not null && IsDuplicateKeyException(ex.InnerException));
 403    }
 404}