-
-
Notifications
You must be signed in to change notification settings - Fork 345
/
SignUpFinder.cs
1857 lines (1552 loc) · 84.4 KB
/
SignUpFinder.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// <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.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Data.Entity.Spatial;
using System.Linq;
using System.Linq.Expressions;
using Rock.Attribute;
using Rock.Data;
using Rock.Field.Types;
using Rock.Model;
using Rock.Reporting;
using Rock.Utility;
using Rock.ViewModels.Blocks;
using Rock.ViewModels.Blocks.Engagement.SignUp.SignUpFinder;
using Rock.ViewModels.Cms;
using Rock.ViewModels.Utility;
using Rock.Web.Cache;
using Rock.Web.UI;
using Rock.Web.UI.Controls;
namespace Rock.Blocks.Engagement.SignUp
{
/// <summary>
/// Block used for finding a sign-up group/project.
/// </summary>
/// <seealso cref="Rock.Blocks.RockBlockType" />
/// <seealso cref="Rock.Blocks.IHasCustomActions" />
[DisplayName( "Sign-Up Finder" )]
[Category( "Engagement > Sign-Up" )]
[Description( "Block used for finding a sign-up group/project." )]
[IconCssClass( "fa fa-clipboard-check" )]
[SupportedSiteTypes( Model.SiteType.Web )]
[ContextAware( typeof( Campus ) )]
#region Block Attributes
#region Layout / Initial Page Load
[BooleanField( "Hide Overcapacity Projects",
Key = AttributeKey.HideOvercapacityProjects,
Description = "Determines if projects that are full should be shown.",
Category = AttributeCategory.CustomSetting,
ControlType = BooleanFieldType.BooleanControlType.Checkbox,
DefaultBooleanValue = false,
IsRequired = false )]
[BooleanField( "Load Results on Initial Page Load",
Key = AttributeKey.LoadResultsOnInitialPageLoad,
Description = "When enabled the project finder will load with all configured projects (no filters enabled).",
Category = AttributeCategory.CustomSetting,
ControlType = BooleanFieldType.BooleanControlType.Checkbox,
DefaultBooleanValue = true,
IsRequired = false )]
[CustomDropdownListField( "Display Project Filters As",
Key = AttributeKey.DisplayProjectFiltersAs,
Description = @"Determines if the ""Project Types"", ""Campus"", and ""Named Schedule"" project filters should be shown as checkboxes or multi-select dropdowns.",
Category = AttributeCategory.CustomSetting,
ListSource = "Checkboxes^Checkboxes,MultiSelectDropDown^Multi-Select Dropdown",
DefaultValue = "Checkboxes",
IsRequired = true )]
[CustomDropdownListField( "Filter Columns",
Key = AttributeKey.FilterColumns,
Description = "The number of columns the filters should be displayed as.",
Category = AttributeCategory.CustomSetting,
ListSource = "1,2,3,4",
DefaultValue = "1",
IsRequired = true )]
#endregion
#region Project Filters
[GroupTypesField( "Project Types",
Key = AttributeKey.ProjectTypes,
Description = "",
Category = AttributeCategory.CustomSetting,
DefaultValue = Rock.SystemGuid.GroupType.GROUPTYPE_SIGNUP_GROUP,
IsRequired = true )]
[TextField( "Project Type Filter Label",
Key = AttributeKey.ProjectTypeFilterLabel,
Description = "The label to use for the project type filter.",
Category = AttributeCategory.CustomSetting,
DefaultValue = "Project Type",
IsRequired = true )]
[AttributeField( "Display Attribute Filters",
Key = AttributeKey.DisplayAttributeFilters,
Description = "The group attributes that should be available for an individual to filter the results by.",
Category = AttributeCategory.CustomSetting,
EntityTypeGuid = Rock.SystemGuid.EntityType.GROUP,
AllowMultiple = true,
IsRequired = false )]
#endregion
#region Campus Filters
[BooleanField( "Display Campus Filter",
Key = AttributeKey.DisplayCampusFilter,
Description = "Determines if the campus filter should be shown. If there is only one active campus to display then this filter will not be shown, even if enabled.",
Category = AttributeCategory.CustomSetting,
ControlType = BooleanFieldType.BooleanControlType.Checkbox,
DefaultBooleanValue = false,
IsRequired = false )]
[BooleanField( "Enable Campus Context",
Key = AttributeKey.EnableCampusContext,
Description = "If the page has a campus context, its value will be used as a filter.",
Category = AttributeCategory.CustomSetting,
ControlType = BooleanFieldType.BooleanControlType.Checkbox,
DefaultBooleanValue = false,
IsRequired = false )]
[DefinedValueField( "Campus Types",
Key = AttributeKey.CampusTypes,
Description = "The types of campuses to include in the campus list.",
Category = AttributeCategory.CustomSetting,
DefinedTypeGuid = Rock.SystemGuid.DefinedType.CAMPUS_TYPE,
AllowMultiple = true,
IsRequired = false )]
[DefinedValueField( "Campus Statuses",
Key = AttributeKey.CampusStatuses,
Description = "The statuses of the campuses to include in the campus list.",
Category = AttributeCategory.CustomSetting,
DefinedTypeGuid = Rock.SystemGuid.DefinedType.CAMPUS_STATUS,
AllowMultiple = true,
IsRequired = false )]
#endregion
#region Schedule Filters
[BooleanField( "Display Named Schedule Filter",
Key = AttributeKey.DisplayNamedScheduleFilter,
Description = "When enabled a list of named schedules will be show as a filter.",
Category = AttributeCategory.CustomSetting,
ControlType = BooleanFieldType.BooleanControlType.Checkbox,
DefaultBooleanValue = false,
IsRequired = false )]
[TextField( "Named Schedule Filter Label",
Key = AttributeKey.NamedScheduleFilterLabel,
Description = "The label to use for the named schedule filter.",
Category = AttributeCategory.CustomSetting,
DefaultValue = "Schedules",
IsRequired = true )]
[CategoryField( "Root Schedule Category",
Key = AttributeKey.RootScheduleCategory,
Description = "When displaying the named schedule filter this will serve to filter which named schedules to show. Only direct descendants of this root schedule category will be displayed.",
Category = AttributeCategory.CustomSetting,
EntityTypeName = "Rock.Model.Schedule",
IsRequired = false )]
#endregion
#region Location Filters
[BooleanField( "Display Location Sort",
Key = AttributeKey.DisplayLocationSort,
Description = "Determines if the location sort field should be shown.",
Category = AttributeCategory.CustomSetting,
ControlType = BooleanFieldType.BooleanControlType.Checkbox,
DefaultBooleanValue = true,
IsRequired = false )]
[TextField( "Location Sort Label",
Key = AttributeKey.LocationSortLabel,
Description = "The label to use for the location sort filter.",
Category = AttributeCategory.CustomSetting,
DefaultValue = "Location (City, State or Zip Code)",
IsRequired = true )]
[BooleanField( "Display Location Range Filter",
Key = AttributeKey.DisplayLocationRangeFilter,
Description = "When enabled a filter will be shown to limit results to a specified number of miles from the location selected or their mailing address if logged in. If the Location Sort entry is not enabled to be shown and the individual is not logged in then this filter will not be shown, even if enabled, as we will not be able to honor the filter.",
Category = AttributeCategory.CustomSetting,
ControlType = BooleanFieldType.BooleanControlType.Checkbox,
DefaultBooleanValue = true,
IsRequired = false )]
#endregion
#region Additional Filters
[BooleanField( "Display Date Range",
Key = AttributeKey.DisplayDateRange,
Description = "When enabled, individuals would be able to filter the results by projects occurring inside the provided date range.",
Category = AttributeCategory.CustomSetting,
ControlType = BooleanFieldType.BooleanControlType.Checkbox,
DefaultBooleanValue = true,
IsRequired = false )]
[BooleanField( "Display Slots Available Filter",
Key = AttributeKey.DisplaySlotsAvailableFilter,
Description = @"When enabled allows the individual to find projects with ""at least"" or ""no more than"" the provided spots available.",
Category = AttributeCategory.CustomSetting,
ControlType = BooleanFieldType.BooleanControlType.Checkbox,
DefaultBooleanValue = true,
IsRequired = false )]
#endregion
#region Lava
[CodeEditorField( "Results Lava Template",
Key = AttributeKey.ResultsLavaTemplate,
Description = "The Lava template to use to show the results of the search. Merge fields include: Projects. <span class='tip tip-lava'></span>",
Category = AttributeCategory.CustomSetting,
EditorMode = CodeEditorMode.Lava,
EditorHeight = 400,
DefaultValue = AttributeDefault.ResultsLavaTemplate,
IsRequired = true )]
[CodeEditorField( "Results Header Lava Template",
Key = AttributeKey.ResultsHeaderLavaTemplate,
Description = "The Lava Template to use to show the results header.",
Category = AttributeCategory.CustomSetting,
EditorMode = CodeEditorMode.Lava,
EditorHeight = 400,
DefaultValue = AttributeDefault.ResultsHeaderLavaTemplate,
IsRequired = false )]
#endregion
#region Linked Pages
[LinkedPage( "Project Detail Page",
Key = AttributeKey.ProjectDetailPage,
Description = "The page reference to pass to the Lava template for the details of the project.",
Category = AttributeCategory.CustomSetting,
IsRequired = true )]
[LinkedPage( "Registration Page",
Key = AttributeKey.RegistrationPage,
Description = "The page reference to pass to the Lava template for the registration page.",
Category = AttributeCategory.CustomSetting,
IsRequired = true )]
#endregion
#endregion
[Rock.SystemGuid.EntityTypeGuid( "BF09747C-786D-4979-BADF-2D0157F4CB21" )]
[Rock.SystemGuid.BlockTypeGuid( "74A20402-00DF-4A87-98D1-B5A8920F1D32" )]
public class SignUpFinder : RockBlockType, IHasCustomActions
{
#region Keys & Constants
private static class AttributeKey
{
// Layout / Initial Page Load.
public const string HideOvercapacityProjects = "HideOvercapacityProjects";
public const string LoadResultsOnInitialPageLoad = "LoadResultsOnInitialPageLoad";
public const string DisplayProjectFiltersAs = "DisplayProjectFiltersAs";
public const string FilterColumns = "FilterColumns";
// Project Filters.
public const string ProjectTypes = "ProjectTypes";
public const string ProjectTypeFilterLabel = "ProjectTypeFilterLabel";
// Campus Filters.
public const string DisplayCampusFilter = "DisplayCampusFilter";
public const string EnableCampusContext = "EnableCampusContext";
public const string CampusTypes = "CampusTypes";
public const string CampusStatuses = "CampusStatuses";
// Schedule Filters.
public const string DisplayNamedScheduleFilter = "DisplayNamedScheduleFilter";
public const string NamedScheduleFilterLabel = "NamedScheduleFilterLabel";
public const string RootScheduleCategory = "RootScheduleCategory";
// Location Filters.
public const string DisplayLocationSort = "DisplayLocationSort";
public const string LocationSortLabel = "LocationSortLabel";
public const string DisplayLocationRangeFilter = "DisplayLocationRangeFilter";
// Additional Filters.
public const string DisplayDateRange = "DisplayDateRange";
public const string DisplaySlotsAvailableFilter = "DisplaySlotsAvailableFilter";
public const string DisplayAttributeFilters = "DisplayAttributeFilters";
// Lava.
public const string ResultsLavaTemplate = "ResultsLavaTemplate";
public const string ResultsHeaderLavaTemplate = "ResultsHeaderLavaTemplate";
// Linked Pages.
public const string ProjectDetailPage = "ProjectDetailPage";
public const string RegistrationPage = "RegistrationPage";
}
private static class AttributeCategory
{
public const string CustomSetting = "CustomSetting";
}
private static class AttributeDefault
{
public const string ResultsLavaTemplate = @"{% assign projectCount = Projects | Size %}
{% if projectCount > 0 %}
<div class=""row d-flex flex-wrap"">
{% for project in Projects %}
<div class=""col-xs-12 col-sm-6 col-md-4 mb-4"">
<div class=""card h-100"">
<div class=""card-body"">
<h3 class=""card-title mt-0"">{{ project.Name }}</h3>
{% if project.ScheduleName and project.ScheduleName != empty %}
<p class=""card-subtitle text-muted mb-3"">{{ project.ScheduleName }}</p>
{% endif %}
<p class=""mb-2"">{{ project.FriendlySchedule }}</p>
<div class=""d-flex justify-content-between mb-3"">
{% if project.AvailableSpots != null %}
<span class=""badge badge-info"">Available Spots: {{ project.AvailableSpots }}</span>
{% else %}
{% endif %}
{% if project.DistanceInMiles != null %}
<span class=""badge"">{{ project.DistanceInMiles | Format:'0.0' }} miles<span>
{% else %}
{% endif %}
</div>
{% if project.MapCenter and project.MapCenter != empty %}
<div class=""mb-3"">
{[ googlestaticmap center:'{{ project.MapCenter }}' zoom:'15' ]}
{[ endgooglestaticmap ]}
</div>
{% endif %}
{% if project.Description and project.Description != empty %}
<p class=""card-text"">
{{ project.Description }}
</p>
{% endif %}
</div>
<div class=""card-footer bg-white border-0"">
{% if project.ShowRegisterButton %}
<a href=""{{ project.RegisterPageUrl }}"" class=""btn btn-primary btn-xs"">Register</a>
{% endif %}
<a href=""{{ project.ProjectDetailPageUrl }}"" class=""btn btn-link btn-xs"">Details</a>
</div>
</div>
</div>
{% endfor %}
</div>
{% else %}
<div>
No projects found.
</div>
{% endif %}";
public const string ResultsHeaderLavaTemplate = @"<h3>Results</h3>
<p>Below is a listing of the projects that match your search results.</p>
<hr>";
}
private static class FilterDisplayType
{
public const string Checkboxes = "Checkboxes";
public const string MultiSelectDropDown = "MultiSelectDropDown";
}
private static class SlotsAvailableComparisonType
{
public const string AtLeast = "AtLeast";
public const string NoMoreThan = "NoMoreThan";
}
private static class PageParameterKey
{
public const string ProjectId = "ProjectId";
public const string LocationId = "LocationId";
public const string ScheduleId = "ScheduleId";
}
#endregion
#region Fields
private List<ListItemBag> _projectTypeFilterItems;
#endregion
#region Properties
public bool IsAuthenticated
{
get
{
return this.RequestContext.CurrentUser?.IsAuthenticated == true;
}
}
#endregion
#region Methods
/// <inheritdoc/>
public override object GetObsidianBlockInitialization()
{
using ( var rockContext = new RockContext() )
{
var box = new SignUpFinderInitializationBox();
SetBoxInitialState( box, rockContext );
return box;
}
}
/// <summary>
/// Sets the initial state of the box.
/// </summary>
/// <param name="box">The box.</param>
/// <param name="rockContext">The rock context.</param>
private void SetBoxInitialState( SignUpFinderInitializationBox box, RockContext rockContext )
{
var block = new BlockService( rockContext ).Get( this.BlockId );
block.LoadAttributes( rockContext );
box.LoadResultsOnInitialPageLoad = GetAttributeValue( AttributeKey.LoadResultsOnInitialPageLoad ).AsBoolean();
box.DisplayProjectFiltersAs = GetAttributeValue( AttributeKey.DisplayProjectFiltersAs );
box.FilterColumns = GetAttributeValue( AttributeKey.FilterColumns ).ToIntSafe();
box.ProjectTypes = GetShouldDisplayProjectTypeFilter() ? GetProjectTypeFilterItems() : new List<ListItemBag>();
box.ProjectTypeFilterLabel = GetAttributeValue( AttributeKey.ProjectTypeFilterLabel );
box.Campuses = GetCampusFilterItems();
box.PageCampusContext = GetPageCampusContext();
box.NamedSchedules = GetNamedScheduleFilterItems( rockContext );
box.NamedScheduleFilterLabel = GetAttributeValue( AttributeKey.NamedScheduleFilterLabel );
box.AttributesByProjectType = GetAttributeFilterItems( rockContext );
box.DisplayDateRange = GetAttributeValue( AttributeKey.DisplayDateRange ).AsBoolean();
box.DisplayLocationSort = GetAttributeValue( AttributeKey.DisplayLocationSort ).AsBoolean();
box.LocationSortLabel = GetAttributeValue( AttributeKey.LocationSortLabel );
box.DisplayLocationRangeFilter = GetShouldDisplayLocationRangeFilter();
box.DisplaySlotsAvailableFilter = GetAttributeValue( AttributeKey.DisplaySlotsAvailableFilter ).AsBoolean();
}
/// <summary>
/// Gets whether the project type filter should be displayed.
/// </summary>
/// <returns>Whether the project type filter should be displayed.</returns>
private bool GetShouldDisplayProjectTypeFilter()
{
return GetProjectTypeFilterItems().Count > 1;
}
/// <summary>
/// Gets the sign-up project group types that should be presented as filter items for the search.
/// </summary>
/// <returns>The sign-up project group types that should be presented as filter items for the search.</returns>
private List<ListItemBag> GetProjectTypeFilterItems()
{
if ( _projectTypeFilterItems != null )
{
return _projectTypeFilterItems;
}
_projectTypeFilterItems = GetAttributeValue( AttributeKey.ProjectTypes ).GroupTypeGuidsToListItemBagList();
return _projectTypeFilterItems;
}
/// <summary>
/// Gets the campuses that should be presented as filter items for the search.
/// </summary>
/// <returns>The campuses that should be presented as filter items for the search.</returns>
private List<ListItemBag> GetCampusFilterItems()
{
if ( !GetAttributeValue( AttributeKey.DisplayCampusFilter ).AsBoolean() )
{
return new List<ListItemBag>();
}
var campusCaches = CampusCache
.All()
.Where( c => c.IsActive.HasValue && c.IsActive.Value )
.ToList();
var campusTypeIds = GetIds( GetAttributeValue( AttributeKey.CampusTypes ).SplitDelimitedValues( "," ), DefinedValueCache.GetId );
if ( campusTypeIds.Any() )
{
campusCaches = campusCaches
.Where( c => c.CampusTypeValueId.HasValue && campusTypeIds.Contains( c.CampusTypeValueId.Value ) )
.ToList();
}
if ( !campusCaches.Any() )
{
return new List<ListItemBag>();
}
var campusStatusIds = GetIds( GetAttributeValue( AttributeKey.CampusStatuses ).SplitDelimitedValues( "," ), DefinedValueCache.GetId );
if ( campusStatusIds.Any() )
{
campusCaches = campusCaches
.Where( c => c.CampusStatusValueId.HasValue && campusStatusIds.Contains( c.CampusStatusValueId.Value ) )
.ToList();
}
if ( campusCaches.Count == 1 )
{
// Only display campus filter if there is more than one campus.
return new List<ListItemBag>();
}
return campusCaches.ToListItemBagList();
}
/// <summary>
/// Gets the <see cref="IEntity.Id"/>s for the supplied guid strings, using the specified function.
/// </summary>
/// <param name="entityGuidStrings">The <see cref="IEntity"/> guid string collection.</param>
/// <param name="getEntityIdFunc">The function to use to get the <see cref="IEntity"/> IDs using the guid strings.</param>
/// <param name="allowedListItems">
/// The optional list of allowed items that will be used to refine the list of <paramref name="entityGuidStrings"/>.
/// <para>
/// This should be used to ensure that requests originating from the client don't pass more guid strings than they're authorized to pass.
/// </para>
/// </param>
/// <returns>The <see cref="IEntity"/> IDs.</returns>
private List<int> GetIds( IEnumerable<string> entityGuidStrings, Func<Guid, int?> getEntityIdFunc, List<ListItemBag> allowedListItems = null )
{
if ( entityGuidStrings?.Any() != true || getEntityIdFunc == null )
{
return new List<int>();
}
if ( allowedListItems?.Any() == true )
{
entityGuidStrings = entityGuidStrings.Where( a => allowedListItems.Any( i => i.Value == a ) );
}
return entityGuidStrings
.Select( a => a.AsGuidOrNull() )
.Where( a => a.HasValue )
.Select( a => getEntityIdFunc( a.Value ) )
.Where( a => a.HasValue )
.Select( a => a.Value )
.ToList();
}
/// <summary>
/// Gets the page campus context, if enabled and defined.
/// </summary>
/// <returns>The page campus context, if enabled and defined.</returns>
private ListItemBag GetPageCampusContext()
{
if ( !GetAttributeValue( AttributeKey.EnableCampusContext ).AsBoolean() )
{
return null;
}
var pageContextCampus = this.RequestContext.GetContextEntity<Campus>();
if ( pageContextCampus == null )
{
return null;
}
return pageContextCampus.ToListItemBag();
}
/// <summary>
/// Gets the named schedules that should be presented as filter items for the search.
/// </summary>
/// <returns>The named schedules that should be presented as filter items for the search.</returns>
private List<ListItemBag> GetNamedScheduleFilterItems( RockContext rockContext )
{
if ( !GetAttributeValue( AttributeKey.DisplayNamedScheduleFilter ).AsBoolean() )
{
return new List<ListItemBag>();
}
// ScheduleService is used instead of the NamedScheduleCache because we want ToFriendlyScheduleText to return
// the condensed values instead of HTML formatted values when the Schedule has multiple dates.
var query = new ScheduleService( rockContext ).Queryable();
var rootScheduleCategoryGuid = GetAttributeValue( AttributeKey.RootScheduleCategory ).AsGuidOrNull();
if ( rootScheduleCategoryGuid.HasValue )
{
var rootScheduleCategoryId = CategoryCache.GetId( rootScheduleCategoryGuid.Value );
if ( rootScheduleCategoryId.HasValue )
{
query = query.Where( a => a.CategoryId.HasValue && a.CategoryId.Value == rootScheduleCategoryId.Value && a.IsActive );
}
}
return ToListItemBagList( query.ToList() );
}
/// <summary>
/// Converts the schedules to a List of ListItemBags. Used instead of the ToListItemBagList() extension method because
/// the extension method uses the FriendlyScheduleTex value of the Schedule which does not return the condensed value
/// by default and as a result contains HTML string if the schedule has multiple dates.
/// </summary>
/// <param name="namedSchedules">The named schedules.</param>
/// <returns></returns>
private List<ListItemBag> ToListItemBagList( List<Schedule> namedSchedules )
{
var items = namedSchedules.Select( a => new ListItemBag()
{
Text = a.ToFriendlyScheduleText( true ),
Value = a.Guid.ToString()
} );
return items.ToList();
}
/// <summary>
/// Gets the display attribute filter guids that should be used to build attribute filter items for the search.
/// </summary>
/// <returns>The display attribute filter guids that should be used to build attribute filter items for the search.</returns>
private List<Guid> GetDisplayAttributeFilterGuids()
{
return GetAttributeValue( AttributeKey.DisplayAttributeFilters )
.SplitDelimitedValues( "," )
.Select( a => a.AsGuidOrNull() )
.Where( a => a.HasValue )
.Select( a => a.Value )
.ToList();
}
/// <summary>
/// Gets the attributes that should be presented as filter items for the search, grouped by project type [guid].
/// </summary>
/// <param name="rockContext">The rock context.</param>
/// <param name="selectedProjectTypeGuidStrings">The optional, selected project type guid strings.</param>
/// <returns>The attributes that should be presented as filter items for the search, grouped by project type [guid].</returns>
private Dictionary<string, Dictionary<string, PublicAttributeBag>> GetAttributeFilterItems( RockContext rockContext, IEnumerable<string> selectedProjectTypeGuidStrings = null )
{
// Because [Attribute].[Key]s aren't guaranteed unique across entities, we need to maintain a separate collection
// of attribute filters per project [group] type.
// Also, because attributes can be inherited by child group types, we'll add a given attribute (by it's guid) only
// the first time we come across it.
var attributeFilterItemsByGroupTypeId = new Dictionary<string, Dictionary<string, PublicAttributeBag>>();
var attributeGuidsAlreadyAdded = new List<Guid>();
var displayAttributeFilterGuids = GetDisplayAttributeFilterGuids();
if ( !displayAttributeFilterGuids.Any() )
{
return attributeFilterItemsByGroupTypeId;
}
bool shouldAddAttribute( AttributeCache attributeCache )
{
if ( !displayAttributeFilterGuids.Contains( attributeCache.Guid ) )
{
return false;
}
if ( attributeGuidsAlreadyAdded.Contains( attributeCache.Guid ) )
{
return false;
}
attributeGuidsAlreadyAdded.Add( attributeCache.Guid );
return true;
}
foreach ( var projectType in GetProjectTypeFilterItems() )
{
var projectTypeGuidString = projectType.Value;
if ( selectedProjectTypeGuidStrings?.Any() == true
&& !selectedProjectTypeGuidStrings.Any( a => a == projectTypeGuidString ) )
{
// This project type was not selected by the individual performing the search; don't include its attributes.
continue;
}
var projectTypeGuid = projectType.Value.AsGuidOrNull();
if ( !projectTypeGuid.HasValue )
{
continue;
}
var projectTypeId = GroupTypeCache.GetId( projectTypeGuid.Value );
if ( !projectTypeId.HasValue )
{
continue;
}
var group = new Rock.Model.Group { GroupTypeId = projectTypeId.Value };
group.LoadAttributes( rockContext );
// Note that we're not enforcing security here, as the public-facing individual performing the search would most likely be restricted.
var attributeFilterItems = group.GetPublicAttributesForEdit( this.RequestContext.CurrentPerson, enforceSecurity: false, attributeFilter: shouldAddAttribute );
if ( attributeFilterItems.Any() )
{
attributeFilterItemsByGroupTypeId.Add( projectTypeGuidString, attributeFilterItems );
}
}
return attributeFilterItemsByGroupTypeId;
}
/// <summary>
/// Gets whether the location range filter should be displayed.
/// </summary>
/// <returns>Whether the location range filter should be displayed.</returns>
private bool GetShouldDisplayLocationRangeFilter()
{
// When enabled a filter will be show to limit results to a specified number of miles
// from the location selected or their mailing address if logged in. If the Location Sort
// entry is not enabled to be shown and the individual is not logged in then this filter
// will not be shown, even if enabled, as we will not be able to honor the filter.
if ( !GetAttributeValue( AttributeKey.DisplayLocationRangeFilter ).AsBoolean() )
{
return false;
}
var isLocationSortEnabled = GetAttributeValue( AttributeKey.DisplayLocationSort ).AsBoolean();
return isLocationSortEnabled || this.IsAuthenticated;
}
/// <summary>
/// Gets the available sign-up project opportunities, based on the selected filters.
/// </summary>
/// <param name="rockContext">The rock context.</param>
/// <param name="selectedFilters">The selected filters.</param>
/// <returns>A <see cref="Opportunity"/> list representing the available sign-up project opportunities.</returns>
private List<Opportunity> GetOpportunities( RockContext rockContext, SignUpFinderSelectedFiltersBag selectedFilters )
{
if ( selectedFilters == null )
{
return new List<Opportunity>();
}
var signUpGroupTypeId = GroupTypeCache.GetId( Rock.SystemGuid.GroupType.GROUPTYPE_SIGNUP_GROUP.AsGuid() ).ToIntSafe();
// Get the active opportunities (GroupLocationSchedules).
var qryGroupLocationSchedules = new GroupLocationService( rockContext )
.Queryable()
.AsNoTracking()
.Where( gl =>
gl.Group.IsActive
&& ( gl.Group.GroupTypeId == signUpGroupTypeId || gl.Group.GroupType.InheritedGroupTypeId == signUpGroupTypeId )
)
.SelectMany( gl => gl.Schedules, ( gl, s ) => new
{
gl.Group,
gl.Location,
Schedule = s,
Config = gl.GroupLocationScheduleConfigs.FirstOrDefault( glsc => glsc.ScheduleId == s.Id )
} );
// Filter by group types.
var selectedProjectTypeGuidStrings = selectedFilters.ProjectTypes;
var actualProjectTypeGuidStrings = GetProjectTypeFilterItems()
.Where( p => selectedProjectTypeGuidStrings?.Any() != true || selectedProjectTypeGuidStrings.Contains( p.Value ) )
.Select( p => p.Value );
var groupTypeIds = GetIds( actualProjectTypeGuidStrings, GroupTypeCache.GetId );
if ( groupTypeIds.Any() )
{
qryGroupLocationSchedules = qryGroupLocationSchedules
.Where( gls => groupTypeIds.Contains( gls.Group.GroupTypeId ) );
}
// Filter by campuses.
var campusIds = new List<int>();
if ( GetAttributeValue( AttributeKey.DisplayCampusFilter ).AsBoolean() )
{
campusIds = GetIds( selectedFilters.Campuses, CampusCache.GetId, GetCampusFilterItems() );
}
else if ( GetAttributeValue( AttributeKey.EnableCampusContext ).AsBoolean() )
{
var pageContextCampus = this.RequestContext.GetContextEntity<Campus>();
if ( pageContextCampus!= null )
{
campusIds.Add( pageContextCampus.Id );
}
}
if ( campusIds.Any() )
{
qryGroupLocationSchedules = qryGroupLocationSchedules
.Where( gls => gls.Group.CampusId.HasValue && campusIds.Contains( gls.Group.CampusId.Value ) );
}
// Filter by named schedules.
var namedScheduleIds = GetIds( selectedFilters.NamedSchedules, NamedScheduleCache.GetId, GetNamedScheduleFilterItems( rockContext ) );
if ( namedScheduleIds.Any() )
{
qryGroupLocationSchedules = qryGroupLocationSchedules
.Where( gls => namedScheduleIds.Contains( gls.Schedule.Id ) );
}
// Filter by attributes.
if ( selectedFilters.AttributeFiltersByProjectType.Any( kvp => kvp.Value.Any() ) )
{
/*
* 2/1/2023 - JPH
*
* Apply the selected attribute filters to the query, per project type.
*
* Note that this filtering approach can lead to some unexpected results for the individuals administering and performing these searches.
*
* --------
* Example:
* --------
* 1) Project Type A has a "Transportation is Provided" boolean attribute;
* 2) Project Type B doesn't have this attribute, and it has opportunities for which transportation is NOT provided;
* 3) Alisha Marble enables both of these project types for this block instance AND allows filtering against Project Type A's "Transportation is Provided" attribute;
* 4) A public-facing individual comes along and performs a search for projects where transportation is provided, but they unknowingly receive
* a list of results that include projects from Project Type A (where transportation is provided) AND Project Type B (where transportation
* is NOT provided). They might accidentally sign up for a project from Project Type B thinking that transportation will be provided for them.
*
* This is not ideal, but not a scenario we're solving for in V1 of this feature; we might circle back in the future to improve this experience.
*
* The challenge is that we cannot simply rule out the projects from Project Type B based on the presence of Project Type A's "Transportation is Provided"
* attribute; we can really only apply attribute filtering based on the project type to which a given attribute actually belongs, otherwise, we'd potentially
* never return any results to the individual in the above scenario (if we tried to apply attribute filters to project types to which they don't belong).
*/
var allowedProjectTypes = GetProjectTypeFilterItems();
var allowedAttributeGuids = GetDisplayAttributeFilterGuids();
var groupService = new GroupService( rockContext );
var parameterExpression = groupService.ParameterExpression;
var projectTypeExpressions = new List<Expression>();
foreach ( var attrFiltersByProjectType in selectedFilters.AttributeFiltersByProjectType )
{
var projectTypeGuidString = attrFiltersByProjectType.Key;
var attrFiltersDictionary = attrFiltersByProjectType.Value;
// Ensure this is an allowed project type.
var projectTypeIds = GetIds( new List<string> { projectTypeGuidString }, GroupTypeCache.GetId, allowedProjectTypes );
if ( projectTypeIds.Count != 1 )
{
// We didn't find a [GroupType].[Id] for this guid string; it must not be valid or allowed.
continue;
}
var projectTypeId = projectTypeIds.First();
Expression projectTypeExpression = null;
foreach ( var attrFilter in attrFiltersDictionary )
{
var attributeGuid = attrFilter.Key.AsGuidOrNull();
PublicComparisonValueBag filter = attrFilter.Value;
if ( !attributeGuid.HasValue || !allowedAttributeGuids.Contains( attributeGuid.Value ) )
{
// This attribute either isn't value or allowed.
continue;
}
var attributeCache = AttributeCache.Get( attributeGuid.Value );
var entityField = EntityHelper.GetEntityFieldForAttribute( attributeCache, false );
var values = new List<string>
{
filter.ComparisonType.ToString(),
PublicAttributeHelper.GetPrivateValue( attributeCache, filter.Value )
};
// Get the expression for this attribute filter.
var filterExpression = ExpressionHelper.GetAttributeExpression( groupService, parameterExpression, entityField, values );
// Combine it with expressions for any other selected filters tied to this project type.
projectTypeExpression = projectTypeExpression == null
? filterExpression
: Expression.And( projectTypeExpression, filterExpression );
}
if ( projectTypeExpression != null )
{
projectTypeExpressions.Add( projectTypeExpression );
}
}
if ( projectTypeExpressions.Any() )
{
var groupQry = groupService
.Queryable()
.AsNoTracking();
if ( projectTypeExpressions.Count == 1 )
{
groupQry = groupQry.Where( parameterExpression, projectTypeExpressions.First() );
}
else
{
var expression = projectTypeExpressions.First();
for ( int i = 1; i < projectTypeExpressions.Count; i++ )
{
expression = Expression.Or( expression, projectTypeExpressions[i] );
}
groupQry = groupQry.Where( parameterExpression, expression );
}
qryGroupLocationSchedules = qryGroupLocationSchedules
.Where( gls => groupQry.Any( g => gls.Group.Id == g.Id ) );
}
}
// Filter by date range.
DateTime fromDateTime = RockDateTime.Now;
DateTime? toDateTime = null;
if ( ( selectedFilters.StartDate.HasValue || selectedFilters.EndDate.HasValue )
&& GetAttributeValue( AttributeKey.DisplayDateRange ).AsBoolean() )
{
// This block shouldn't display past opportunities, since its goal is to get individuals to sign up.
if ( selectedFilters.StartDate.HasValue && selectedFilters.StartDate.Value > fromDateTime )
{
fromDateTime = selectedFilters.StartDate.Value.DateTime;
}
if ( selectedFilters.EndDate.HasValue )
{
// Set this to the end of the selected day to perform a search fully-inclusive of the day the individual
// selected. Note also that we cannot apply this filter during the query phase; we need to wait until we
// materialize Schedule objects so we can compare this value to Schedule.NextStartDateTime, which is a
// runtime-calculated value. If we instead applied this filter to the Schedule.EffectiveEndDate, we could
// accidentally rule out opportunities for which the individual might otherwise be interested in signing up.
// We'll apply this filter value below.
toDateTime = selectedFilters.EndDate.Value.DateTime.EndOfDay();
}
}
// Get just the date portion of the "from" date so we can compare it against the stored Schedules' EffectiveEndDates, which hold
// only a date value (without the time component). Return any Schedules whose EffectiveEndDate:
// 1) is not defined (this should never happen, but get them just in case), OR
// 2) is greater than or equal to the "from" date being filtered against.
//
// We'll do this to rule out any Schedules that have already ended, therefore making the initial results record set smaller,
// since we still have to do additional Schedule-based filtering below: once we materialize the Schedule objects, we'll use their
// runtime-calculated "Start[Date]Time" properties and methods to ensure we're only showing Schedules that actually qualify to
// be shown, based on the DateTime filter criteria provided to this method (either RockDateTime.Now OR the "from" date selected
// by the individual performing the search).
DateTime fromDate = fromDateTime.Date;
qryGroupLocationSchedules = qryGroupLocationSchedules
.Where( gls => !gls.Schedule.EffectiveEndDate.HasValue || gls.Schedule.EffectiveEndDate >= fromDate );
// Get all participant counts for all filtered opportunities; we'll hook them up to their respective opportunities below.
var participantCounts = new GroupMemberAssignmentService( rockContext )
.Queryable()
.AsNoTracking()
.Where( gma =>
!gma.GroupMember.Person.IsDeceased
&& qryGroupLocationSchedules.Any( gls =>
gls.Group.Id == gma.GroupMember.GroupId
&& gls.Location.Id == gma.LocationId
&& gls.Schedule.Id == gma.ScheduleId
)
)
.GroupBy( gma => new
{
gma.GroupMember.GroupId,
gma.LocationId,
gma.ScheduleId
} )
.Select( g => new
{
g.Key.GroupId,
g.Key.LocationId,
g.Key.ScheduleId,
Count = g.Count()
} )
.ToList();
var opportunities = qryGroupLocationSchedules
.ToList() // Execute the query; we have additional filtering that needs to happen once we materialize these objects.
.Select( gls =>
{
var participantCount = participantCounts.FirstOrDefault( c =>
c.GroupId == gls.Group.Id
&& c.LocationId == gls.Location.Id
&& c.ScheduleId == gls.Schedule.Id
)?.Count ?? 0;