Skip to content

Commit

Permalink
GS_Notification (#72)
Browse files Browse the repository at this point in the history
* Not good standing Notification  created

* Updated template retrieval with number

* OFMCC-1994 & OFMCC-1995 (bypass Good Standing logic)

* Updated email status to completed for 205,400,405 and 210
  • Loading branch information
bcgov-hl authored Apr 24, 2024
1 parent 87b5700 commit 512b34f
Show file tree
Hide file tree
Showing 9 changed files with 365 additions and 166 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -412,3 +412,5 @@ FodyWeavers.xsd
/OFM.Infrastructure.PCF/Controls/GoodStanding/Solution/OFMPCFs/src/Controls/ofm_ECC.PCF.FundingEnvelopeControl/ControlManifest.xml.data.xml
/OFM.Infrastructure.PCF/Controls/GoodStanding/Solution/OFMPCFs/src/Controls/ofm_ECC.PCF.FundingEnvelopeControl/ControlManifest.xml
/OFM.Infrastructure.PCF/Controls/GoodStanding/Solution/OFMPCFs/src/Controls/ofm_Banner.Banner
/OFM.Infrastructure.WebAPI/appsettings.DEV.json
/OFM.Infrastructure.WebAPI/appsettings.UAT.json
7 changes: 6 additions & 1 deletion OFM.Infrastructure.WebAPI/Models/DataverseModels.cs
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,10 @@ public record D365Template
{
public string? title { get; set; }
public string? safehtml { get; set; }
public string? body { get; set; }
public string? body { get; set; }
public string? templateid { get; set; }
public string? templatecode { get; set; }

}

public record D365Email
Expand Down Expand Up @@ -223,7 +224,11 @@ public record D365Organization_Account
public string? name { get; set; }
public string? ofm_incorporation_number { get; set; }
public string? ofm_business_number { get; set; }
public bool? ofm_bypass_bc_registry_good_standing { get; set; }
public int statecode { get; set; }
public Guid _primarycontactid_value { get; set; }
public Guid _ofm_primarycontact_value { get; set; }


}

Expand Down
5 changes: 2 additions & 3 deletions OFM.Infrastructure.WebAPI/Models/SettingsModels.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ public record CommunicationTypes
public class EmailTemplate
{
public int TemplateNumber { get; set; }
public string TemplateId { get; set; }
public string Description { get; set; }

}

public record ProcessSettings
Expand Down Expand Up @@ -152,7 +151,7 @@ public record BCRegistrySettings
public string batchtaskprocess { get; set; }
public string singletaskprocess { get; set; }
public required TaskActivity TaskActivity { get; set; }

}
public record TaskActivity
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ namespace OFM.Infrastructure.WebAPI.Services.Processes.Fundings;
public interface IEmailRepository
{
Task<IEnumerable<D365CommunicationType>> LoadCommunicationTypeAsync();
Task<JsonObject> CreateAndUpdateEmail(string subject, string emailDescription, List<Guid> toRecipient, Guid? senderId, string communicationType, ID365AppUserService appUserService, ID365WebApiService d365WebApiService, Int16 processId);
Task<ProcessData> GetTemplateDataAsync(int templateNumber);
}

public class EmailRepository(ID365AppUserService appUserService, ID365WebApiService service, ID365DataService dataService, ILoggerFactory loggerFactory) : IEmailRepository
Expand All @@ -25,6 +27,7 @@ public class EmailRepository(ID365AppUserService appUserService, ID365WebApiServ
private readonly ID365AppUserService _appUserService = appUserService;
private readonly ID365WebApiService _d365webapiservice = service;
private Guid? _fundingId;
private int _templateNumber;

#region Pre-Defined Queries

Expand Down Expand Up @@ -53,15 +56,138 @@ private string CommunicationTypeRequestUri
return requestUri;
}
}

private string TemplatetoRetrieveUri
{
get
{
var fetchXml = $"""
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
<entity name="template">
<attribute name="title" />
<attribute name="templatetypecode" />
<attribute name="safehtml" />
<attribute name="languagecode" />
<attribute name="templateid" />
<attribute name="description" />
<attribute name="body" />
<order attribute="title" descending="false" />
<filter type="or">
<condition attribute="ccof_templateid" operator="eq" uitype="template" value="{_templateNumber}" />
</filter>
</entity>
</fetch>
""";

var requestUri = $"""
templates?fetchXml={WebUtility.UrlEncode(fetchXml)}
""";

return requestUri.CleanCRLF();
}
}
#endregion

public async Task<ProcessData> GetTemplateDataAsync(int templateNumber)
{
_templateNumber = templateNumber;
_logger.LogDebug(CustomLogEvent.Process, "Calling GetTemplateToSendEmail");

var response = await _d365webapiservice.SendRetrieveRequestAsync(_appUserService.AZSystemAppUser, TemplatetoRetrieveUri);

if (!response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
_logger.LogError(CustomLogEvent.Process, "Failed to query Emmail Template to update with the server error {responseBody}", responseBody.CleanLog());

return await Task.FromResult(new ProcessData(string.Empty));
}

var jsonObject = await response.Content.ReadFromJsonAsync<JsonObject>();

JsonNode d365Result = string.Empty;
if (jsonObject?.TryGetPropertyValue("value", out var currentValue) == true)
{
if (currentValue?.AsArray().Count == 0)
{
_logger.LogInformation(CustomLogEvent.Process, "No template found with query {requestUri}", TemplatetoRetrieveUri.CleanLog());
}
d365Result = currentValue!;
}

_logger.LogDebug(CustomLogEvent.Process, "Query Result {queryResult}", d365Result.ToString().CleanLog());

return await Task.FromResult(new ProcessData(d365Result));
}

