Skip to content

Commit 69da7f9

Browse files
authored
Merge pull request #356 from bcgov/OperationalSpace_Count
Update P900 for operationcount update
2 parents 3909c09 + 29663e5 commit 69da7f9

File tree

2 files changed

+201
-14
lines changed

2 files changed

+201
-14
lines changed

OFM.Infrastructure.WebAPI/Models/DataverseModels.cs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,33 @@ public class LicenceDetail
557557
public string TypeName { get; set; } = string.Empty;
558558
}
559559

560+
561+
public class D365LicenceDetail
562+
{
563+
public int ofm_operational_spaces { get; set; }
564+
565+
566+
public string ofm_program_session { get; set; }
567+
568+
public Guid ofm_licence_detailid { get; set; }
569+
570+
[property: JsonPropertyName("ofm_licence_type@OData.Community.Display.V1.FormattedValue")]
571+
public string ofm_licence_typename { get; set; }
572+
573+
[JsonPropertyName("ofm_licence")]
574+
public D365Licence ofm_licence { get; set; }
575+
576+
577+
578+
}
579+
580+
public class D365Licence
581+
{
582+
[JsonPropertyName("ofm_licenceid")]
583+
public Guid ofm_licenceid { get; set; }
584+
}
585+
586+
560587
#region External Parameters
561588

562589
#endregion

OFM.Infrastructure.WebAPI/Services/Processes/LicenceDetail/P900CalculateLicenceTotal.cs

Lines changed: 174 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
1-
using Microsoft.Extensions.Logging;
1+
using ECC.Core.DataContext;
2+
using Microsoft.Extensions.Logging;
23
using OFM.Infrastructure.WebAPI.Extensions;
4+
using OFM.Infrastructure.WebAPI.Messages;
35
using OFM.Infrastructure.WebAPI.Models;
46
using OFM.Infrastructure.WebAPI.Services.AppUsers;
57
using OFM.Infrastructure.WebAPI.Services.D365WebApi;
68
using OFM.Infrastructure.WebAPI.Services.Processes.Emails;
79
using OFM.Infrastructure.WebAPI.Services.Processes.Fundings;
810
using OFM.Infrastructure.WebAPI.Services.Processes.ProviderProfiles;
911
using System;
12+
using System.Linq;
1013
using System.Net;
1114
using System.Reflection;
1215
using System.Text.Json;
1316
using System.Text.Json.Nodes;
17+
using System.Text.RegularExpressions;
1418

