|
| 1 | +namespace NHS.CohortManager.ParticipantManagementServices; |
| 2 | + |
| 3 | +using System.ComponentModel.DataAnnotations; |
| 4 | +using System.Globalization; |
| 5 | +using System.Net; |
| 6 | +using System.Net.Http.Json; |
| 7 | +using System.Text; |
| 8 | +using System.Text.Json; |
| 9 | +using System.Text.RegularExpressions; |
| 10 | +using Common; |
| 11 | +using Microsoft.Azure.Functions.Worker; |
| 12 | +using Microsoft.Azure.Functions.Worker.Http; |
| 13 | +using Microsoft.Extensions.Logging; |
| 14 | +using Microsoft.Extensions.Options; |
| 15 | +using Model; |
| 16 | +using Model.Constants; |
| 17 | +using NHS.CohortManager.ParticipantManagementServices.Models; |
| 18 | + |
| 19 | +public class ReceiveRemoveDummyGpCodeFunction |
| 20 | +{ |
| 21 | + private readonly ILogger<ReceiveRemoveDummyGpCodeFunction> _logger; |
| 22 | + private readonly ICreateResponse _createResponse; |
| 23 | + private readonly IHttpClientFunction _httpClientFunction; |
| 24 | + private readonly IQueueClient _queueClient; |
| 25 | + private readonly RemoveDummyGpCodeConfig _config; |
| 26 | + |
| 27 | + private static readonly Regex NonLetterRegex = new(@"[^\p{Lu}\p{Ll}\p{Lt}]", RegexOptions.Compiled, TimeSpan.FromSeconds(1)); |
| 28 | + |
| 29 | + public ReceiveRemoveDummyGpCodeFunction( |
| 30 | + ILogger<ReceiveRemoveDummyGpCodeFunction> logger, |
| 31 | + ICreateResponse createResponse, |
| 32 | + IHttpClientFunction httpClientFunction, |
| 33 | + IQueueClient queueClient, |
| 34 | + IOptions<RemoveDummyGpCodeConfig> config) |
| 35 | + { |
| 36 | + _logger = logger; |
| 37 | + _createResponse = createResponse; |
| 38 | + _httpClientFunction = httpClientFunction; |
| 39 | + _queueClient = queueClient; |
| 40 | + _config = config.Value; |
| 41 | + } |
| 42 | + |
| 43 | + /// <summary> |
| 44 | + /// Validates and enqueues a dummy GP code removal request to the ServiceNow participant management topic. |
| 45 | + /// </summary> |
| 46 | + [Function("ReceiveRemoveDummyGPCodeFunction")] |
| 47 | + public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "RemoveDummyGPCode")] HttpRequestData req) |
| 48 | + { |
| 49 | + try |
| 50 | + { |
| 51 | + var requestBody = await JsonSerializer.DeserializeAsync<RemoveDummyGPCodeRequestBody>(req.Body); |
| 52 | + if (requestBody == null) |
| 53 | + { |
| 54 | + _logger.LogError("Request body deserialised to null"); |
| 55 | + return _createResponse.CreateHttpResponse(HttpStatusCode.BadRequest, req); |
| 56 | + } |
| 57 | + |
| 58 | + var validationContext = new ValidationContext(requestBody); |
| 59 | + var validationResult = new List<ValidationResult>(); |
| 60 | + var isRequestValid = Validator.TryValidateObject(requestBody, validationContext, validationResult, true); |
| 61 | + |
| 62 | + if (!isRequestValid) |
| 63 | + { |
| 64 | + _logger.LogError("Request body failed validation"); |
| 65 | + return _createResponse.CreateHttpResponse(HttpStatusCode.BadRequest, req); |
| 66 | + } |
| 67 | + |
| 68 | + if (!ValidationHelper.ValidateNHSNumber(requestBody.NhsNumber)) |
| 69 | + { |
| 70 | + return _createResponse.CreateHttpResponse(HttpStatusCode.BadRequest, req); |
| 71 | + } |
| 72 | + |
| 73 | + var pdsResponse = await _httpClientFunction.SendGetResponse($"{_config.RetrievePdsDemographicURL}?nhsNumber={requestBody.NhsNumber}"); |
| 74 | + |
| 75 | + if (pdsResponse.StatusCode == HttpStatusCode.NotFound) |
| 76 | + { |
| 77 | + return _createResponse.CreateHttpResponse(HttpStatusCode.BadRequest, req); |
| 78 | + } |
| 79 | + |
| 80 | + if (pdsResponse.StatusCode != HttpStatusCode.OK) |
| 81 | + { |
| 82 | + _logger.LogError("Unexpected PDS response status code {StatusCode}", pdsResponse.StatusCode); |
| 83 | + return _createResponse.CreateHttpResponse(HttpStatusCode.InternalServerError, req); |
| 84 | + } |
| 85 | + |
| 86 | + var pdsDemographic = await pdsResponse.Content.ReadFromJsonAsync<PdsDemographic>(); |
| 87 | + if (pdsDemographic == null) |
| 88 | + { |
| 89 | + _logger.LogError("Failed to deserialize PDS demographic response"); |
| 90 | + return _createResponse.CreateHttpResponse(HttpStatusCode.InternalServerError, req); |
| 91 | + } |
| 92 | + |
| 93 | + if (!CheckParticipantDataMatches(requestBody, pdsDemographic)) |
| 94 | + { |
| 95 | + return _createResponse.CreateHttpResponse(HttpStatusCode.BadRequest, req); |
| 96 | + } |
| 97 | + |
| 98 | + if (!DateOnly.TryParseExact(pdsDemographic.DateOfBirth, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var pdsDateOfBirth)) |
| 99 | + { |
| 100 | + _logger.LogError("PDS demographic date of birth was missing or invalid for RequestId {RequestId}", requestBody.RequestId); |
| 101 | + return _createResponse.CreateHttpResponse(HttpStatusCode.InternalServerError, req); |
| 102 | + } |
| 103 | + |
| 104 | + var participant = new ServiceNowParticipant |
| 105 | + { |
| 106 | + ServiceNowCaseNumber = requestBody.RequestId, |
| 107 | + ScreeningId = 1, |
| 108 | + NhsNumber = long.Parse(requestBody.NhsNumber), |
| 109 | + FirstName = pdsDemographic.FirstName ?? string.Empty, |
| 110 | + FamilyName = pdsDemographic.FamilyName ?? string.Empty, |
| 111 | + DateOfBirth = pdsDateOfBirth, |
| 112 | + BsoCode = pdsDemographic.CurrentPosting ?? string.Empty, |
| 113 | + ReasonForAdding = ServiceNowReasonsForAdding.DummyGpCodeRemoval, |
| 114 | + RequiredGpCode = null |
| 115 | + }; |
| 116 | + |
| 117 | + var enqueueResult = await _queueClient.AddAsync(participant, _config.ServiceNowParticipantManagementTopic); |
| 118 | + if (!enqueueResult) |
| 119 | + { |
| 120 | + _logger.LogError("Failed to enqueue remove dummy GP code request for RequestId {RequestId}", requestBody.RequestId); |
| 121 | + return _createResponse.CreateHttpResponse(HttpStatusCode.InternalServerError, req); |
| 122 | + } |
| 123 | + |
| 124 | + return _createResponse.CreateHttpResponse(HttpStatusCode.Accepted, req); |
| 125 | + } |
| 126 | + catch (JsonException ex) |
| 127 | + { |
| 128 | + _logger.LogError(ex, "Failed to deserialize request body"); |
| 129 | + return _createResponse.CreateHttpResponse(HttpStatusCode.BadRequest, req); |
| 130 | + } |
| 131 | + catch (Exception ex) |
| 132 | + { |
| 133 | + _logger.LogError(ex, "Unexpected error occurred in ReceiveRemoveDummyGPCodeFunction"); |
| 134 | + return _createResponse.CreateHttpResponse(HttpStatusCode.InternalServerError, req); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + private static bool CheckParticipantDataMatches(RemoveDummyGPCodeRequestBody requestBody, PdsDemographic pdsDemographic) |
| 139 | + { |
| 140 | + return NormalizedNamesMatch(requestBody.Forename, pdsDemographic.FirstName) && |
| 141 | + NormalizedNamesMatch(requestBody.Surname, pdsDemographic.FamilyName) && |
| 142 | + requestBody.DateOfBirth.ToString("yyyy-MM-dd") == pdsDemographic.DateOfBirth; |
| 143 | + } |
| 144 | + |
| 145 | + /// <summary> |
| 146 | + /// Normalizes and compares two name strings by removing accents, spaces, hyphens, and special characters. |
| 147 | + /// Converts accented characters to their base forms (É→E, Ñ→N, Ö→O) to match database storage behavior. |
| 148 | + /// </summary> |
| 149 | + /// <param name="name1">First name to compare</param> |
| 150 | + /// <param name="name2">Second name to compare</param> |
| 151 | + /// <returns>True if the normalized names match (case-insensitive), false otherwise</returns> |
| 152 | + private static bool NormalizedNamesMatch(string? name1, string? name2) |
| 153 | + { |
| 154 | + if (string.IsNullOrWhiteSpace(name1) && string.IsNullOrWhiteSpace(name2)) |
| 155 | + { |
| 156 | + return true; |
| 157 | + } |
| 158 | + |
| 159 | + if (string.IsNullOrWhiteSpace(name1) || string.IsNullOrWhiteSpace(name2)) |
| 160 | + { |
| 161 | + return false; |
| 162 | + } |
| 163 | + |
| 164 | + var normalized1 = NormalizeName(name1); |
| 165 | + var normalized2 = NormalizeName(name2); |
| 166 | + |
| 167 | + if (string.IsNullOrEmpty(normalized1) || string.IsNullOrEmpty(normalized2)) |
| 168 | + { |
| 169 | + return false; |
| 170 | + } |
| 171 | + |
| 172 | + return string.Equals(normalized1, normalized2, StringComparison.OrdinalIgnoreCase); |
| 173 | + } |
| 174 | + |
| 175 | + /// <summary> |
| 176 | + /// Normalizes a name by removing accents and all non-letter characters. |
| 177 | + /// This handles spaces, hyphens, apostrophes, and other punctuation. |
| 178 | + /// Accented characters like É, Ñ, Ö are converted to their base forms (E, N, O). |
| 179 | + /// Uses Unicode NFD normalization to decompose accents, then removes diacritical marks. |
| 180 | + /// </summary> |
| 181 | + /// <param name="name">The name to normalize</param> |
| 182 | + /// <returns>Normalized name containing only unaccented ASCII letters</returns> |
| 183 | + private static string NormalizeName(string name) |
| 184 | + { |
| 185 | + if (string.IsNullOrWhiteSpace(name)) |
| 186 | + { |
| 187 | + return string.Empty; |
| 188 | + } |
| 189 | + |
| 190 | + var trimmedName = name.Trim(); |
| 191 | + var normalizedString = trimmedName.Normalize(NormalizationForm.FormD); |
| 192 | + var lettersOnlyString = NonLetterRegex.Replace(normalizedString, string.Empty); |
| 193 | + |
| 194 | + return lettersOnlyString.Normalize(NormalizationForm.FormC); |
| 195 | + } |
| 196 | +} |
0 commit comments