Skip to content

Commit

Permalink
Refactor inspection findings/teams code
Browse files Browse the repository at this point in the history
  • Loading branch information
andchiind committed Dec 19, 2024
1 parent 038f29f commit 2dc31ea
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 37 deletions.
37 changes: 7 additions & 30 deletions backend/api/EventHandlers/InspectionFindingEventHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,46 +27,33 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
while (!stoppingToken.IsCancellationRequested)
{
var now = DateTime.UtcNow;

var nextExecutionTime = CrontabSchedule.Parse(_cronExpression).GetNextOccurrence(now);

var delay = nextExecutionTime - now;

if (delay.TotalMilliseconds > 0)
{
await Task.Delay(delay, stoppingToken);
}

var lastReportingTime = DateTime.UtcNow - _timeSpan;

var inspectionFindings = await InspectionFindingService.RetrieveInspectionFindings(lastReportingTime, readOnly: true);

logger.LogInformation("Found {count} inspection findings in last {interval}", inspectionFindings.Count, _timeSpan);

if (inspectionFindings.Count > 0)
{
var findingsList = await GenerateFindingsList(inspectionFindings);

string adaptiveCardJson = GenerateAdaptiveCard($"Rapport {DateTime.UtcNow:yyyy-MM-dd HH}", inspectionFindings.Count, findingsList);

string url = GetWebhookURL(configuration, "TeamsInspectionFindingsWebhook");

var client = new HttpClient();

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var content = new StringContent(adaptiveCardJson, Encoding.UTF8, "application/json");

var response = await client.PostAsync(url, content, stoppingToken);

if (response.StatusCode == HttpStatusCode.OK)
{
logger.LogInformation("Post request via teams incomming webhook was successful, Status Code: {response.StatusCode}", response.StatusCode);
}
else
if (response.StatusCode != HttpStatusCode.OK)
{
string errorBody = await response.Content.ReadAsStringAsync(stoppingToken);
logger.LogError($"Webhook request failed with status code {response.StatusCode}. Response body: {errorBody}");
logger.LogWarning($"Webhook request failed with status code {response.StatusCode}. Response body: {errorBody}");
}
}
}
Expand All @@ -93,13 +80,7 @@ private async Task<List<Finding>> GenerateFindingsList(List<InspectionFinding> i

findingsList.Add(finding);
}
else
{
logger.LogInformation("Failed to generate a finding since TagId in missionTask or Area in MissionRun is null");
continue;
}
}
logger.LogInformation("Findings List sucessfully generated, adaptive Card will be generated next");
return findingsList;
}

Expand All @@ -109,7 +90,6 @@ public static string GenerateAdaptiveCard(string title, int numberOfFindings, Li

foreach (var finding in findingsReports)
{

var factsArray = new JArray(
new JObject(new JProperty("name", "Anlegg"), new JProperty("value", finding.PlantName)),
new JObject(new JProperty("name", "Område"), new JProperty("value", finding.InspectionAreaName)),
Expand All @@ -136,18 +116,15 @@ public static string GenerateAdaptiveCard(string title, int numberOfFindings, Li
new JProperty("activityTitle", "The following inspection findings were identified:")));

foreach (var findingObj in findingsJsonArray)
{
sections.Add(findingObj);
}

var adaptiveCardObj = new JObject(
new JProperty("summary", "Inspection Findings Report"),
new JProperty("themeColor", "0078D7"),
new JProperty("title", $"Inspection Findings: \"{title}\""),
new JProperty("sections", sections));

string adaptiveCardJson = adaptiveCardObj.ToString(Formatting.Indented);
return adaptiveCardJson;
return adaptiveCardObj.ToString(Formatting.Indented);
}

public static string GetWebhookURL(IConfiguration configuration, string secretName)
Expand All @@ -171,10 +148,10 @@ public static string GetWebhookURL(IConfiguration configuration, string secretNa

public class Finding(string tagId, string plantName, string inspectionAreaName, string findingDescription, DateTime timestamp)
{
public string TagId { get; set; } = tagId ?? throw new ArgumentNullException(nameof(tagId));
public string PlantName { get; set; } = plantName ?? throw new ArgumentNullException(nameof(plantName));
public string InspectionAreaName { get; set; } = inspectionAreaName ?? throw new ArgumentNullException(nameof(inspectionAreaName));
public string FindingDescription { get; set; } = findingDescription ?? throw new ArgumentNullException(nameof(findingDescription));
public string TagId { get; set; } = tagId;
public string PlantName { get; set; } = plantName;
public string InspectionAreaName { get; set; } = inspectionAreaName;
public string FindingDescription { get; set; } = findingDescription;
public DateTime Timestamp { get; set; } = timestamp;
}
}
11 changes: 4 additions & 7 deletions backend/api/EventHandlers/TeamsMessageEventHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,12 @@ private async void OnTeamsMessageReceived(object? sender, TeamsMessageEventArgs
_logger.LogError(ex, "Failed to send message to Teams");
return;
}
if (response.IsSuccessStatusCode)

if (!response.IsSuccessStatusCode)
{
_logger.LogInformation("Post request via teams incomming webhook was successful, Status Code: {response.StatusCode}", response.StatusCode);
return;
string errorBody = await response.Content.ReadAsStringAsync();
_logger.LogError($"Webhook request failed with status code {response.StatusCode}. Response body: {errorBody}");
}

string errorBody = await response.Content.ReadAsStringAsync();
_logger.LogError($"Webhook request failed with status code {response.StatusCode}. Response body: {errorBody}");

}

private static StringContent CreateTeamsMessageCard(string message)
Expand Down

0 comments on commit 2dc31ea

Please sign in to comment.