1519
namespace OFM.Infrastructure.WebAPI.Services.Processes.LicenceDetailRecords
1620
{
@@ -23,7 +27,7 @@ public class P900CalculateLicenceTotal(ID365AppUserService appUserService, ID365
2327
private ProcessParameter? _processParams;
2428
private ProcessData? _data;
2529
private string? licenceFilterDate;
26-
30+
2731
private int Group_Child_Care_Under_36_Enrolled = 0;
2832
private int Group_Child_Care_Under_36_Licenced = 0;
2933
private int Group_Child_Care_Under_36_Operational = 0;
@@ -66,21 +70,73 @@ public class P900CalculateLicenceTotal(ID365AppUserService appUserService, ID365
6670
private decimal Total_Three_to_Five;
6771
private decimal Total_Under_Three;
6872
private decimal Total_Star_Percentage;
69-
73+
string currentMonth;
7074
public short ProcessId => Setup.Process.LicenceDetailRecords.CalculateLicenceTotal;
7175
public string ProcessName => Setup.Process.LicenceDetailRecords.CalculteLicenceTotalName;
7276

77+
public string SDDforOperationalSpaceRequestURI
78+
{
79+
80+
get
81+
{
82+
var fetchXml = $"""
83+
<fetch>
84+
<entity name="ofm_licence_detail">
85+
<attribute name="ofm_operational_spaces"/>
86+
<attribute name="ofm_program_session"/>
87+
<attribute name="ofm_licence_detailid"/>
88+
<attribute name="ofm_licence_type"/>
89+
<filter>
90+
<condition attribute="statecode" operator="eq" value="0"/>
91+
<filter type="or">
92+
<condition attribute="{string.Concat("ofm_", currentMonth.ToLower())}" operator="null"/>
93+
<condition attribute="{string.Concat("ofm_", currentMonth.ToLower())}" operator="eq" value="1"/>
94+
</filter>
95+
</filter>
96+
<link-entity name="ofm_licence" from="ofm_licenceid" to="ofm_licence" link-type="inner">
97+
<filter type="and">
98+
<condition attribute="ofm_start_date" operator="on-or-before" value="{licenceFilterDate}"/>
99+
<condition attribute="statecode" operator="eq" value="0"/>
100+
<filter type="or">
101+
<condition attribute="ofm_end_date" operator="null"/>
102+
<condition attribute="ofm_end_date" operator="on-or-after" value="{licenceFilterDate}"/>
103+
</filter>
104+
</filter>
105+
<link-entity name="account" from="accountid" to="ofm_facility" link-type="inner">
106+
<filter>
107+
<condition attribute="accountid" operator="eq" value="{_processParams.Application.facilityId}"/>
108+
</filter>
109+
</link-entity>
110+
</link-entity>
111+
</entity>
112+
</fetch>
113+
""";
114+
115+
var requestUri = $"""
116+
ofm_licence_details?$select=ofm_operational_spaces,ofm_program_session,ofm_licence_type&$filter=statecode eq 0 and (ofm_january eq null or ofm_january eq true) and (ofm_february eq null or ofm_february eq true) and (ofm_march eq null or ofm_march eq true) and (ofm_april eq null or ofm_april eq true) and (ofm_may eq null or ofm_may eq true) and (ofm_june eq null or ofm_june eq true) and (ofm_july eq null or ofm_july eq true) and (ofm_august eq null or ofm_august eq true) and (ofm_september eq null or ofm_september eq true) and (ofm_october eq null or ofm_october eq true) and (ofm_november eq null or ofm_november eq true) and (ofm_december eq null or ofm_december eq true) and ofm_licence/ofm_start_date le {DateTime.Parse(licenceFilterDate).ToString("yyyy-MM-dd")} and (ofm_licence/ofm_end_date eq null or ofm_licence/ofm_end_date ge {DateTime.Parse(licenceFilterDate).ToString("yyyy-MM-dd")}) and ofm_licence/ofm_facility/accountid eq {_processParams.Application.facilityId}&$expand=ofm_licence($expand=ofm_facility)
117+
""";
118+
119+
return requestUri.CleanCRLF();
120+
121+
//var requestUri = $"""
122+
// ofm_licence_details?fetchXml={WebUtility.UrlEncode(fetchXml)}
123+
// """;
124+
125+
//return requestUri;
126+
}
127+
}
128+
73129
public string ServiceDeliveryDetailRequestURI
74130
{
75131
get
76132
{
133+
77134
var fetchXml = $"""
78135
<fetch aggregate="true">
79136
<entity name="ofm_licence_detail">
80137
<attribute name="ofm_enrolled_spaces" alias="Total_Enrolled_Spaces" aggregate="sum" />
81138
<attribute name="ofm_licence_spaces" alias="Total_Licenced_Spaces" aggregate="sum" />
82-
<attribute name="ofm_operational_spaces" alias="Total_Operational_Spaces" aggregate="sum" />
83-
<attribute name="ofm_star_spaces_three_to_five_years" alias="Total_Three_to_Five" aggregate="sum" />
139+
<attribute name="ofm_star_spaces_three_to_five_years" alias="Total_Three_to_Five" aggregate="sum" />
84140
<attribute name="ofm_star_spaces_under_three_years" alias="Total_Under_Three" aggregate="sum" />
85141
<attribute name="ofm_licence_type" groupby="true" alias="type" />
86142
<filter>
@@ -113,12 +169,62 @@ public string ServiceDeliveryDetailRequestURI
113169
}
114170
}
115171

172+
public async Task<ProcessData> GetOperationSpaceDataAsync()
173+
{
174+
_logger.LogDebug(CustomLogEvent.Process, "Calling GetData of {nameof}", nameof(P900CalculateLicenceTotal));
175+
176+
if (_data is null && _processParams is not null)
177+
{
178+
if (_processParams.Application.submittedOn is not null)
179+
{
180+
licenceFilterDate = _processParams.Application.submittedOn.ToString();
181+
}
182+
183+
else
184+
{
185+
licenceFilterDate = _processParams.Application.createdOn.ToString();
186+
}
187+
try
188+
{
189+
_logger.LogDebug(CustomLogEvent.Process, "Getting Licence Detail with query {requestUri}", SDDforOperationalSpaceRequestURI.CleanLog());
190+
191+
var response = await _d365webapiservice.SendRetrieveRequestAsync(_appUserService.AZSystemAppUser, SDDforOperationalSpaceRequestURI, true, isProcess: true);
192+
193+
if (!response.IsSuccessStatusCode)
194+
{
195+
var responseBody = await response.Content.ReadAsStringAsync();
196+
_logger.LogError(CustomLogEvent.Process, "Failed to query Licence Detail with the server error {responseBody}", responseBody.CleanLog());
197+
198+
return await Task.FromResult(new ProcessData(string.Empty));
199+
}
200+
201+
var jsonObject = await response.Content.ReadFromJsonAsync<JsonObject>();
202+
203+
JsonNode d365Result = string.Empty;
204+
if (jsonObject?.TryGetPropertyValue("value", out var currentValue) == true)
205+
{
206+
if (currentValue?.AsArray().Count == 0)
207+
{
208+
_logger.LogInformation(CustomLogEvent.Process, "No Licence Detail found with query {requestUri}", ServiceDeliveryDetailRequestURI.CleanLog());
209+
}
210+
d365Result = currentValue!;
211+
}
212+
213+
_data = new ProcessData(d365Result);
214+
215+
_logger.LogDebug(CustomLogEvent.Process, "Query Result {_data}", _data?.Data.ToString().CleanLog());
216+
}
217+
catch (Exception ex) { }
218+
}
219+
220+
return await Task.FromResult(_data!);
221+
}
116222

117223
public async Task<ProcessData> GetDataAsync()
118224
{
119225
_logger.LogDebug(CustomLogEvent.Process, "Calling GetData of {nameof}", nameof(P900CalculateLicenceTotal));
120226

121-
if (_data is null && _processParams is not null)
227+
if (_processParams is not null)
122228
{
123229
if (_processParams.Application.submittedOn is not null)
124230
{
@@ -164,16 +270,70 @@ public async Task<ProcessData> GetDataAsync()
164270
public async Task<JsonObject> RunProcessAsync(ID365AppUserService appUserService, ID365WebApiService d365WebApiService, ProcessParameter processParams)
165271
{
166272
_processParams = processParams;
167-
if (_processParams == null || _processParams.Application == null || _processParams.Application.applicationId == null ||_processParams.Application.facilityId == null
273+
if (_processParams == null || _processParams.Application == null || _processParams.Application.applicationId == null || _processParams.Application.facilityId == null
168274
|| (_processParams.Application.submittedOn == null && _processParams.Application.createdOn == null))
169275
{
170276
_logger.LogError(CustomLogEvent.Process, "Application data is missing.");
171277
throw new Exception("Application data is missing.");
172278
}
173279

280+
currentMonth = DateTime.UtcNow.ToLocalPST().ToString("MMMM", System.Globalization.CultureInfo.InvariantCulture);
174281
var startTime = _timeProvider.GetTimestamp();
175282

176283
_logger.LogDebug(CustomLogEvent.Process, "Start of {nameof}", nameof(P900CalculateLicenceTotal));
284+
var oplicencedetail = await GetOperationSpaceDataAsync();
285+
var updateSessionDetailRequests = new List<HttpRequestMessage>() { };
286+
var deserializedopLicenceDetailData = JsonSerializer.Deserialize<List<D365LicenceDetail>>(oplicencedetail.Data.ToString());
287+
var enrichedRecords = from d in deserializedopLicenceDetailData
288+
select new
289+
{
290+
Detail = d,
291+
ofm_program_session = string.IsNullOrWhiteSpace(d.ofm_program_session)
292+
? (d.ofm_licence_typename.Contains("(School-Age)") ? "School Age Care" :
293+
d.ofm_licence_typename.Contains("Preschool (") ? d.ofm_licence_typename : Regex.Replace(d.ofm_licence_typename, @"group\s+\d+\b", "", RegexOptions.IgnoreCase).Trim())
294+
: d.ofm_program_session,
295+
};
296+
297+
JsonObject updateSessionDetail;
298+
299+
300+
foreach (var eachRec in enrichedRecords)
301+
{
302+
updateSessionDetail = new JsonObject {
303+
{ "ofm_program_session", eachRec.ofm_program_session }
304+
};
305+
306+
updateSessionDetailRequests.Add(new D365UpdateRequest(new D365EntityReference("ofm_licence_details", (Guid)eachRec.Detail.ofm_licence_detailid), updateSessionDetail));
307+
}
308+
309+
// Deactive reminders
310+
var updateSessionDetailResults = await d365WebApiService.SendBatchMessageAsync(appUserService.AZSystemAppUser, updateSessionDetailRequests, null);
311+
if (updateSessionDetailResults.Errors.Any())
312+
{
313+
var sendNotificationError = ProcessResult.Failure(ProcessId, updateSessionDetailResults.Errors, updateSessionDetailResults.TotalProcessed, updateSessionDetailResults.TotalRecords);
314+
_logger.LogError(CustomLogEvent.Process, "Failed to send notifications with an error: {error}", JsonValue.Create(sendNotificationError)!.ToString());
315+
316+
return await Task.FromResult(sendNotificationError.SimpleProcessResult);
317+
}
318+
319+
320+
var grouped = enrichedRecords.GroupBy(x => new
321+
{
322+
LicenceId = x.Detail.ofm_licence.ofm_licenceid,
323+
ProgramSession = string.IsNullOrWhiteSpace(x.ofm_program_session) ? null : x.ofm_program_session
324+
325+
}).Select(g => new
326+
{
327+
LicenceName = g.Key.LicenceId,
328+
ProgramSessionName = g.Key.ProgramSession,
329+
MaxOperationalSpaces = g.Max(x => x.Detail.ofm_operational_spaces)
330+
});
331+
332+
333+
334+
// Final total operational spaces for facility
335+
int totalOperationalSpaces = (int)grouped.Sum(x => x.MaxOperationalSpaces);
336+
177337
var licenceDetail = await GetDataAsync();
178338
var deserializedLicenceDetailData = JsonSerializer.Deserialize<List<LicenceDetail>>(licenceDetail.Data.ToString());
179339
#region commented code to hold total space functionality
@@ -294,24 +454,24 @@ public async Task<JsonObject> RunProcessAsync(ID365AppUserService appUserService
294454

295455
deserializedLicenceDetailData?.ForEach(licenceDetail =>
296456
{
297-
Total_Operational_Spaces += licenceDetail.Total_Operational_Spaces;
457+
Total_Operational_Spaces = totalOperationalSpaces;//totalOperationalSpaces;
298458
Total_Under_Three += licenceDetail.Total_Under_Three;
299459
Total_Three_to_Five += licenceDetail.Total_Three_to_Five;
300460

301-
461+
302462
});
303-
// var Total = Math.Round(Total_Under_Three + Total_Three_to_Five, 0, MidpointRounding.AwayFromZero);
463+
// var Total = Math.Round(Total_Under_Three + Total_Three_to_Five, 0, MidpointRounding.AwayFromZero);
304464
if (Total_Operational_Spaces != 0)
305465
{
306-
Total_Star_Percentage = Math.Round(Total_Under_Three + Total_Three_to_Five / Total_Operational_Spaces * 100, 0, MidpointRounding.AwayFromZero) ;
307-
}
466+
Total_Star_Percentage = Math.Round(Total_Under_Three + Total_Three_to_Five / Total_Operational_Spaces * 100, 0, MidpointRounding.AwayFromZero);
467+
}
308468
else
309469
{
310470
_logger.LogError("Total_Operational_Spaces is null or zero. Cannot compute percentage.");
311471
}
312472

313-
314-
var updateApplicationRecord = new JsonObject {
473+
474+
var updateApplicationRecord = new JsonObject {
315475
{"ofm_total_operational_spaces", Total_Operational_Spaces},
316476
{"ofm_star_total_percentage",Total_Star_Percentage},
317477
};

0 commit comments

Comments
 (0)