UserDeletedEventHandler.cs
1,796 bytes
| 1 | using Microsoft.EntityFrameworkCore; |
|---|---|
| 2 | using SplitApp.Modules.Expenses.Infrastructure.Persistence; |
| 3 | using SplitApp.Modules.Trips.Infrastructure.Persistence; |
| 4 | using SplitApp.Shared.Messaging; |
| 5 | using SplitApp.Shared.Messaging.Integration.Users; |
| 6 | |
| 7 | namespace SplitApp.WebApp.Application.Messaging; |
| 8 | |
| 9 | /// <summary> |
| 10 | /// Cascades user deletion across the monolith: drops the user's TripParticipant rows |
| 11 | /// and removes ExpenseSplit references. Pure data cleanup — no orphan rows are deleted |
| 12 | /// (the surrounding Trip / Expense stays so other participants keep their history). |
| 13 | /// </summary> |
| 14 | public class UserDeletedEventHandler : IEventHandler<UserDeletedEvent> |
| 15 | { |
| 16 | private readonly TripsDbContext _trips; |
| 17 | private readonly ExpensesDbContext _expenses; |
| 18 | private readonly ILogger<UserDeletedEventHandler> _logger; |
| 19 | |
| 20 | public UserDeletedEventHandler( |
| 21 | TripsDbContext trips, |
| 22 | ExpensesDbContext expenses, |
| 23 | ILogger<UserDeletedEventHandler> logger) |
| 24 | { |
| 25 | _trips = trips; |
| 26 | _expenses = expenses; |
| 27 | _logger = logger; |
| 28 | } |
| 29 | |
| 30 | public async Task HandleAsync(UserDeletedEvent @event, CancellationToken cancellationToken) |
| 31 | { |
| 32 | _logger.LogInformation("Cascade-cleaning data for deleted user {UserId}", @event.UserId); |
| 33 | |
| 34 | var participants = await _trips.TripParticipants |
| 35 | .Where(p => p.UserId == @event.UserId) |
| 36 | .ToListAsync(cancellationToken); |
| 37 | _trips.TripParticipants.RemoveRange(participants); |
| 38 | |
| 39 | var splits = await _expenses.ExpenseSplits |
| 40 | .Where(s => s.UserId == @event.UserId) |
| 41 | .ToListAsync(cancellationToken); |
| 42 | _expenses.ExpenseSplits.RemoveRange(splits); |
| 43 | |
| 44 | await _trips.SaveChangesAsync(cancellationToken); |
| 45 | await _expenses.SaveChangesAsync(cancellationToken); |
| 46 | } |
| 47 | } |
| 48 | |