-
-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathCallsController.cs
More file actions
1842 lines (1541 loc) · 64.2 KB
/
Copy pathCallsController.cs
File metadata and controls
1842 lines (1541 loc) · 64.2 KB
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
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Resgrid.Framework;
using Resgrid.Model;
using Resgrid.Model.Providers;
using Resgrid.Model.Services;
using Resgrid.Providers.Claims;
using Resgrid.Web.Services.Models.v4.Calls;
using Resgrid.Web.Services.Models.v4.UserDefinedFields;
using System;
using System.Linq;
using System.Threading.Tasks;
using Resgrid.Model.Helpers;
using IAuthorizationService = Resgrid.Model.Services.IAuthorizationService;
using Resgrid.Web.Services.Helpers;
using System.Net.Mime;
using System.Threading;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Resgrid.Model.Events;
using Resgrid.Model.Queue;
using Resgrid.Web.Services.Models.v4.CallProtocols;
using Resgrid.Web.Helpers;
using Resgrid.Web.ServicesCore.Helpers;
namespace Resgrid.Web.Services.Controllers.v4
{
/// <summary>
/// Calls, also referred to as Dispatches.
/// </summary>
[Route("api/v{VersionId:apiVersion}/[controller]")]
[ApiVersion("4.0")]
[ApiExplorerSettings(GroupName = "v4")]
[Authorize(AuthenticationSchemes = "BasicAuthentication,SystemApiKey")]
public class CallsController : V4AuthenticatedApiControllerbaseSystemAuth
{
#region Members and Constructors
private readonly ICallsService _callsService;
private readonly IDepartmentsService _departmentsService;
private readonly IUserProfileService _userProfileService;
private readonly IGeoLocationProvider _geoLocationProvider;
private readonly IAuthorizationService _authorizationService;
private readonly IQueueService _queueService;
private readonly IUsersService _usersService;
private readonly IUnitsService _unitsService;
private readonly IActionLogsService _actionLogsService;
private readonly IDepartmentGroupsService _departmentGroupsService;
private readonly IPersonnelRolesService _personnelRolesService;
private readonly IProtocolsService _protocolsService;
private readonly IEventAggregator _eventAggregator;
private readonly ICustomStateService _customStateService;
private readonly IDepartmentSettingsService _departmentSettingsService;
private readonly IShiftsService _shiftsService;
private readonly IMappingService _mappingService;
private readonly IUserDefinedFieldsService _userDefinedFieldsService;
private readonly ICommunicationService _communicationService;
private readonly IWeatherAlertService _weatherAlertService;
private readonly ICallDispatchStatusService _callDispatchStatusService;
public CallsController(
ICallsService callsService,
IDepartmentsService departmentsService,
IUserProfileService userProfileService,
IGeoLocationProvider geoLocationProvider,
IAuthorizationService authorizationService,
IQueueService queueService,
IUsersService usersService,
IUnitsService unitsService,
IActionLogsService actionLogsService,
IDepartmentGroupsService departmentGroupsService,
IPersonnelRolesService personnelRolesService,
IProtocolsService protocolsService,
IEventAggregator eventAggregator,
ICustomStateService customStateService,
IDepartmentSettingsService departmentSettingsService,
IShiftsService shiftsService,
IMappingService mappingService,
IUserDefinedFieldsService userDefinedFieldsService,
ICommunicationService communicationService,
IWeatherAlertService weatherAlertService,
ICallDispatchStatusService callDispatchStatusService
)
{
_callsService = callsService;
_departmentsService = departmentsService;
_userProfileService = userProfileService;
_geoLocationProvider = geoLocationProvider;
_authorizationService = authorizationService;
_queueService = queueService;
_usersService = usersService;
_unitsService = unitsService;
_actionLogsService = actionLogsService;
_departmentGroupsService = departmentGroupsService;
_personnelRolesService = personnelRolesService;
_protocolsService = protocolsService;
_eventAggregator = eventAggregator;
_customStateService = customStateService;
_departmentSettingsService = departmentSettingsService;
_shiftsService = shiftsService;
_mappingService = mappingService;
_userDefinedFieldsService = userDefinedFieldsService;
_communicationService = communicationService;
_weatherAlertService = weatherAlertService;
_callDispatchStatusService = callDispatchStatusService;
}
#endregion Members and Constructors
/// <summary>
/// Returns all the active calls for the department
/// </summary>
/// <returns>Array of CallResult objects for each active call in the department</returns>
[HttpGet("GetActiveCalls")]
[ProducesResponseType(StatusCodes.Status200OK)]
[Authorize(Policy = ResgridResources.Call_View)]
public async Task<ActionResult<ActiveCallsResult>> GetActiveCalls()
{
var result = new ActiveCallsResult();
var calls = (await _callsService.GetActiveCallsByDepartmentAsync(DepartmentId)).OrderByDescending(x => x.LoggedOn);
var destinationPois = await _mappingService.GetPOIsForDepartmentAsync(DepartmentId);
var destinationPoiLookup = destinationPois.ToDictionary(x => x.PoiId);
if (calls != null && calls.Any())
{
foreach (var c in calls)
{
var callWithData = await _callsService.PopulateCallData(c, false, true, true, false, false, false, true, true, true);
string address = "";
if (String.IsNullOrWhiteSpace(c.Address) && c.HasValidGeolocationData())
{
var geo = c.GeoLocationData.Split(char.Parse(","));
if (geo.Length == 2)
address = await _geoLocationProvider.GetAddressFromLatLong(double.Parse(geo[0]), double.Parse(geo[1]));
}
else
address = c.Address;
destinationPoiLookup.TryGetValue(callWithData.DestinationPoiId.GetValueOrDefault(), out var destinationPoi);
result.Data.Add(ConvertCall(callWithData, null, address, TimeZone, destinationPoi));
}
result.PageSize = result.Data.Count();
result.Status = ResponseHelper.Success;
}
else
{
result.PageSize = 0;
result.Status = ResponseHelper.NotFound;
}
ResponseHelper.PopulateV4ResponseData(result);
return Ok(result);
}
/// <summary>
/// Returns a specific call from the Resgrid System
/// </summary>
/// <param name="callId">Id of the call trying to be retrived</param>
/// <returns>CallResult of the call in the Resgrid system</returns>
[HttpGet("GetCall")]
[ProducesResponseType(StatusCodes.Status200OK)]
[Authorize(Policy = ResgridResources.Call_View)]
public async Task<ActionResult<GetCallResult>> GetCall(string callId, [FromQuery] string departmentId = null)
{
if (String.IsNullOrWhiteSpace(callId))
return BadRequest();
var result = new CallResult();
var c = await _callsService.GetCallByIdAsync(int.Parse(callId));
if (c == null)
{
ResponseHelper.PopulateV4ResponseNotFound(result);
return Ok(result);
}
var effectiveDepartmentId = GetEffectiveDepartmentId(departmentId);
if (c.DepartmentId != effectiveDepartmentId)
return Unauthorized();
if (!IsSystemApiKeyRequest && !await _authorizationService.CanUserViewCallAsync(UserId, int.Parse(callId)))
return Unauthorized();
c = await _callsService.PopulateCallData(c, false, true, true, false, false, false, true, true, true);
var destinationPoi = await GetValidatedDestinationPoiAsync(c.DestinationPoiId, effectiveDepartmentId);
string address = "";
if (String.IsNullOrWhiteSpace(c.Address) && c.HasValidGeolocationData())
{
var geo = c.GeoLocationData.Split(char.Parse(","));
if (geo.Length == 2)
address = await _geoLocationProvider.GetAddressFromLatLong(double.Parse(geo[0]), double.Parse(geo[1]));
}
else
address = c.Address;
var protocols = new List<DispatchProtocol>();
if (c.Protocols != null && c.Protocols.Any())
{
foreach (var callProtocol in c.Protocols)
{
var protocol = await _protocolsService.GetProtocolByIdAsync(callProtocol.CallProtocolId);
if (protocol != null)
protocols.Add(protocol);
}
}
result.Data = ConvertCall(c, protocols, address, TimeZone, destinationPoi);
// Populate UDF values
var udfValues = await _userDefinedFieldsService.GetFieldValuesForEntityAsync(effectiveDepartmentId, (int)UdfEntityType.Call, c.CallId.ToString());
if (udfValues != null && udfValues.Any())
{
result.Data.UdfValues = udfValues.Select(v => new UdfFieldValueResultData
{
UdfFieldValueId = v.UdfFieldValueId,
UdfFieldId = v.UdfFieldId,
UdfDefinitionId = v.UdfDefinitionId,
EntityId = v.EntityId,
EntityType = v.EntityType,
Value = v.Value
}).ToList();
}
result.PageSize = 1;
result.Status = ResponseHelper.Success;
ResponseHelper.PopulateV4ResponseData(result);
return Ok(result);
}
/// <summary>
/// Gets all the meta-data around a call, dispatched personnel, units, groups and responses
/// </summary>
/// <param name="callId">CallId to get data for</param>
/// <returns></returns>
[HttpGet("GetCallExtraData")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<CallExtraDataResult>> GetCallExtraData(int callId)
{
var result = new CallExtraDataResult();
var call = await _callsService.GetCallByIdAsync(callId);
if (call == null)
{
ResponseHelper.PopulateV4ResponseNotFound(result);
return Ok(result);
}
if (call.DepartmentId != DepartmentId)
Unauthorized();
if (!await _authorizationService.CanUserViewCallAsync(UserId, callId))
return Unauthorized();
call = await _callsService.PopulateCallData(call, true, true, true, true, true, true, true, true, true);
result.Data.CallFormData = call.CallFormData;
var groups = await _departmentGroupsService.GetAllGroupsForDepartmentAsync(DepartmentId);
var units = await _unitsService.GetUnitsForDepartmentAsync(call.DepartmentId);
var unitStates = (await _unitsService.GetUnitStatesForCallAsync(call.DepartmentId, callId)).OrderBy(x => x.UnitId).OrderBy(y => y.Timestamp).ToList();
var actionLogs = (await _actionLogsService.GetActionLogsForCallAsync(call.DepartmentId, callId)).OrderBy(x => x.UserId).OrderBy(y => y.Timestamp).ToList();
var names = await _usersService.GetUserGroupAndRolesByDepartmentIdAsync(DepartmentId, true, true, true);
var priority = await _callsService.GetCallPrioritiesByIdAsync(call.DepartmentId, call.Priority, false);
var roles = await _personnelRolesService.GetAllRolesForDepartmentAsync(call.DepartmentId);
var customStates = await _customStateService.GetAllCustomStatesForDepartmentAsync(call.DepartmentId);
var defaultUnitStatuses = _customStateService.GetDefaultUnitStatuses();
var defaultUserStatuses = await _customStateService.GetCustomPersonnelStatusesOrDefaultsAsync(call.DepartmentId);
if (priority != null)
{
result.Data.Priority = CallPrioritiesController.ConvertPriorityData(priority);
}
foreach (var actionLog in actionLogs)
{
var eventResult = new DispatchedEventResultData();
eventResult.Id = actionLog.ActionLogId.ToString();
eventResult.Timestamp = actionLog.Timestamp;
eventResult.Type = "User";
var name = names.FirstOrDefault(x => x.UserId == actionLog.UserId);
if (name != null)
{
eventResult.Name = name.Name;
if (name.DepartmentGroupId.HasValue)
{
eventResult.GroupId = name.DepartmentGroupId.Value.ToString();
eventResult.Group = name.DepartmentGroupName;
}
}
else
{
eventResult.Name = "Unknown User";
}
eventResult.StatusId = actionLog.ActionTypeId;
eventResult.Location = actionLog.GeoLocationData;
eventResult.Note = actionLog.Note;
if (actionLog.ActionTypeId <= 25)
{
var state = defaultUserStatuses.FirstOrDefault(x => x.CustomStateDetailId == actionLog.ActionTypeId);
if (state != null)
{
eventResult.StatusText = state.ButtonText;
eventResult.StatusColor = state.ButtonColor;
}
}
else
{
if (customStates != null && customStates.Count > 0)
{
var state = customStates.Select(state => state.Details.FirstOrDefault(x => x.CustomStateDetailId == actionLog.ActionTypeId)).FirstOrDefault(detail => detail != null);
if (state != null)
{
eventResult.StatusText = state.ButtonText;
eventResult.StatusColor = state.ButtonColor;
}
}
}
if (String.IsNullOrWhiteSpace(eventResult.StatusText))
eventResult.StatusText = "Unknown";
if (String.IsNullOrWhiteSpace(eventResult.StatusColor))
eventResult.StatusColor = "#ffa500";
result.Data.Activity.Add(eventResult);
}
foreach (var unitLog in unitStates)
{
var eventResult = new DispatchedEventResultData();
eventResult.Id = unitLog.UnitStateId.ToString();
eventResult.Timestamp = unitLog.Timestamp;
eventResult.Type = "Unit";
eventResult.Name = unitLog.Unit.Name;
var group = groups.FirstOrDefault(x => x.DepartmentGroupId == unitLog.Unit.StationGroupId);
if (group != null)
{
eventResult.GroupId = group.DepartmentGroupId.ToString();
eventResult.Group = group.Name;
}
eventResult.StatusId = unitLog.State;
eventResult.Location = unitLog.GeoLocationData;
eventResult.Note = unitLog.Note;
if (unitLog.UnitStateId <= 12)
{
var state = defaultUnitStatuses.FirstOrDefault(x => x.CustomStateDetailId == unitLog.UnitStateId);
if (state != null)
{
eventResult.StatusText = state.ButtonText;
eventResult.StatusColor = state.ButtonColor;
}
}
else
{
if (customStates != null && customStates.Count > 0)
{
var state = customStates.Select(state => state.Details.FirstOrDefault(x => x.CustomStateDetailId == unitLog.State)).FirstOrDefault(detail => detail != null);
if (state != null)
{
eventResult.StatusText = state.ButtonText;
eventResult.StatusColor = state.ButtonColor;
}
}
}
if (String.IsNullOrWhiteSpace(eventResult.StatusText))
eventResult.StatusText = "Unknown";
if (String.IsNullOrWhiteSpace(eventResult.StatusColor))
eventResult.StatusColor = "#ffa500";
result.Data.Activity.Add(eventResult);
}
foreach (var dispatch in call.Dispatches)
{
var eventResult = new DispatchedEventResultData();
eventResult.Id = dispatch.UserId;
if (dispatch.LastDispatchedOn.HasValue)
{
eventResult.Timestamp = dispatch.LastDispatchedOn.Value;
}
eventResult.Type = "User";
var name = names.FirstOrDefault(x => x.UserId == dispatch.UserId);
if (name != null)
{
eventResult.Name = name.Name;
if (name.DepartmentGroupId.HasValue)
{
eventResult.GroupId = name.DepartmentGroupId.Value.ToString();
eventResult.Group = name.DepartmentGroupName;
}
}
else
{
eventResult.Name = "Unknown User";
}
result.Data.Dispatches.Add(eventResult);
}
if (call.GroupDispatches != null && call.GroupDispatches.Any())
{
foreach (var groupDispatch in call.GroupDispatches)
{
var eventResult = new DispatchedEventResultData();
eventResult.Id = groupDispatch.DepartmentGroupId.ToString();
if (groupDispatch.LastDispatchedOn.HasValue)
{
eventResult.Timestamp = groupDispatch.LastDispatchedOn.Value;
}
eventResult.Type = "Group";
var name = groups.FirstOrDefault(x => x.DepartmentGroupId == groupDispatch.DepartmentGroupId);
if (name != null)
{
eventResult.Name = name.Name;
eventResult.GroupId = name.DepartmentGroupId.ToString();
eventResult.Group = name.Name;
}
else
{
eventResult.Name = "Unknown Group";
}
result.Data.Dispatches.Add(eventResult);
}
}
if (call.UnitDispatches != null && call.UnitDispatches.Any())
{
foreach (var unitDispatch in call.UnitDispatches)
{
var eventResult = new DispatchedEventResultData();
eventResult.Id = unitDispatch.UnitId.ToString();
if (unitDispatch.LastDispatchedOn.HasValue)
{
eventResult.Timestamp = unitDispatch.LastDispatchedOn.Value;
}
eventResult.Type = "Unit";
var unit = units.FirstOrDefault(x => x.UnitId == unitDispatch.UnitId);
if (unit != null)
{
eventResult.Name = unit.Name;
if (unit.StationGroupId.HasValue)
{
var group = groups.FirstOrDefault(x => x.DepartmentGroupId == unit.StationGroupId.GetValueOrDefault());
if (group != null)
{
eventResult.GroupId = group.DepartmentGroupId.ToString();
eventResult.Group = group.Name;
}
}
}
else
{
eventResult.Name = "Unknown Unit";
}
result.Data.Dispatches.Add(eventResult);
}
}
if (call.RoleDispatches != null && call.RoleDispatches.Any())
{
foreach (var roleDispatch in call.RoleDispatches)
{
var eventResult = new DispatchedEventResultData();
eventResult.Id = roleDispatch.RoleId.ToString();
if (roleDispatch.LastDispatchedOn.HasValue)
{
eventResult.Timestamp = roleDispatch.LastDispatchedOn.Value;
}
eventResult.Type = "Role";
var role = roles.FirstOrDefault(x => x.PersonnelRoleId == roleDispatch.RoleId);
if (role != null)
{
eventResult.Name = role.Name;
}
else
{
eventResult.Name = "Unknown Role";
}
result.Data.Dispatches.Add(eventResult);
}
}
if (call.Protocols != null && call.Protocols.Any())
{
foreach (var callProtocol in call.Protocols)
{
var protocol = await _protocolsService.GetProtocolByIdAsync(callProtocol.DispatchProtocolId);
if (protocol != null)
result.Data.Protocols.Add(CallProtocolsController.ConvertProtocolData(protocol));
}
}
result.PageSize = 0;
result.Status = ResponseHelper.Success;
ResponseHelper.PopulateV4ResponseData(result);
return Ok(result);
}
/// <summary>
/// Saves a call in the Resgrid system
/// </summary>
/// <param name="newCallInput"></param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns></returns>
[HttpPost("SaveCall")]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[Authorize(Policy = ResgridResources.Call_Create)]
public async Task<ActionResult<SaveCallResult>> SaveCall([FromBody] NewCallInput newCallInput, CancellationToken cancellationToken)
{
var result = new SaveCallResult();
var effectiveDepartmentId = GetEffectiveDepartmentId(newCallInput.DepartmentId);
if (!IsSystemApiKeyRequest)
{
var canDoOperation = await _authorizationService.CanUserCreateCallAsync(UserId, effectiveDepartmentId);
if (!canDoOperation)
return Unauthorized();
}
if (!ModelState.IsValid)
return BadRequest();
var department = await _departmentsService.GetDepartmentByIdAsync(effectiveDepartmentId);
if (department == null)
return BadRequest($"Department not found: {effectiveDepartmentId}");
var activeUsers = await _departmentsService.GetAllMembersForDepartmentAsync(effectiveDepartmentId);
var groups = await _departmentGroupsService.GetAllGroupsForDepartmentAsync(effectiveDepartmentId);
var roles = await _personnelRolesService.GetAllRolesForDepartmentAsync(effectiveDepartmentId);
var units = await _unitsService.GetUnitsForDepartmentAsync(effectiveDepartmentId);
var destinationPoi = await GetValidatedDestinationPoiAsync(newCallInput.DestinationPoiId, effectiveDepartmentId);
if (newCallInput.DestinationPoiId.HasValue && newCallInput.DestinationPoiId.Value > 0 && destinationPoi == null)
return BadRequest();
var call = new Call
{
DepartmentId = effectiveDepartmentId,
ReportingUserId = UserId,
Priority = newCallInput.Priority,
Name = newCallInput.Name,
NatureOfCall = newCallInput.Nature
};
if (!string.IsNullOrWhiteSpace(newCallInput.ContactName))
call.ContactName = newCallInput.ContactName;
if (!string.IsNullOrWhiteSpace(newCallInput.ContactInfo))
call.ContactNumber = newCallInput.ContactInfo;
if (!string.IsNullOrWhiteSpace(newCallInput.ExternalId))
call.ExternalIdentifier = newCallInput.ExternalId;
if (!string.IsNullOrWhiteSpace(newCallInput.IncidentId))
call.IncidentNumber = newCallInput.IncidentId;
if (!string.IsNullOrWhiteSpace(newCallInput.ReferenceId))
call.ReferenceNumber = newCallInput.ReferenceId;
if (!string.IsNullOrWhiteSpace(newCallInput.Address))
call.Address = newCallInput.Address;
call.DestinationPoiId = destinationPoi?.PoiId;
if (!string.IsNullOrWhiteSpace(newCallInput.What3Words))
call.W3W = newCallInput.What3Words;
if (!string.IsNullOrWhiteSpace(newCallInput.CallFormData))
call.CallFormData = newCallInput.CallFormData;
if (!string.IsNullOrWhiteSpace(newCallInput.IndoorMapZoneId))
call.IndoorMapZoneId = newCallInput.IndoorMapZoneId;
if (!string.IsNullOrWhiteSpace(newCallInput.IndoorMapFloorId))
call.IndoorMapFloorId = newCallInput.IndoorMapFloorId;
if (newCallInput.DispatchOn.HasValue)
{
call.DispatchOn = DateTimeHelpers.ConvertToUtc(newCallInput.DispatchOn.Value, department.TimeZone);
call.HasBeenDispatched = false;
}
if (!string.IsNullOrWhiteSpace(newCallInput.Note))
call.Notes = newCallInput.Note;
if (!string.IsNullOrWhiteSpace(newCallInput.Geolocation))
call.GeoLocationData = newCallInput.Geolocation;
if (string.IsNullOrWhiteSpace(call.GeoLocationData) && !string.IsNullOrWhiteSpace(call.Address))
call.GeoLocationData = await _geoLocationProvider.GetLatLonFromAddress(call.Address);
if (string.IsNullOrWhiteSpace(call.GeoLocationData) && !string.IsNullOrWhiteSpace(call.W3W))
{
var coords = await _geoLocationProvider.GetCoordinatesFromW3WAsync(call.W3W);
if (coords != null)
{
call.GeoLocationData = $"{coords.Latitude},{coords.Longitude}";
}
}
call.LoggedOn = DateTime.UtcNow;
if (newCallInput.CheckInTimersEnabled.HasValue)
call.CheckInTimersEnabled = newCallInput.CheckInTimersEnabled.Value;
else
{
var autoEnable = await _departmentSettingsService.GetCheckInTimersAutoEnableForNewCallsAsync(effectiveDepartmentId);
call.CheckInTimersEnabled = autoEnable;
}
if (!String.IsNullOrWhiteSpace(newCallInput.Type) && newCallInput.Type != "No Type")
{
var callTypes = await _callsService.GetCallTypesForDepartmentAsync(effectiveDepartmentId);
var type = callTypes.FirstOrDefault(x => x.Type == newCallInput.Type);
if (type != null)
{
call.Type = type.Type;
}
}
var users = await _departmentsService.GetAllUsersForDepartmentAsync(effectiveDepartmentId);
call.Dispatches = new Collection<CallDispatch>();
call.GroupDispatches = new List<CallDispatchGroup>();
call.RoleDispatches = new List<CallDispatchRole>();
call.UnitDispatches = new List<CallDispatchUnit>();
if (!IsSystemApiKeyRequest && (newCallInput.DispatchList == "0" || string.IsNullOrWhiteSpace(newCallInput.DispatchList)))
{
// Use case, existing clients and non-ionic2 app this will be null dispatch all users. Or we've specified everyone (0).
foreach (var u in users)
{
var cd = new CallDispatch { UserId = u.UserId };
call.Dispatches.Add(cd);
}
}
else if (!string.IsNullOrWhiteSpace(newCallInput.DispatchList) && newCallInput.DispatchList != "0")
{
var dispatch = newCallInput.DispatchList.Split(char.Parse("|"));
try
{
var usersToDispatch = dispatch.Where(x => x.StartsWith("P:")).Select(y => y.Replace("P:", ""));
foreach (var user in usersToDispatch)
{
if (activeUsers.Any(x => x.UserId == user && x.IsDeleted == false && x.IsDisabled == false))
{
var cd = new CallDispatch { UserId = user };
call.Dispatches.Add(cd);
}
}
}
catch (Exception ex)
{
Logging.LogException(ex);
}
try
{
var groupsToDispatch = dispatch.Where(x => x.StartsWith("G:")).Select(y => int.Parse(y.Replace("G:", "")));
foreach (var group in groupsToDispatch)
{
if (groups.Any(x => x.DepartmentGroupId == group))
{
var cd = new CallDispatchGroup { DepartmentGroupId = group };
call.GroupDispatches.Add(cd);
}
}
}
catch (Exception ex)
{
Logging.LogException(ex);
}
try
{
var rolesToDispatch = dispatch.Where(x => x.StartsWith("R:")).Select(y => int.Parse(y.Replace("R:", "")));
foreach (var role in rolesToDispatch)
{
if (roles.Any(x => x.PersonnelRoleId == role))
{
var cd = new CallDispatchRole { RoleId = role };
call.RoleDispatches.Add(cd);
}
}
}
catch (Exception ex)
{
Logging.LogException(ex);
}
try
{
var unitsToDispatch = dispatch.Where(x => x.StartsWith("U:")).Select(y => int.Parse(y.Replace("U:", "")));
foreach (var unit in unitsToDispatch)
{
if (units.Any(x => x.UnitId == unit))
{
var cdu = new CallDispatchUnit { UnitId = unit };
call.UnitDispatches.Add(cdu);
}
}
}
catch (Exception ex)
{
Logging.LogException(ex);
}
}
var shouldDispatchNow = !call.DispatchOn.HasValue || call.DispatchOn.Value <= DateTime.UtcNow;
// Call is in the past or is now, were dispatching now (at the end of this func)
if (call.DispatchOn.HasValue && call.DispatchOn.Value <= DateTime.UtcNow)
call.HasBeenDispatched = true;
var savedCall = await _callsService.SaveCallAsync(call, cancellationToken);
// Attach weather alerts as call notes if enabled
await _weatherAlertService.AttachWeatherAlertsToCallAsync(savedCall, cancellationToken);
//OutboundEventProvider handler = new OutboundEventProvider.CallAddedTopicHandler();
//OutboundEventProvider..Handle(new CallAddedEvent() { DepartmentId = DepartmentId, Call = savedCall });
_eventAggregator.SendMessage<CallAddedEvent>(new CallAddedEvent() { DepartmentId = effectiveDepartmentId, Call = savedCall });
if (shouldDispatchNow && ((call.GroupDispatches != null && call.GroupDispatches.Any()) || (call.UnitDispatches != null && call.UnitDispatches.Any())))
{
await _callDispatchStatusService.ApplyDispatchStatusesAsync(savedCall,
call.GroupDispatches?.Select(x => x.DepartmentGroupId),
call.UnitDispatches?.Select(x => x.UnitId),
cancellationToken);
}
var profiles = new List<string>();
if (call.Dispatches != null && call.Dispatches.Any())
{
profiles.AddRange(call.Dispatches.Select(x => x.UserId).ToList());
}
if (call.GroupDispatches != null && call.GroupDispatches.Any())
{
foreach (var groupDispatch in call.GroupDispatches)
{
var group = await _departmentGroupsService.GetGroupByIdAsync(groupDispatch.DepartmentGroupId);
if (group != null && group.Members != null)
{
profiles.AddRange(group.Members.Select(x => x.UserId));
}
}
}
if (call.RoleDispatches != null && call.RoleDispatches.Any())
{
foreach (var roleDispatch in call.RoleDispatches)
{
var members = await _personnelRolesService.GetAllMembersOfRoleAsync(roleDispatch.RoleId);
if (members != null)
{
profiles.AddRange(members.Select(x => x.UserId).ToList());
}
}
}
var cqi = new CallQueueItem();
cqi.Call = savedCall;
if (profiles.Any())
cqi.Profiles = await _userProfileService.GetSelectedUserProfilesAsync(profiles);
if (!savedCall.DispatchOn.HasValue || savedCall.DispatchOn.Value <= DateTime.UtcNow)
await _queueService.EnqueueCallBroadcastAsync(cqi, cancellationToken);
// Save UDF field values if supplied
if (newCallInput.UdfValues != null && newCallInput.UdfValues.Any())
{
bool isDeptAdmin = IsSystemApiKeyRequest || ClaimsAuthorizationHelper.IsUserDepartmentAdmin();
bool isGroupAdmin = HttpContext.User.Claims
.Any(c => c.Type.StartsWith(ResgridClaimTypes.Resources.Group + "/", StringComparison.Ordinal)
&& c.Value == ResgridClaimTypes.Actions.Update);
var udfValues = newCallInput.UdfValues.Select(v => new UdfFieldValue
{
UdfFieldId = v.UdfFieldId,
Value = v.Value
}).ToList();
await _userDefinedFieldsService.SaveFieldValuesForEntityAsync(effectiveDepartmentId, (int)UdfEntityType.Call, savedCall.CallId.ToString(), udfValues, UserId, isDeptAdmin, isGroupAdmin, cancellationToken);
}
result.Id = savedCall.CallId.ToString();
result.PageSize = 0;
result.Status = ResponseHelper.Created;
ResponseHelper.PopulateV4ResponseData(result);
return CreatedAtAction("GetCall", new { callId = result.Id }, result);
}
/// <summary>
/// Updates an existing Active Call in the Resgrid system
/// </summary>
/// <param name="editCallInput">Data to updated the call</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>OK status code if successful</returns>
[HttpPut("EditCall")]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[Authorize(Policy = ResgridResources.Call_Update)]
public async Task<ActionResult<EditCallResult>> EditCall([FromBody] EditCallInput editCallInput, CancellationToken cancellationToken)
{
var result = new EditCallResult();
var canDoOperation = await _authorizationService.CanUserEditCallAsync(UserId, int.Parse(editCallInput.Id));
if (!canDoOperation)
return Unauthorized();
var call = await _callsService.GetCallByIdAsync(int.Parse(editCallInput.Id));
call = await _callsService.PopulateCallData(call, true, true, true, true, true, true, true, true, true);
var department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId);
if (call == null)
{
ResponseHelper.PopulateV4ResponseNotFound(result);
return Ok(result);
}
if (!ModelState.IsValid)
return BadRequest();
if (call.DepartmentId != DepartmentId)
return Unauthorized();
if (call.State != (int)CallStates.Active)
return BadRequest();
var activeUsers = await _departmentsService.GetAllMembersForDepartmentAsync(DepartmentId);
var groups = await _departmentGroupsService.GetAllGroupsForDepartmentAsync(DepartmentId);
var roles = await _personnelRolesService.GetAllRolesForDepartmentAsync(DepartmentId);
var units = await _unitsService.GetUnitsForDepartmentAsync(DepartmentId);
var destinationPoi = await GetValidatedDestinationPoiAsync(editCallInput.DestinationPoiId);
if (editCallInput.DestinationPoiId.HasValue && editCallInput.DestinationPoiId.Value > 0 && destinationPoi == null)
return BadRequest();
call.Priority = editCallInput.Priority;
call.Name = editCallInput.Name;
call.NatureOfCall = editCallInput.Nature;
if (!string.IsNullOrWhiteSpace(editCallInput.ContactName))
call.ContactName = editCallInput.ContactName;
if (!string.IsNullOrWhiteSpace(editCallInput.ContactInfo))
call.ContactNumber = editCallInput.ContactInfo;
if (!string.IsNullOrWhiteSpace(editCallInput.ExternalId))
call.ExternalIdentifier = editCallInput.ExternalId;
if (!string.IsNullOrWhiteSpace(editCallInput.IncidentId))
call.IncidentNumber = editCallInput.IncidentId;
if (!string.IsNullOrWhiteSpace(editCallInput.ReferenceId))
call.ReferenceNumber = editCallInput.ReferenceId;
if (!string.IsNullOrWhiteSpace(editCallInput.Address))
call.Address = editCallInput.Address;
call.DestinationPoiId = destinationPoi?.PoiId;
if (!string.IsNullOrWhiteSpace(editCallInput.What3Words))
call.W3W = editCallInput.What3Words;
if (!string.IsNullOrWhiteSpace(editCallInput.CallFormData))
call.CallFormData = editCallInput.CallFormData;
if (editCallInput.DispatchOn.HasValue)
{
call.DispatchOn = DateTimeHelpers.ConvertToUtc(editCallInput.DispatchOn.Value, department.TimeZone);
call.HasBeenDispatched = false;
}
if (!string.IsNullOrWhiteSpace(editCallInput.Note))
call.Notes = editCallInput.Note;
if (!string.IsNullOrWhiteSpace(editCallInput.Geolocation))
call.GeoLocationData = editCallInput.Geolocation;
if (string.IsNullOrWhiteSpace(call.GeoLocationData) && !string.IsNullOrWhiteSpace(call.Address))
call.GeoLocationData = await _geoLocationProvider.GetLatLonFromAddress(call.Address);
if (string.IsNullOrWhiteSpace(call.GeoLocationData) && !string.IsNullOrWhiteSpace(call.W3W))
{
var coords = await _geoLocationProvider.GetCoordinatesFromW3WAsync(call.W3W);
if (coords != null)
{
call.GeoLocationData = $"{coords.Latitude},{coords.Longitude}";
}
}
if (!String.IsNullOrWhiteSpace(editCallInput.Type) && editCallInput.Type != "No Type")
{
var callTypes = await _callsService.GetCallTypesForDepartmentAsync(DepartmentId);
var type = callTypes.FirstOrDefault(x => x.Type == editCallInput.Type);
if (type != null)
{
call.Type = type.Type;
}
}
// Capture existing dispatch snapshots for cancel notification diffing
var existingDispatches = new List<CallDispatch>(call.Dispatches ?? new List<CallDispatch>());
var existingGroupDispatches = new List<CallDispatchGroup>(call.GroupDispatches ?? new List<CallDispatchGroup>());
var existingUnitDispatches = new List<CallDispatchUnit>(call.UnitDispatches ?? new List<CallDispatchUnit>());
var existingRoleDispatches = new List<CallDispatchRole>(call.RoleDispatches ?? new List<CallDispatchRole>());
if (string.IsNullOrWhiteSpace(editCallInput.DispatchList) || editCallInput.DispatchList == "0")
{
if (call.Dispatches == null)
call.Dispatches = new List<CallDispatch>();
if (call.GroupDispatches == null)
call.GroupDispatches = new List<CallDispatchGroup>();
if (call.RoleDispatches == null)
call.RoleDispatches = new List<CallDispatchRole>();
if (call.UnitDispatches == null)
call.UnitDispatches = new List<CallDispatchUnit>();
var users = await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId);
// Use case, existing clients and non-ionic2 app this will be null dispatch all users. Or we've specified everyone (0).
foreach (var u in users)
{
var cd = new CallDispatch { UserId = u.UserId };
call.Dispatches.Add(cd);
}
}
else
{
var dispatch = editCallInput.DispatchList.Split(char.Parse("|"));
var usersToDispatch = dispatch.Where(x => x.StartsWith("P:")).Select(y => y.Replace("P:", ""));
var groupsToDispatch = dispatch.Where(x => x.StartsWith("G:")).Select(y => int.Parse(y.Replace("G:", "")));
var rolesToDispatch = dispatch.Where(x => x.StartsWith("R:")).Select(y => int.Parse(y.Replace("R:", "")));
var unitsToDispatch = dispatch.Where(x => x.StartsWith("U:")).Select(y => int.Parse(y.Replace("U:", "")));
try
{
if (call.Dispatches == null)
call.Dispatches = new List<CallDispatch>();
var dispatchesToRemove = call.Dispatches.Select(x => x.UserId).Where(y => !usersToDispatch.Contains(y)).ToList();