-
-
Notifications
You must be signed in to change notification settings - Fork 345
/
Attendance.SaveHook.cs
291 lines (251 loc) · 13.1 KB
/
Attendance.SaveHook.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// <copyright>
// Copyright by the Spark Development Network
//
// Licensed under the Rock Community License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.rockrms.com/license
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Linq;
using Rock.Data;
using Rock.Tasks;
using Rock.Transactions;
using Rock.Web.Cache;
namespace Rock.Model
{
public partial class Attendance
{
/// <summary>
/// Save hook implementation for <see cref="Attendance"/>.
/// </summary>
/// <seealso cref="Rock.Data.EntitySaveHook{TEntity}" />
internal class SaveHook : EntitySaveHook<Attendance>
{
/// <summary>
/// Changes to the Person's Attendance's Group, Schedule or Location
/// </summary>
/// <value>The person attendance history change list.</value>
private History.HistoryChangeList PersonAttendanceHistoryChangeList { get; set; }
private int? preSavePersonAliasId { get; set; }
private bool previousDidAttendValue { get; set; }
/// <summary>
/// Method that will be called on an entity immediately before the item is saved by context
/// </summary>
protected override void PreSave()
{
PersonAttendanceHistoryChangeList = new History.HistoryChangeList();
_isDeleted = State == EntityContextState.Deleted;
bool previouslyDeclined;
if ( State == EntityContextState.Added )
{
previousDidAttendValue = false;
previouslyDeclined = false;
}
else
{
// get original values so we can detect whether the value changed
previousDidAttendValue = ( bool? )Entry.OriginalValues.GetReadOnlyValueOrDefault( "DidAttend", false ) == true;
previouslyDeclined = ( Entry.OriginalValues.GetReadOnlyValueOrDefault( "RSVP", null ) as RSVP? ) == RSVP.No;
}
// if the record was changed to Declined, queue a GroupScheduleCancellationTransaction in PostSaveChanges
_declinedScheduledAttendance = ( previouslyDeclined == false ) && Entity.IsScheduledPersonDeclined();
/*
06/21/2023 ETD
Launch the workflow in post save to avoid a race condition between the bus message and the saving of the Attendance record.
The LaunchMemberAttendedGroupWorkflow needs to be run post save to work correctly.
if ( previousDidAttendValue == false && Entity.DidAttend == true )
{
var launchMemberAttendedGroupWorkflowMsg = GetLaunchMemberAttendedGroupWorkflowMessage();
launchMemberAttendedGroupWorkflowMsg.Send();
}
*/
var attendance = this.Entity;
if ( State == EntityContextState.Modified )
{
preSavePersonAliasId = attendance.PersonAliasId;
var originalOccurrenceId = ( int? ) OriginalValues[nameof( attendance.OccurrenceId )];
if ( originalOccurrenceId.HasValue && attendance.OccurrenceId != originalOccurrenceId.Value )
{
var attendanceOccurrenceService = new AttendanceOccurrenceService( this.RockContext );
var originalOccurrence = attendanceOccurrenceService.GetNoTracking( originalOccurrenceId.Value );
var currentOccurrence = attendanceOccurrenceService.GetNoTracking( attendance.OccurrenceId );
if ( originalOccurrence != null && currentOccurrence != null )
{
if ( originalOccurrence.GroupId != currentOccurrence.GroupId )
{
History.EvaluateChange( PersonAttendanceHistoryChangeList, "Group", originalOccurrence.Group?.Name, currentOccurrence.Group?.Name );
}
if ( originalOccurrence.ScheduleId.HasValue && currentOccurrence.ScheduleId.HasValue && originalOccurrence.ScheduleId.Value != currentOccurrence.ScheduleId.Value )
{
History.EvaluateChange( PersonAttendanceHistoryChangeList, "Schedule", NamedScheduleCache.Get( originalOccurrence.ScheduleId.Value )?.Name, NamedScheduleCache.Get( currentOccurrence.ScheduleId.Value )?.Name );
}
if ( originalOccurrence.LocationId.HasValue && currentOccurrence.LocationId.HasValue && originalOccurrence.LocationId.Value != currentOccurrence.LocationId.Value )
{
History.EvaluateChange( PersonAttendanceHistoryChangeList, "Location", NamedLocationCache.Get( originalOccurrence.LocationId.Value )?.Name, NamedLocationCache.Get( currentOccurrence.LocationId.Value )?.Name );
}
}
}
}
else if ( State == EntityContextState.Deleted )
{
preSavePersonAliasId = ( int? ) OriginalValues[nameof( attendance.PersonAliasId )];
PersonAttendanceHistoryChangeList.AddChange( History.HistoryVerb.Delete, History.HistoryChangeType.Record, "Attendance" );
}
// If we need to send a real-time notification then do so after
// this change has been committed to the database.
if ( ShouldSendRealTimeMessage() )
{
RockContext.ExecuteAfterCommit( () =>
{
// Use the fast queue for this because it is real-time.
new SendAttendanceRealTimeNotificationsTransaction( Entity.Guid, State == EntityContextState.Deleted ).Enqueue( true );
} );
}
base.PreSave();
}
private bool _declinedScheduledAttendance = false;
private bool _isDeleted = false;
/// <summary>
/// Method that will be called on an entity immediately after the item is saved by context
/// </summary>
/// <remarks>
/// This method is only called if <see cref="M:Rock.Data.EntitySaveHook`1.PreSave" /> returns
/// without error.
/// </remarks>
protected override void PostSave()
{
if ( _declinedScheduledAttendance )
{
new LaunchGroupScheduleCancellationWorkflow.Message()
{
AttendanceId = Entity.Id
}.Send();
}
if ( !_isDeleted )
{
// Process any streaks that may occur as a result of adding/modifying an attendance record.
// If there are any, they need to be processed in this thread in case there are any achievement changes
// that need to be detected as a result of this attendance.
StreakTypeService.HandleAttendanceRecord( Entity.Id );
}
// Do this in post save to avoid a race condition between the bus message and the saving of the Attendance record. See engineering note in PreSave().
if ( previousDidAttendValue == false && Entity.DidAttend == true )
{
var launchMemberAttendedGroupWorkflowMsg = GetLaunchMemberAttendedGroupWorkflowMessage();
launchMemberAttendedGroupWorkflowMsg.Send();
}
var rockContext = ( RockContext ) this.RockContext;
if ( PersonAttendanceHistoryChangeList?.Any() == true )
{
var attendanceId = Entity.Id;
if ( preSavePersonAliasId.HasValue )
{
var attendeePersonId = new PersonAliasService( this.RockContext ).GetPersonId( preSavePersonAliasId.Value );
if ( attendeePersonId.HasValue )
{
var entityTypeType = typeof( Person );
var relatedEntityTypeType = typeof( Attendance );
HistoryService.SaveChanges(
rockContext,
entityTypeType,
Rock.SystemGuid.Category.HISTORY_ATTENDANCE_CHANGES.AsGuid(),
attendeePersonId.Value,
this.PersonAttendanceHistoryChangeList,
$"Attendance {attendanceId}",
relatedEntityTypeType,
attendanceId,
true,
Entity.ModifiedByPersonAliasId,
rockContext.SourceOfChange );
}
}
}
base.PostSave();
}
/// <summary>
/// Determines if we need to send any real-time messages for the
/// changes made to this entity.
/// </summary>
/// <returns><c>true</c> if a message should be sent, <c>false</c> otherwise.</returns>
private bool ShouldSendRealTimeMessage()
{
if ( !RockContext.IsRealTimeEnabled )
{
return false;
}
if ( PreSaveState == EntityContextState.Added )
{
return true;
}
else if ( PreSaveState == EntityContextState.Modified )
{
if ( ( Entity.DidAttend ?? false ) != ( ( ( bool? ) OriginalValues[nameof( Entity.DidAttend )] ) ?? false ) )
{
return true;
}
else if ( Entity.RSVP != ( RSVP ) OriginalValues[nameof( Entity.RSVP )] )
{
return true;
}
else if ( Entity.PresentDateTime != ( DateTime? ) OriginalValues[nameof( Entity.PresentDateTime )] )
{
return true;
}
}
else if ( PreSaveState == EntityContextState.Deleted )
{
return true;
}
return false;
}
private LaunchMemberAttendedGroupWorkflow.Message GetLaunchMemberAttendedGroupWorkflowMessage()
{
var launchMemberAttendedGroupWorkflowMsg = new LaunchMemberAttendedGroupWorkflow.Message();
if ( State == EntityContextState.Deleted )
{
return launchMemberAttendedGroupWorkflowMsg;
}
// Get the attendance record
var attendance = Entity as Attendance;
// If attendance record is not valid or the DidAttend is false
if ( attendance == null || ( attendance.DidAttend.GetValueOrDefault( false ) == false ) )
{
return launchMemberAttendedGroupWorkflowMsg;
}
// Save for all adds
bool valid = State == EntityContextState.Added;
// If not an add, check previous DidAttend value
if ( !valid )
{
// Only use changes where DidAttend was previously not true
valid = ( bool? ) Entry.OriginalValues.GetReadOnlyValueOrDefault( "DidAttend", false ) != true;
}
if ( valid )
{
var occ = attendance.Occurrence ?? new AttendanceOccurrenceService( new RockContext() ).Get( attendance.OccurrenceId );
if ( occ != null )
{
// Save the values
launchMemberAttendedGroupWorkflowMsg.GroupId = occ.GroupId;
launchMemberAttendedGroupWorkflowMsg.AttendanceDateTime = occ.OccurrenceDate;
launchMemberAttendedGroupWorkflowMsg.PersonAliasId = attendance.PersonAliasId;
launchMemberAttendedGroupWorkflowMsg.AttendanceId = attendance.Id;
if ( occ.Group != null )
{
launchMemberAttendedGroupWorkflowMsg.GroupTypeId = occ.Group.GroupTypeId;
}
}
}
return launchMemberAttendedGroupWorkflowMsg;
}
}
}
}