-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathReceiveRemoveDummyGPCodeFunction.cs
More file actions
227 lines (193 loc) · 9.57 KB
/
ReceiveRemoveDummyGPCodeFunction.cs
File metadata and controls
227 lines (193 loc) · 9.57 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
namespace NHS.CohortManager.ParticipantManagementServices;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Common;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Model;
using Model.Constants;
using Model.Enums;
using NHS.CohortManager.ParticipantManagementServices.Models;
public class ReceiveRemoveDummyGpCodeFunction
{
private readonly ILogger<ReceiveRemoveDummyGpCodeFunction> _logger;
private readonly ICreateResponse _createResponse;
private readonly IHttpClientFunction _httpClientFunction;
private readonly IQueueClient _queueClient;
private readonly RemoveDummyGpCodeConfig _config;
private readonly IAuditLogClient _auditLogClient;
private readonly IFunctionContextAuthResolver _authResolver;
private static readonly Regex NonLetterRegex = new(@"[^\p{Lu}\p{Ll}\p{Lt}]", RegexOptions.Compiled, TimeSpan.FromSeconds(1));
public ReceiveRemoveDummyGpCodeFunction(
ILogger<ReceiveRemoveDummyGpCodeFunction> logger,
ICreateResponse createResponse,
IHttpClientFunction httpClientFunction,
IQueueClient queueClient,
IOptions<RemoveDummyGpCodeConfig> config,
IAuditLogClient auditLogClient,
IFunctionContextAuthResolver authResolver)
{
_logger = logger;
_createResponse = createResponse;
_httpClientFunction = httpClientFunction;
_queueClient = queueClient;
_config = config.Value;
_auditLogClient = auditLogClient;
_authResolver = authResolver;
}
/// <summary>
/// Validates and enqueues a dummy GP code removal request to the ServiceNow participant management topic.
/// </summary>
[Function("ReceiveRemoveDummyGPCodeFunction")]
[Authentication(Role.CohortManagerDummyGpRemoval)]
public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "RemoveDummyGPCode")] HttpRequestData req)
{
try
{
var requestBody = await JsonSerializer.DeserializeAsync<RemoveDummyGPCodeRequestBody>(req.Body);
if (requestBody == null)
{
_logger.LogError("Request body deserialised to null");
return _createResponse.CreateHttpResponse(HttpStatusCode.BadRequest, req);
}
var user = _authResolver.GetCis2User(req.FunctionContext);
if (user == null && _authResolver.IsAuthenticationRequired(req.FunctionContext))
{
_logger.LogWarning("Authentication is required but user information could not be retrieved from the function context");
return _createResponse.CreateHttpResponse(HttpStatusCode.Unauthorized, req);
}
await _auditLogClient.AddAsync(new ParticipantAuditMessage
{
NhsNumber = requestBody.NhsNumber,
Source = AuditSource.DummyGpRemoval,
RecordSourceDesc = "Dummy GP Code Removal Form",
CreatedBy = user != null ? user.Uid : "Unknown User",
ScreeningId = (int)ServiceProvider.BSS,
RequestSnapshot = requestBody
});
var validationContext = new ValidationContext(requestBody);
var validationResult = new List<ValidationResult>();
var isRequestValid = Validator.TryValidateObject(requestBody, validationContext, validationResult, true);
if (!isRequestValid)
{
_logger.LogError("Request body failed validation");
return _createResponse.CreateHttpResponse(HttpStatusCode.BadRequest, req);
}
if (!ValidationHelper.ValidateNHSNumber(requestBody.NhsNumber))
{
return _createResponse.CreateHttpResponse(HttpStatusCode.BadRequest, req);
}
var pdsResponse = await _httpClientFunction.SendGetResponse($"{_config.RetrievePdsDemographicURL}?nhsNumber={requestBody.NhsNumber}");
if (pdsResponse.StatusCode == HttpStatusCode.NotFound)
{
return _createResponse.CreateHttpResponse(HttpStatusCode.BadRequest, req);
}
if (pdsResponse.StatusCode != HttpStatusCode.OK)
{
_logger.LogError("Unexpected PDS response status code {StatusCode}", pdsResponse.StatusCode);
return _createResponse.CreateHttpResponse(HttpStatusCode.InternalServerError, req);
}
var pdsDemographic = await pdsResponse.Content.ReadFromJsonAsync<PdsDemographic>();
if (pdsDemographic == null)
{
_logger.LogError("Failed to deserialize PDS demographic response");
return _createResponse.CreateHttpResponse(HttpStatusCode.InternalServerError, req);
}
if (!CheckParticipantDataMatches(requestBody, pdsDemographic))
{
return _createResponse.CreateHttpResponse(HttpStatusCode.BadRequest, req);
}
if (!DateOnly.TryParseExact(pdsDemographic.DateOfBirth, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var pdsDateOfBirth))
{
_logger.LogError("PDS demographic date of birth was missing or invalid for RequestId {RequestId}", requestBody.RequestId);
return _createResponse.CreateHttpResponse(HttpStatusCode.InternalServerError, req);
}
var participant = new ServiceNowParticipant
{
ServiceNowCaseNumber = requestBody.RequestId,
ScreeningId = 1,
NhsNumber = long.Parse(requestBody.NhsNumber),
FirstName = pdsDemographic.FirstName ?? string.Empty,
FamilyName = pdsDemographic.FamilyName ?? string.Empty,
DateOfBirth = pdsDateOfBirth,
BsoCode = pdsDemographic.CurrentPosting ?? string.Empty,
ReasonForAdding = ServiceNowReasonsForAdding.DummyGpCodeRemoval,
RequiredGpCode = null
};
var enqueueResult = await _queueClient.AddAsync(participant, _config.ServiceNowParticipantManagementTopic);
if (!enqueueResult)
{
_logger.LogError("Failed to enqueue remove dummy GP code request for RequestId {RequestId}", requestBody.RequestId);
return _createResponse.CreateHttpResponse(HttpStatusCode.InternalServerError, req);
}
return _createResponse.CreateHttpResponse(HttpStatusCode.Accepted, req);
}
catch (JsonException ex)
{
_logger.LogError(ex, "Failed to deserialize request body");
return _createResponse.CreateHttpResponse(HttpStatusCode.BadRequest, req);
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected error occurred in ReceiveRemoveDummyGPCodeFunction");
return _createResponse.CreateHttpResponse(HttpStatusCode.InternalServerError, req);
}
}
private static bool CheckParticipantDataMatches(RemoveDummyGPCodeRequestBody requestBody, PdsDemographic pdsDemographic)
{
return NormalizedNamesMatch(requestBody.Forename, pdsDemographic.FirstName) &&
NormalizedNamesMatch(requestBody.Surname, pdsDemographic.FamilyName) &&
requestBody.DateOfBirth.ToString("yyyy-MM-dd") == pdsDemographic.DateOfBirth;
}
/// <summary>
/// Normalizes and compares two name strings by removing accents, spaces, hyphens, and special characters.
/// Converts accented characters to their base forms (É→E, Ñ→N, Ö→O) to match database storage behavior.
/// </summary>
/// <param name="name1">First name to compare</param>
/// <param name="name2">Second name to compare</param>
/// <returns>True if the normalized names match (case-insensitive), false otherwise</returns>
private static bool NormalizedNamesMatch(string? name1, string? name2)
{
if (string.IsNullOrWhiteSpace(name1) && string.IsNullOrWhiteSpace(name2))
{
return true;
}
if (string.IsNullOrWhiteSpace(name1) || string.IsNullOrWhiteSpace(name2))
{
return false;
}
var normalized1 = NormalizeName(name1);
var normalized2 = NormalizeName(name2);
if (string.IsNullOrEmpty(normalized1) || string.IsNullOrEmpty(normalized2))
{
return false;
}
return string.Equals(normalized1, normalized2, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Normalizes a name by removing accents and all non-letter characters.
/// This handles spaces, hyphens, apostrophes, and other punctuation.
/// Accented characters like É, Ñ, Ö are converted to their base forms (E, N, O).
/// Uses Unicode NFD normalization to decompose accents, then removes diacritical marks.
/// </summary>
/// <param name="name">The name to normalize</param>
/// <returns>Normalized name containing only unaccented ASCII letters</returns>
private static string NormalizeName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return string.Empty;
}
var trimmedName = name.Trim();
var normalizedString = trimmedName.Normalize(NormalizationForm.FormD);
var lettersOnlyString = NonLetterRegex.Replace(normalizedString, string.Empty);
return lettersOnlyString.Normalize(NormalizationForm.FormC);
}
}