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