rama creada apartir de master en j

This commit is contained in:
jrojas
2026-06-26 10:29:23 +02:00
parent 319fd3dfb0
commit c1517fda87
2810 changed files with 1927392 additions and 25392 deletions
@@ -12,6 +12,10 @@ using MongoDB.Bson;
namespace adas_core.Application.Customizations.HUVH.UCIN;
/// <summary>
/// Represents a concrete implementation of the <see cref="ICalculatedObservations"/> interface,
/// providing a collection of calculated observation data.
/// </summary>
public class CalculatedObservations : ICalculatedObservations
{
private const string Spo2PreObservationName = "SpO2";
@@ -46,12 +50,23 @@ public class CalculatedObservations : ICalculatedObservations
}
/// <summary>
/// Calculates the active bolus for the specified patient.
/// </summary>
/// <param name="patientId">The unique identifier of the patient for whom the active bolus is calculated.</param>
/// <exception cref="NotImplementedException">Thrown because the method has not been implemented yet.</exception>
public Task CalculateActiveBolus(ObjectId patientId)
{
throw new NotImplementedException();
}
/// <summary>
/// Maps a patient observation by applying the appropriate calculation logic based on its name, handling multi-value interventions, surgeries, complexity scoring, pre/post saturation differences, pain scales, and last defecation value.
/// </summary>
/// <param name="obs">The patient observation to be mapped, which may be transformed depending on its name.</param>
/// <param name="onlyByName">Indicates whether the mapping should be performed using only the observation name.</param>
/// <returns>The mapped patient observation, potentially enriched with computed values, wrapped in a task.</returns>
public async Task<T?> Map<T>(T obs, bool onlyByName = false) where T : BasePatientObservation
{
if (obs.Name is "Intervention_In" or "Intervention_Out") await CalculateInterventionMultiValueObservation(obs);
@@ -78,6 +93,12 @@ public class CalculatedObservations : ICalculatedObservations
}
/// <summary>
/// Maps a <see cref="PatientTreatment"/> by determining its <see cref="OrderControlType"/> based on prior treatments and expiration status.
/// If the placer order number is missing, the treatment is returned unchanged. The order control is set to <see cref="OrderControlType.Xo"/> when previous treatments exist, <see cref="OrderControlType.Dc"/> when the treatment has expired (end time set), or <see cref="OrderControlType.Nw"/> otherwise.
/// </summary>
/// <param name="treatment">The patient treatment to map, including its placer order, end time, and medicines.</param>
/// <returns>The mapped <see cref="PatientTreatment"/> with its order control type and medicines updated.</returns>
public async Task<PatientTreatment> Map(PatientTreatment treatment)
{
var order = treatment.PlacerOrder?.EntityIdentifier; //aquí almacenamos el número de orden
@@ -97,12 +118,22 @@ public class CalculatedObservations : ICalculatedObservations
return treatment;
}
/// <summary>
/// Maps the provided <see cref="PumpObservation"/> instance by returning it unchanged, wrapped in a completed task.
/// </summary>
/// <param name="pumpObservation">The pump observation to map.</param>
/// <returns>A completed <see cref="Task{TResult}"/> containing the provided <see cref="PumpObservation"/>.</returns>
public async Task<PumpObservation> Map(PumpObservation pumpObservation)
{
return await Task.FromResult(pumpObservation);
}
/// <summary>
/// Persists a multivalue medication observation for the specified patient based on the currently active medicines, expiring any previous medication observation recorded for the same patient.
/// </summary>
/// <param name="activeMedicines">The list of active medicines from which distinct medication names are extracted to build the observation value.</param>
/// <param name="patientId">The identifier of the patient for whom the medication observation is calculated and stored.</param>
public async Task CalculateMedicineObservation(List<Medicine> activeMedicines, ObjectId patientId)
{
var medicineObs = new PatientObservation
@@ -129,6 +160,11 @@ public class CalculatedObservations : ICalculatedObservations
medicineObs); //mapObs:volvemos a mapear la observación para que pase por el cálculo de la complejidad
}
/// <summary>
/// Asynchronously retrieves the collection of active treatments associated with the specified patient identifier.
/// </summary>
/// <param name="id">The unique <see cref="ObjectId"/> of the patient whose active treatments should be fetched.</param>
/// <returns>A task that represents the asynchronous operation, containing an <see cref="IEnumerable{T}"/> of nullable <see cref="PatientTreatment"/> instances for the patient.</returns>
public async Task<IEnumerable<PatientTreatment?>> GetActiveTreatmentsByPatient(ObjectId id)
{
var activeTreatments = await _treatmentService.Value.GetActiveTreatmentsByPatient(id);
@@ -136,12 +172,23 @@ public class CalculatedObservations : ICalculatedObservations
}
/// <summary>
/// Asynchronously maps a <see cref="PatientDiagnosis"/> to a target <see cref="PatientDiagnosis"/> representation.
/// </summary>
/// <param name="diagnosis">The source <see cref="PatientDiagnosis"/> instance to be mapped.</param>
/// <returns>A <see cref="Task{PatientDiagnosis}"/> that represents the asynchronous mapping operation, containing the mapped <see cref="PatientDiagnosis"/>.</returns>
/// <exception cref="T:System.NotImplementedException">Thrown when the method is invoked, as the mapping logic has not yet been implemented.</exception>
public Task<PatientDiagnosis> Map(PatientDiagnosis diagnosis)
{
throw new NotImplementedException();
}
/// <summary>
/// Adjusts the time of a new patient observation to ensure it is at least one second after the most recent observation with the same name, preventing time conflicts. If the observation name is null or empty, the method logs an error and returns the observation unchanged.
/// </summary>
/// <param name="newObservation">The new patient observation whose time may be adjusted to follow the most recent observation for the same patient and measurement.</param>
/// <returns>The patient observation with a corrected time if a time conflict was detected, or the original observation if no adjustment was needed or the name was invalid.</returns>
public async Task<PatientObservation?> FixTimeInconsistencyWithLast(PatientObservation newObservation)
{
if (string.IsNullOrEmpty(newObservation.Name))
@@ -169,21 +216,45 @@ public class CalculatedObservations : ICalculatedObservations
return newObservation;
}
/// <summary>
/// Performs a pre-mapping operation on a list of patient observations, returning the list for further processing.
/// </summary>
/// <param name="listToInsert">The list of patient observations to pre-map.</param>
/// <returns>A task that represents the asynchronous operation, containing the provided list of patient observations.</returns>
public Task<List<PatientObservation>> PreMapList(List<PatientObservation> listToInsert)
{
return Task.FromResult(listToInsert);
}
/// <summary>
/// Maps a source alarm onto a patient observation, returning the observation unchanged without applying the alarm data.
/// </summary>
/// <param name="obs">The patient observation that the alarm is to be associated with.</param>
/// <param name="alarmToInsert">The alarm intended to be inserted into the observation.</param>
/// <returns>A task containing the patient observation, returned as-is.</returns>
public Task<PatientObservation> MapSourceAlarm(PatientObservation obs, PatientObservationAlarm alarmToInsert)
{
return Task.FromResult(obs);
}
/// <summary>
/// Sends an alarm notification for the specified patient observation, identified by name and optional alarm code.
/// </summary>
/// <param name="obs">The patient observation that triggers the alarm.</param>
/// <param name="name">The name associated with the alarm.</param>
/// <param name="code">The optional alarm code categorizing the type of alarm to be sent.</param>
/// <exception cref="NotImplementedException">Thrown because the method has not been implemented.</exception>
public Task SendAlarm(PatientObservation obs, string name, AlarmEnum.Name? code)
{
throw new NotImplementedException();
}
/// <summary>
/// Calculates and stores a derived "Pain_Scale" observation in the ADAS coding system based on the provided source observation.
/// Handles the ALPS scale by using its value directly, and the NPASS scale by combining the complementary "NPASS_Sedation" and "NPASS_Analgesia" observations into a single combined value (defaulting to "0" when the complementary observation is not found).
/// Returns without creating a record when the observation is not a <see cref="PatientObservation"/> or when its name does not match any of the supported scales.
/// </summary>
/// <param name="obs">The source patient observation used to derive the pain scale; only instances of <see cref="PatientObservation"/> with a supported name (ALPS, NPASS_Sedation, NPASS_Analgesia) are processed.</param>
private async Task CalculatePainScale(BasePatientObservation obs)
{
if (obs is not PatientObservation pobs) return;
@@ -197,24 +268,24 @@ public class CalculatedObservations : ICalculatedObservations
valueObs = pobs.Value;
break;
case "NPASS_Sedation":
{
//Buscamos la complementaria "NPASS Analgesia"
var analgesiaObs =
await _observationService.Value.FindLastObservations(obs.PatientId, 1, ["NPASS_Analgesia"]);
var analgesiaValue = analgesiaObs.FirstOrDefault()?.Value.ToString() ?? "0";
{
//Buscamos la complementaria "NPASS Analgesia"
var analgesiaObs =
await _observationService.Value.FindLastObservations(obs.PatientId, 1, ["NPASS_Analgesia"]);
var analgesiaValue = analgesiaObs.FirstOrDefault()?.Value.ToString() ?? "0";
valueObs = $"{pobs.Value}/{analgesiaValue}";
}
valueObs = $"{pobs.Value}/{analgesiaValue}";
}
break;
case "NPASS_Analgesia":
{
//Buscamos la complementaria "NPASS Sedation"
var sedationObs =
await _observationService.Value.FindLastObservations(obs.PatientId, 1, ["NPASS_Sedation"]);
var sedationValue = sedationObs.FirstOrDefault()?.Value.ToString() ?? "0";
{
//Buscamos la complementaria "NPASS Sedation"
var sedationObs =
await _observationService.Value.FindLastObservations(obs.PatientId, 1, ["NPASS_Sedation"]);
var sedationValue = sedationObs.FirstOrDefault()?.Value.ToString() ?? "0";
valueObs = $"{sedationValue}/{pobs.Value}";
}
valueObs = $"{sedationValue}/{pobs.Value}";
}
break;
default:
return;
@@ -232,6 +303,11 @@ public class CalculatedObservations : ICalculatedObservations
_ = _observationService.Value.InsertObservation(painScaleObs, mapObs: false);
}
/// <summary>
/// Calculates the last defecation value for a patient observation by assigning the observation's time, converted to local time and formatted as a date/time string, to its value. If the observation is not a <see cref="PatientObservation"/>, it is returned unchanged.
/// </summary>
/// <param name="obs">The base patient observation to process.</param>
/// <returns>The original <see cref="BasePatientObservation"/> if it is not a <see cref="PatientObservation"/>; otherwise, the <see cref="PatientObservation"/> with its value set to the locally formatted observation time.</returns>
private static BasePatientObservation CalculateLastDefecationValue(BasePatientObservation obs)
{
if (obs is not PatientObservation pobs) return obs;
@@ -246,6 +322,10 @@ public class CalculatedObservations : ICalculatedObservations
}
/// <summary>
/// Calculates and persists a multi-value observation by appending the current value to the existing list of values for the corresponding "Multivalue" observation. Expirates the previous multi-value observation before inserting the new one.
/// </summary>
/// <param name="obs">The base patient observation used to derive the multi-value observation; it must be a <see cref="PatientObservation"/> with a non-empty name and a string value.</param>
private async Task CalculateMultiValueObservation(BasePatientObservation obs)
{
//El valor de la observación es un array de strings
@@ -298,6 +378,10 @@ public class CalculatedObservations : ICalculatedObservations
await _observationService.Value.InsertObservation(newObservation);
}
/// <summary>
/// Calculates and persists a multi-value observation that aggregates the active intervention groups (e.g., devices, routes) for a patient based on incoming "<c>_In</c>" and "<c>_Out</c>" observations. Handles the insertion of new groups (with special duplicate prevention for respiratory devices) and the removal of groups when a corresponding "Out" event is received, expiring the previous multi-value observation and inserting a new one when the resulting set is not empty.
/// </summary>
/// <param name="obs">The base patient observation that triggered the calculation; expected to be a <see cref="PatientObservation"/> with a non-empty name and a string value representing the intervention group.</param>
private async Task CalculateInterventionMultiValueObservation(BasePatientObservation obs)
{
if (obs is not PatientObservation pobs || string.IsNullOrEmpty(obs.Name) ||
@@ -380,6 +464,14 @@ public class CalculatedObservations : ICalculatedObservations
await _observationService.Value.InsertObservation(newObservation);
}
/// <summary>
/// Extracts a numeric code from the observation value, normalizes it, and resolves the corresponding intervention
/// by looking it up in the mapping repository. Returns false when the code cannot be parsed as a number or when no
/// matching intervention is found.
/// </summary>
/// <param name="valueObs">Observation text from which the leading token is taken as the candidate intervention code.</param>
/// <param name="r">When the method returns true, contains the resolved intervention's type, name, and group; otherwise null.</param>
/// <returns><c>true</c> if a matching intervention was found; <c>false</c> if the code is not numeric or the lookup yields no result.</returns>
private bool GetInterventionValue(string valueObs, out (string type, string Name, string Group)? r)
{
var code = valueObs.Split(" ")[0]; //
@@ -404,6 +496,10 @@ public class CalculatedObservations : ICalculatedObservations
* cuando entra una nueva observación que afecte a complejidad, se recalcula de 0 para no tener que estar pendiente de qué puntos corresponden a qué observación
* Valor máximo 46 Guardamos la observación que nos llega y recalculamos complejidad.
*/
/// <summary>
/// Calcula la complejidad del paciente en función de las observaciones registradas.
/// </summary>
/// <param name="obs">Observación del paciente que se va a evaluar para recalcular su complejidad.</param>
private async Task CalculateComplexity(BasePatientObservation obs)
{
var pobs = obs as PatientObservation;
@@ -466,8 +562,15 @@ public class CalculatedObservations : ICalculatedObservations
await _observationService.Value.InsertObservation(complexity, mapObs: false);
}
/// <summary>
/// Calculates the total complexity value for a multivalue observation belonging to a patient. Uses the supplied observation when provided; otherwise retrieves the most recent one from the database and sums the complexity values resolved via the mapping utility, returning 0 when no data is available.
/// </summary>
/// <param name="patientId">The identifier of the patient whose observation is being evaluated.</param>
/// <param name="observationName">The name of the multivalue observation to look up and calculate complexity for.</param>
/// <param name="observation">An optional pre-loaded observation that overrides the database lookup when supplied.</param>
/// <returns>The aggregated complexity value for the observation, or 0 if no observation or values are found.</returns>
private async Task<int> CalculateMultivalueObservationComplexityValue(ObjectId patientId, string observationName,
PatientObservation? observation = null)
PatientObservation? observation = null)
{
var result =
await _observationService.Value.FindLastObservations(patientId, 1, [observationName]);
@@ -486,6 +589,13 @@ public class CalculatedObservations : ICalculatedObservations
}
/// <summary>
/// Calculates the complexity value associated with a newborn's weight observation for the specified patient.
/// When <paramref name="pobs"/> is null, the most recent stored "Newborn_Weight" observation is used; otherwise the provided observation is used, converting from kilograms when applicable. Returns 0 when no value can be retrieved or parsed, or when the observation name is missing, and otherwise returns the complexity value resolved via the mapping utilities.
/// </summary>
/// <param name="patientId">The identifier of the patient whose newborn weight complexity is being calculated.</param>
/// <param name="pobs">An optional patient observation to use instead of the latest stored one; if provided with "kg" units, its value is converted.</param>
/// <returns>The calculated newborn weight complexity value, or 0 when no valid value is available.</returns>
private async Task<int> CalculateWeightNewBornValue(ObjectId patientId, PatientObservation? pobs = null)
{
var result =
@@ -522,6 +632,12 @@ public class CalculatedObservations : ICalculatedObservations
return weightNewBornValue;
}
/// <summary>
/// Parses a weight observation by converting its value to grams (multiplying by 1000) and assigning the "gr" unit.
/// If the value cannot be parsed as a double, the error is logged and the original observation is returned unchanged.
/// </summary>
/// <param name="obs">The patient observation containing the weight value to parse and convert.</param>
/// <returns>The patient observation with the value converted to grams, or the original observation if the value could not be parsed.</returns>
private PatientObservation ParseWeight(PatientObservation obs)
{
if (!double.TryParse(obs.Value.ToString(), out var dValue))
@@ -535,7 +651,13 @@ public class CalculatedObservations : ICalculatedObservations
return obs;
}
/// <summary>
/// Calculates the SpO2 difference between pre and post observations for a patient and persists the resulting SpO2_Diff and combined pre/post observations.
/// Handles both pre and post observation entry points, adjusts the timestamp to the earlier of the two observations, and defaults to 0 when a value cannot be parsed as a double.
/// </summary>
/// <param name="obs">The incoming patient observation (either a pre or post SpO2 measurement) used to drive the calculation and identify the counterpart observation.</param>
/// <returns>A task that represents the asynchronous insert of the derived observations.</returns>
private async Task CalculateSaturation_DiffObservation(BasePatientObservation obs)
{
var toSearchList = new List<string>();
@@ -593,6 +715,11 @@ public class CalculatedObservations : ICalculatedObservations
}
}
/// <summary>
/// Checks for expired patient treatments and updates the matching treatment's <see cref="OrderControlType"/> to <c>DC</c> when its end time is in the future, returning the remaining active treatments for the same patient.
/// </summary>
/// <param name="treatment">The patient treatment being evaluated, used to locate the existing record by its placer order entity identifier and to persist the updated state.</param>
/// <returns>A task that yields the list of active patient treatments for the patient that are not the same placer order as the supplied treatment.</returns>
private async Task<List<PatientTreatment>> CheckExpiredPatientTreatments(PatientTreatment treatment)
{
//si el tratamiento ha expirado actualizamos el OrderControl a DC y devolvemos las que siguen activas
@@ -622,6 +749,14 @@ public class CalculatedObservations : ICalculatedObservations
return result;
}
/// <summary>
/// Validates the medicines requested in a patient treatment, handling nutrition items by creating
/// dedicated observations, detecting vasoactive drugs to record a flag, and combining remaining
/// medicines with the patient's active treatment medicines to calculate a unified medicine observation.
/// Medicines that are not found by code are skipped, and the method returns early when no new
/// medicines remain after filtering.
/// </summary>
/// <param name="treatment">The patient treatment whose requested give codes are inspected for medicines, nutrition items, and vasoactive drugs.</param>
private async Task CheckTreatmentMedicines(PatientTreatment treatment)
{
var newMedicines = new List<Medicine>();
@@ -679,6 +814,11 @@ public class CalculatedObservations : ICalculatedObservations
await CalculateMedicineObservation(uniqueMedicines, treatment.PatientId);
}
/// <summary>
/// Creates a new feeding/nutrition observation for the specified patient. When the value indicates parenteral feeding, the observation name is normalized to "Parenteral" and the value to "SI". Any previous non-expired observation with the same name is marked as expired before the new one is inserted.
/// </summary>
/// <param name="value">The feeding type value to record; if it contains "parenteral" (case-insensitive), the observation is stored as a parenteral entry.</param>
/// <param name="patientId">The identifier of the patient to whom the observation belongs.</param>
private async Task CreateNutritionObservation(string value, ObjectId patientId)
{
var nutritionObs = new PatientObservation