1
+ using Application . Core ;
2
+ using Application . Interfaces ;
3
+ using Domain ;
4
+ using MediatR ;
5
+ using Microsoft . EntityFrameworkCore ;
6
+ using Persistence ;
7
+
8
+ namespace Application . Activities
9
+ {
10
+ public class UpdateAttendance
11
+ {
12
+ public class Command : IRequest < Result < Unit > >
13
+ {
14
+ public Guid Id { get ; set ; }
15
+ }
16
+
17
+ public class Handler : IRequestHandler < Command , Result < Unit > >
18
+ {
19
+ private readonly DataContext _context ;
20
+ private readonly IUserAccessor _userAccessor ;
21
+ public Handler ( DataContext context , IUserAccessor userAccessor )
22
+ {
23
+ _userAccessor = userAccessor ;
24
+ _context = context ;
25
+ }
26
+
27
+ public async Task < Result < Unit > > Handle ( Command request , CancellationToken cancellationToken )
28
+ {
29
+ var activity = await _context . Activities
30
+ . Include ( a => a . Attendees ) . ThenInclude ( u => u . AppUser )
31
+ . SingleOrDefaultAsync ( x => x . Id == request . Id ) ;
32
+
33
+ if ( activity == null ) return null ;
34
+
35
+ var user = await _context . Users . FirstOrDefaultAsync ( x =>
36
+ x . UserName == _userAccessor . GetUserName ( ) ) ;
37
+
38
+ if ( user == null ) return null ;
39
+
40
+ var hostUserName = activity . Attendees . FirstOrDefault ( x => x . IsHost ) ? . AppUser ? . UserName ;
41
+
42
+ var attendance = activity . Attendees . FirstOrDefault ( x =>
43
+ x . AppUser . UserName == user . UserName ) ;
44
+
45
+ if ( attendance != null && hostUserName == user . UserName )
46
+ activity . IsCancelled = ! activity . IsCancelled ;
47
+
48
+ if ( attendance != null && hostUserName != user . UserName )
49
+ activity . Attendees . Remove ( attendance ) ;
50
+
51
+ if ( attendance == null )
52
+ {
53
+ attendance = new ActivityAttendee
54
+ {
55
+ AppUser = user ,
56
+ Activity = activity ,
57
+ IsHost = false
58
+ } ;
59
+
60
+ activity . Attendees . Add ( attendance ) ;
61
+ }
62
+ var result = await _context . SaveChangesAsync ( ) > 0 ;
63
+
64
+ return result ? Result < Unit > . Success ( Unit . Value ) :
65
+ Result < Unit > . Failure ( "Problem updating attendance" ) ;
66
+ }
67
+ }
68
+ }
69
+ }
0 commit comments