1
- using Microsoft . Extensions . Logging ;
1
+ using ECC . Core . DataContext ;
2
+ using Microsoft . Extensions . Logging ;
2
3
using OFM . Infrastructure . WebAPI . Extensions ;
4
+ using OFM . Infrastructure . WebAPI . Messages ;
3
5
using OFM . Infrastructure . WebAPI . Models ;
4
6
using OFM . Infrastructure . WebAPI . Services . AppUsers ;
5
7
using OFM . Infrastructure . WebAPI . Services . D365WebApi ;
6
8
using OFM . Infrastructure . WebAPI . Services . Processes . Emails ;
7
9
using OFM . Infrastructure . WebAPI . Services . Processes . Fundings ;
8
10
using OFM . Infrastructure . WebAPI . Services . Processes . ProviderProfiles ;
9
11
using System ;
12
+ using System . Linq ;
10
13
using System . Net ;
11
14
using System . Reflection ;
12
15
using System . Text . Json ;
13
16
using System . Text . Json . Nodes ;
17
+ using System . Text . RegularExpressions ;
14
18
15
19
namespace OFM . Infrastructure . WebAPI . Services . Processes . LicenceDetailRecords
16
20
{
@@ -23,7 +27,7 @@ public class P900CalculateLicenceTotal(ID365AppUserService appUserService, ID365
23
27
private ProcessParameter ? _processParams ;
24
28
private ProcessData ? _data ;
25
29
private string ? licenceFilterDate ;
26
-
30
+
27
31
private int Group_Child_Care_Under_36_Enrolled = 0 ;
28
32
private int Group_Child_Care_Under_36_Licenced = 0 ;
29
33
private int Group_Child_Care_Under_36_Operational = 0 ;
@@ -66,21 +70,73 @@ public class P900CalculateLicenceTotal(ID365AppUserService appUserService, ID365
66
70
private decimal Total_Three_to_Five ;
67
71
private decimal Total_Under_Three ;
68
72
private decimal Total_Star_Percentage ;
69
-
73
+ string currentMonth ;
70
74
public short ProcessId => Setup . Process . LicenceDetailRecords . CalculateLicenceTotal ;
71
75
public string ProcessName => Setup . Process . LicenceDetailRecords . CalculteLicenceTotalName ;
72
76
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
+
73
129
public string ServiceDeliveryDetailRequestURI
74
130
{
75
131
get
76
132
{
133
+
77
134
var fetchXml = $ """
78
135
<fetch aggregate="true">
79
136
<entity name="ofm_licence_detail">
80
137
<attribute name="ofm_enrolled_spaces" alias="Total_Enrolled_Spaces" aggregate="sum" />
81
138
<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" />
84
140
<attribute name="ofm_star_spaces_under_three_years" alias="Total_Under_Three" aggregate="sum" />
85
141
<attribute name="ofm_licence_type" groupby="true" alias="type" />
86
142
<filter>
@@ -113,12 +169,62 @@ public string ServiceDeliveryDetailRequestURI
113
169
}
114
170
}
115
171
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
+ }
116
222
117
223
public async Task < ProcessData > GetDataAsync ( )
118
224
{
119
225
_logger . LogDebug ( CustomLogEvent . Process , "Calling GetData of {nameof}" , nameof ( P900CalculateLicenceTotal ) ) ;
120
226
121
- if ( _data is null && _processParams is not null )
227
+ if ( _processParams is not null )
122
228
{
123
229
if ( _processParams . Application . submittedOn is not null )
124
230
{
@@ -164,16 +270,70 @@ public async Task<ProcessData> GetDataAsync()
164
270
public async Task < JsonObject > RunProcessAsync ( ID365AppUserService appUserService , ID365WebApiService d365WebApiService , ProcessParameter processParams )
165
271
{
166
272
_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
168
274
|| ( _processParams . Application . submittedOn == null && _processParams . Application . createdOn == null ) )
169
275
{
170
276
_logger . LogError ( CustomLogEvent . Process , "Application data is missing." ) ;
171
277
throw new Exception ( "Application data is missing." ) ;
172
278
}
173
279
280
+ currentMonth = DateTime . UtcNow . ToLocalPST ( ) . ToString ( "MMMM" , System . Globalization . CultureInfo . InvariantCulture ) ;
174
281
var startTime = _timeProvider . GetTimestamp ( ) ;
175
282
176
283
_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
+
177
337
var licenceDetail = await GetDataAsync ( ) ;
178
338
var deserializedLicenceDetailData = JsonSerializer . Deserialize < List < LicenceDetail > > ( licenceDetail . Data . ToString ( ) ) ;
179
339
#region commented code to hold total space functionality
@@ -294,24 +454,24 @@ public async Task<JsonObject> RunProcessAsync(ID365AppUserService appUserService
294
454
295
455
deserializedLicenceDetailData ? . ForEach ( licenceDetail =>
296
456
{
297
- Total_Operational_Spaces += licenceDetail . Total_Operational_Spaces ;
457
+ Total_Operational_Spaces = totalOperationalSpaces ; //totalOperationalSpaces ;
298
458
Total_Under_Three += licenceDetail . Total_Under_Three ;
299
459
Total_Three_to_Five += licenceDetail . Total_Three_to_Five ;
300
460
301
-
461
+
302
462
} ) ;
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);
304
464
if ( Total_Operational_Spaces != 0 )
305
465
{
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
+ }
308
468
else
309
469
{
310
470
_logger . LogError ( "Total_Operational_Spaces is null or zero. Cannot compute percentage." ) ;
311
471
}
312
472
313
-
314
- var updateApplicationRecord = new JsonObject {
473
+
474
+ var updateApplicationRecord = new JsonObject {
315
475
{ "ofm_total_operational_spaces" , Total_Operational_Spaces } ,
316
476
{ "ofm_star_total_percentage" , Total_Star_Percentage } ,
317
477
} ;
0 commit comments