public async Task<IEnumerable<D365CommunicationType>> LoadCommunicationTypeAsync()
{
var localdata = await _dataService.FetchDataAsync(CommunicationTypeRequestUri, "CommunicationTypes");
var deserializedData = localdata.Data.Deserialize<List<D365CommunicationType>>(Setup.s_writeOptionsForLogs);

return await Task.FromResult(deserializedData!); ;
return await Task.FromResult(deserializedData!);
}



#region Create and Update Email

public async Task<JsonObject> CreateAndUpdateEmail(string subject, string emailDescription, List<Guid> toRecipient, Guid? senderId, string communicationType, ID365AppUserService appUserService, ID365WebApiService d365WebApiService, Int16 processId)
{
toRecipient.ForEach(async recipient =>
{
var requestBody = new JsonObject(){
{"subject",subject },
{"description",emailDescription },
{"email_activity_parties", new JsonArray(){
new JsonObject
{
{ "[email protected]", $"/systemusers({senderId})"},
{ "participationtypemask", 1 } //From Email
},
new JsonObject
{
{ "[email protected]", $"/contacts({recipient})" },
{ "participationtypemask", 2 } //To Email
}
}},
{ "[email protected]", $"/ofm_communication_types({communicationType})"}
};

var response = await d365WebApiService.SendCreateRequestAsync(appUserService.AZSystemAppUser, "emails", requestBody.ToString());

if (!response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
_logger.LogError(CustomLogEvent.Process, "Failed to create the record with the server error {responseBody}", responseBody.CleanLog());

return await Task.FromResult<JsonObject>(new JsonObject() { });
}

var newEmail = await response.Content.ReadFromJsonAsync<JsonObject>();
var newEmailId = newEmail?["activityid"];

var emailStatement = $"emails({newEmailId})";

var payload = new JsonObject {
{ "ofm_sent_on", DateTime.UtcNow },
{ "statuscode", 2 }, // 6 = Pending Send ,2=Completed
{ "statecode", 1 }};

var requestBody1 = JsonSerializer.Serialize(payload);

var patchResponse = await d365WebApiService.SendPatchRequestAsync(appUserService.AZSystemAppUser, emailStatement, requestBody1);

if (!patchResponse.IsSuccessStatusCode)
{
var responseBody = await patchResponse.Content.ReadAsStringAsync();
_logger.LogError(CustomLogEvent.Process, "Failed to patch the record with the server error {responseBody}", responseBody.CleanLog());

return ProcessResult.Failure(processId, new String[] { responseBody }, 0, 0).SimpleProcessResult;
}
});

return ProcessResult.Completed(processId).SimpleProcessResult;
}

#endregion
}
Original file line number Diff line number Diff line change
Expand Up @@ -197,19 +197,21 @@ public async Task<JsonObject> RunProcessAsync(ID365AppUserService appUserService
recipientsList.Add(contactId);
});
List<HttpRequestMessage> SendEmailFromTemplateRequest = [];
recipientsList?.ForEach(recepientcontact =>
var templateData = await _emailRepository.GetTemplateDataAsync(_notificationSettings.EmailTemplates.First(t => t.TemplateNumber == 201).TemplateNumber);
var serializedtemplateData = JsonConvert.DeserializeObject<List<D365Template>>(templateData.Data.ToString());

recipientsList?.ForEach(recipientContact =>
{
SendEmailFromTemplateRequest.Add(new SendEmailFromTemplateRequest(
new JsonObject(){
{ "TemplateId" , _notificationSettings.EmailTemplates.First(t=>t.TemplateNumber == 201).TemplateId}, //Action Required: A communication regarding OFM funding requires your attention.
{ "TemplateId" , serializedtemplateData?.First().templateid}, //Action Required: A communication regarding OFM funding requires your attention.
{ "Regarding" , new JsonObject {
{ "@odata.type" , "Microsoft.Dynamics.CRM.systemuser"},
{ "systemuserid",_notificationSettings.DefaultSenderId}
}
},
{ "Target", new JsonObject {
{ "ofm_show_notification_on_portal" , false},

{"email_activity_parties", new JsonArray(){
new JsonObject
{
Expand All @@ -218,7 +220,7 @@ public async Task<JsonObject> RunProcessAsync(ID365AppUserService appUserService
},
new JsonObject
{
{ "[email protected]", $"/contacts({recepientcontact})" },
{ "[email protected]", $"/contacts({recipientContact})" },
{ "participationtypemask", 2 } //To Email
}
}},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ private async Task<JsonObject> MarkEmailsAsComppleted(ID365AppUserService appUse
{
var emailToUpdate = new JsonObject {
{ "ofm_sent_on", DateTime.UtcNow },
{ "statuscode", 6 }, // 6 = Pending Send
{ "statuscode", 2 }, // 2 = Completed
{ "statecode", 1 } // 1 = Completed
};

Expand Down
Loading

0 comments on commit 512b34f

Please sign in to comment.