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
@@ -11,6 +11,10 @@ using MongoDB.Driver;
namespace adas_core.Application.Customizations.HUVH.UCIA;
/// <summary>
/// Represents a concrete implementation of the <see cref="ICalculatedObservations"/> interface,
/// providing functionality to manage a collection of calculated observations.
/// </summary>
public class CalculatedObservations : ICalculatedObservations
{
private const string CodingSystem = "ADAS";
@@ -53,12 +57,23 @@ public class CalculatedObservations : ICalculatedObservations
}
/// <summary>
/// Asynchronously calculates the active bolus for the specified patient.
/// </summary>
/// <param name="patientId">The identifier of the patient whose active bolus should be calculated.</param>
/// <exception cref="NotImplementedException">Thrown when the method is invoked, as the calculation logic has not yet been implemented.</exception>
public Task CalculateActiveBolus(ObjectId patientId)
{
throw new NotImplementedException();
}
/// <summary>
/// Processes a patient observation by dispatching to the appropriate domain-specific calculation based on the observation name, handling over-sedation, ventilation mode, ECMO location, over-analgesia, driving pressure, ROX index, diuresis, and rehabilitation alarm assessments.
/// </summary>
/// <param name="obs">The patient observation to map; may be replaced with the result of the matched asynchronous calculation when applicable.</param>
/// <param name="onlyByName">Indicates whether the mapping should be performed using only the observation's name.</param>
/// <returns>The processed patient observation, potentially updated by the applicable calculation.</returns>
public async Task<T?> Map<T>(T obs, bool onlyByName = false) where T : BasePatientObservation
{
if (obs.Name is "PSI" or "RASS" or "TS") _ = CalculateOverSedation(obs);
@@ -81,6 +96,11 @@ public class CalculatedObservations : ICalculatedObservations
return obs;
}
/// <summary>
/// Maps a <see cref="PatientTreatment"/> by determining the appropriate order control status, handling cases for missing placer orders, previous expired treatments, and treatments with a defined end time.
/// </summary>
/// <param name="treatment">The patient treatment to map and update.</param>
/// <returns>The patient treatment with its order control set according to the evaluated business rules.</returns>
public async Task<PatientTreatment> Map(PatientTreatment treatment)
{
var order = treatment.PlacerOrder?.EntityIdentifier; //aquí almacenamos el número de orden
@@ -100,12 +120,22 @@ public class CalculatedObservations : ICalculatedObservations
return treatment;
}
/// <summary>
/// Maps a <see cref="PumpObservation"/> instance to its output representation as a pass-through operation.
/// </summary>
/// <param name="pumpObservation">The pump observation to map.</param>
/// <returns>A completed task containing the provided <see cref="PumpObservation"/>.</returns>
public async Task<PumpObservation> Map(PumpObservation pumpObservation)
{
return await Task.FromResult(pumpObservation);
}
/// <summary>
/// Calculates medicine observations for a patient by validating the categories of their active medications. Typically invoked by the scheduler service to review current medication statuses.
/// </summary>
/// <param name="activeMedicines">The list of currently active medicines assigned to the patient.</param>
/// <param name="patientId">The unique identifier of the patient whose medication categories will be checked.</param>
public Task CalculateMedicineObservation(List<Medicine> activeMedicines, ObjectId patientId)
{
//Esto viene del schedulerService para chequear los medicamentos activos
@@ -114,6 +144,11 @@ public class CalculatedObservations : ICalculatedObservations
return Task.CompletedTask;
}
/// <summary>
/// Retrieves all currently active treatments associated with the specified patient.
/// </summary>
/// <param name="id">The unique identifier of the patient whose active treatments should be retrieved.</param>
/// <returns>A collection of <see cref="PatientTreatment"/> objects representing the patient's active treatments.</returns>
public async Task<IEnumerable<PatientTreatment?>> GetActiveTreatmentsByPatient(ObjectId id)
{
var activeTreatments = await _treatmentService.Value.GetActiveTreatmentsByPatient(id);
@@ -121,13 +156,24 @@ public class CalculatedObservations : ICalculatedObservations
}
/// <summary>
/// Asynchronously maps a <see cref="PatientDiagnosis"/> instance to its corresponding data representation or transfer model.
/// </summary>
/// <param name="diagnosis">The <see cref="PatientDiagnosis"/> to be mapped.</param>
/// <returns>A task that represents the asynchronous mapping operation, containing the resulting <see cref="PatientDiagnosis"/>.</returns>
/// <exception cref="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>
/// Ensures the timestamp of the new observation does not collide with the most recent observation for the same patient and observation name. If the new observation's time is equal to or earlier than the last observation's time (compared at second precision), the new observation's time is incremented by one second. If the observation name is null or empty, the new observation is returned unchanged after logging an error.
/// </summary>
/// <param name="newObservation">The new patient observation whose timestamp should be adjusted to avoid time inconsistencies with prior observations.</param>
/// <returns>The patient observation, with its <c>Time</c> adjusted when a time collision is detected, or the original observation when its name is null or empty.</returns>
public async Task<PatientObservation?> FixTimeInconsistencyWithLast(PatientObservation newObservation)
{
if (string.IsNullOrEmpty(newObservation.Name))
@@ -155,21 +201,46 @@ public class CalculatedObservations : ICalculatedObservations
return newObservation;
}
/// <summary>
/// Pre-maps the provided list of patient observations, returning it as a completed task for asynchronous processing pipelines.
/// </summary>
/// <param name="listToInsert">The list of patient observations to pre-map before insertion.</param>
/// <returns>A completed task 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 to a patient observation. Returns the provided observation without applying changes from the alarm.
/// </summary>
/// <param name="obs">The patient observation to be returned as the mapping result.</param>
/// <param name="alarmToInsert">The patient observation alarm intended to be associated with the observation.</param>
/// <returns>A task containing the patient observation.</returns>
public Task<PatientObservation> MapSourceAlarm(PatientObservation obs, PatientObservationAlarm alarmToInsert)
{
return Task.FromResult(obs);
}
/// <summary>
/// Asynchronously sends an alarm notification associated with a patient observation, identified by a name and an 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 alarm, or null if no code is specified.</param>
/// <returns>A task that represents the asynchronous alarm sending operation.</returns>
/// <exception cref="NotImplementedException">Thrown to indicate that the method has not yet been implemented.</exception>
public Task SendAlarm(PatientObservation obs, string name, AlarmEnum.Name? code)
{
throw new NotImplementedException();
}
/// <summary>
/// Evaluates a rehabilitation observation and marks it as Alert when the degree value is between 0 and 2 (inclusive) for more than seven consecutive days.
/// The observation is returned unchanged when it is not a patient observation, its value cannot be parsed as an integer, or its value is greater than 2.
/// </summary>
/// <param name="obs">The base patient observation to evaluate for the rehabilitation alarm condition.</param>
/// <returns>The observation with its status set to Alert when the six previous rehabilitation observations also fall within the 0-2 range; otherwise the observation is returned as-is.</returns>
private async Task<BasePatientObservation> CalculateRehabilitationAlarm(BasePatientObservation obs)
{
//En rojo si el grado es de 0 a 2 incluidos, por más de 7 días
@@ -186,6 +257,14 @@ public class CalculatedObservations : ICalculatedObservations
return obs;
}
/// <summary>
/// Calculates the diuresis index in ml/kg/h for a patient by summing the diuresis values from the last six hours
/// and dividing by the patient's weight and by six. Handles trigger observations of type "Diuresis" (which also
/// pulls the latest recorded weight) and "Weight" (which supplies the weight directly), and aborts with a warning
/// when fewer than three diuresis values are available or the weight is not greater than zero.
/// </summary>
/// <param name="obs">The incoming base patient observation; only <see cref="PatientObservation"/> instances whose
/// <c>Name</c> is "Diuresis" or "Weight" are processed, otherwise the method returns without changes.</param>
private async Task CalculateDiuresis(BasePatientObservation obs)
{
// Calculado como el sumatorio de la Diuresis de las últimas 6h
@@ -262,6 +341,10 @@ public class CalculatedObservations : ICalculatedObservations
}
/// <summary>
/// Calculates the ROX Index by dividing the SpO2/FiO2 ratio by the respiratory rate (FR) and persists the result as a new <c>Rox_Index</c> observation. The method supports both directions of the calculation: when the incoming observation is the SpO2/FiO2 ratio, it retrieves the latest FR, and vice versa. It silently returns if the observation is not a <c>PatientObservation</c>, if the observation name is not recognized, if the required paired observation cannot be found, if its value cannot be parsed, or if the FR value is zero (to avoid division by zero).
/// </summary>
/// <param name="obs">The base patient observation that triggers the ROX index calculation. Only observations named <c>SpO2_FiO2_Ratio</c> or <c>FR</c> are processed; any other type or name is ignored.</param>
private async Task CalculateRoxIndex(BasePatientObservation obs)
{
// Cálculo dividiendo el ratio SpO2/FiO2 entre la FR
@@ -310,6 +393,10 @@ public class CalculatedObservations : ICalculatedObservations
await _observationService.Value.InsertObservation(roxIndexObs, mapObs: false);
}
/// <summary>
/// Calculates the driving pressure for a patient as the difference between Pmeset and PEEP when a new Pmeset or PEEP observation is provided. Looks up the complementary observation to obtain the missing value, then creates and persists a "Driving_Pressure" observation. Returns early if the input is not a PatientObservation, the observation name is neither Pmeset nor PEEP, the complementary observation cannot be found, or its value cannot be parsed as an integer.
/// </summary>
/// <param name="obs">The base patient observation that triggered the calculation; expected to represent a Pmeset or PEEP measurement.</param>
private async Task CalculateDrivingPressure(BasePatientObservation obs)
{
//Diferencia entre la Pmeset y la PEEP
@@ -361,6 +448,11 @@ public class CalculatedObservations : ICalculatedObservations
}
}
/// <summary>
/// Evaluates whether a patient meets the over-analgesia criteria based on pain-related observations (EVN between 0 and 3, ESCID equal to 3, or ANI greater than 70) combined with sustained infusions of morphine, remifentanil, or fentanyl exceeding the analgesia threshold, and records an "Over_Analgesia" observation when the conditions are satisfied.
/// </summary>
/// <param name="obs">The observation that triggered the evaluation; its value must be numeric and it is ignored if <paramref name="patientId"/> is provided (e.g., when invoked from a treatment context).</param>
/// <param name="patientId">The patient identifier when the evaluation is triggered by a treatment event; when null, it is derived from <paramref name="obs"/>.</param>
private async Task CalculateOverAnalgesia(BasePatientObservation? obs, ObjectId? patientId = null)
{
// Mandar observación 'SOBREANALGESIA'
@@ -435,6 +527,11 @@ public class CalculatedObservations : ICalculatedObservations
}
}
/// <summary>
/// Normalizes the ECMO location value of a patient observation. If the observation value matches one of the ECMO variants (ECCO2r, VVDL, VA+V, VVDL+V, VV+V, or VVA), it is mapped to "ECMO"; VV and VA values are left unchanged. If the observation is not a PatientObservation, it is returned unmodified.
/// </summary>
/// <param name="obs">The base patient observation to evaluate and potentially transform.</param>
/// <returns>A task that yields the observation, with its value normalized to "ECMO" when the original value is one of the recognized ECMO variants.</returns>
private Task<BasePatientObservation> CalculateEcmoLocation(BasePatientObservation obs)
{
//Las opciones pueden ser VV, VA o ECMO.
@@ -453,6 +550,15 @@ public class CalculatedObservations : ICalculatedObservations
return Task.FromResult(obs);
}
/// <summary>
/// Determines the ventilation mode for a patient based on the type of the incoming observation:
/// assigns <c>VMNI</c> when an Inspiratory Pressure value is received without a Compliancia value,
/// assigns <c>VMI</c> when a Compliancia value is received, and reads the mode from the CCC coding
/// system when an Air Flow value is received. If a mode is resolved, it is persisted as a new
/// <c>Ventilation_Mode</c> patient observation; otherwise the method returns without inserting
/// anything.
/// </summary>
/// <param name="obs">The incoming patient observation whose name drives the ventilation mode calculation.</param>
private async Task CalculateVentilationMode(BasePatientObservation obs)
{
//- Si llega valor de PI pero NO COMPL, el tipo de ventilación es VMNI
@@ -501,6 +607,13 @@ public class CalculatedObservations : ICalculatedObservations
_ = _observationService.Value.InsertObservation(ventilationModeObservation, mapObs: false);
}
/// <summary>
/// Evaluates whether an "Over_Sedation" clinical condition should be recorded for a patient.
/// The condition is met when RASS is -4 or -5, PSI is below 25, TS is above 5, and an active treatment exceeds its sedation threshold (Propofol &gt; 3, Midazolam &gt; 0.05, or Isoflurane &gt; 10).
/// If invoked with a single observation, the method extracts the patient identifier, validates the observation value against its own threshold, and then loads the remaining required observations (RASS, PSI, TS) to confirm the full set of conditions before persisting the Over_Sedation observation.
/// </summary>
/// <param name="obs">The triggering patient observation used to evaluate the sedation state. When provided, its name and value drive the initial validation; when null, the method relies on the <paramref name="patientId"/> parameter (typically from a treatment update).</param>
/// <param name="patientId">Optional identifier of the patient to evaluate. If null, it is derived from <paramref name="obs"/>; otherwise, the method performs a full evaluation using the patient's recent observations.</param>
private async Task CalculateOverSedation(BasePatientObservation? obs, ObjectId? patientId = null)
{
//Mandar observación 'SOBRESEDACIÓN'
@@ -576,6 +689,12 @@ public class CalculatedObservations : ICalculatedObservations
}
}
/// <summary>
/// Determines whether the given patient treatment has exceeded the 24-hour sustained analgesia threshold (e.g., morphine, remifentanil, or fentanyl perfusions).
/// Returns false when the treatment is null or its start time is not set.
/// </summary>
/// <param name="treatment">The patient treatment to evaluate; may be null.</param>
/// <returns><c>true</c> if the treatment has a start time and was started more than 24 hours ago; otherwise, <c>false</c>.</returns>
private static bool ExceedsAnalgesiaThreshold(PatientTreatment? treatment)
{
// Perfusiones de morfina, remifentanilo o fentanilo sostenidas > 24 h
@@ -584,6 +703,11 @@ public class CalculatedObservations : ICalculatedObservations
treatment.StartTime.Value.AddSeconds(86400) < DateTime.UtcNow;
}
/// <summary>
/// Determines whether a patient treatment exceeds the sedation threshold for Propofol, Midazolam, or Isoflurane based on requested minimum dosage amounts.
/// </summary>
/// <param name="treatment">The patient treatment to evaluate, or <c>null</c>.</param>
/// <returns><c>true</c> if the treatment is not <c>null</c> and any requested medication exceeds its defined sedation threshold; otherwise, <c>false</c>.</returns>
private static bool ExceedsSedationThreshold(PatientTreatment? treatment)
{
return (treatment != null &&
@@ -595,6 +719,11 @@ public class CalculatedObservations : ICalculatedObservations
c.Text == "Isoflorano" && treatment.RequestedGiveAmountMinimum > 10));
}
/// <summary>
/// Checks the active treatments of a patient and discontinues those whose end time is in the future by setting their <see cref="PatientTreatment.OrderControl"/> to <see cref="OrderControlType.Dc"/>, returning the remaining active treatments.
/// </summary>
/// <param name="treatment">The patient treatment whose patient is used to look up the list of active treatments to evaluate.</param>
/// <returns>A task that returns the list of active patient treatments that were not discontinued.</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
@@ -616,6 +745,13 @@ public class CalculatedObservations : ICalculatedObservations
return result;
}
/// <summary>
/// Validates the medicines associated with a patient treatment by combining newly requested medicines
/// with the patient's currently active medicines, deduplicating them by name, and verifying their
/// medication categories. If no new medicines are found, the method returns without performing any
/// further validation.
/// </summary>
/// <param name="treatment">The patient treatment whose requested medicines will be checked against the patient's active medicines.</param>
private async Task CheckTreatmentMedicines(PatientTreatment treatment)
{
var newMedicines = (await Task.WhenAll(treatment.RequestedGiveCodes
@@ -639,21 +775,26 @@ public class CalculatedObservations : ICalculatedObservations
CheckMedicationCategories(treatment.PatientId, uniqueMedicines as List<Medicine>);
}
/// <summary>
/// Classifies a patient's unique medicines into predefined clinical medication groups (e.g., sedation, inotropic, antibiotic, anxiolytic, antipsychotic, antidepressants, neuro medication, crystalloid/colloid serum, antihypertensives) and creates a multivalue observation for every category that contains at least one matching medicine. Categories whose list reference is null, medicines with a null or empty name, and categories with no matching medicines are skipped.
/// </summary>
/// <param name="patientId">The identifier of the patient whose medication categories are being evaluated and linked to the created observations.</param>
/// <param name="uniqueMedicines">The distinct list of medicines to be checked against the predefined category reference lists.</param>
private void CheckMedicationCategories(ObjectId patientId, List<Medicine> uniqueMedicines)
{
var medicationCategories = new Dictionary<string, List<string>?>
{
{ "Sedation_Medication_Multivalue", _sedationList },
{ "Inotropic_Medication_Multivalue", _inotropicMedicines },
{ "Antibiotic_Medication_Multivalue", _antibioticList },
{ "Anxiolytic_Medication_Multivalue", _anxiolyticsList },
{ "Antipsychotic_Medication_Multivalue", _antipsicoticList },
{ "Antidepressants_Medication_Multivalue", _antidepressantsList },
{ "Neuro_Medication_Multivalue", _neuroMedicationList },
{ "Crystalloid_Serum_Medication_Multivalue", _serumCrystalloidList },
{ "Colloid_Serum_Medication_Multivalue", _serumColloidList },
{ "Antihypertensives_Medication_Multivalue", _antihypertensivesList }
};
{
{ "Sedation_Medication_Multivalue", _sedationList },
{ "Inotropic_Medication_Multivalue", _inotropicMedicines },
{ "Antibiotic_Medication_Multivalue", _antibioticList },
{ "Anxiolytic_Medication_Multivalue", _anxiolyticsList },
{ "Antipsychotic_Medication_Multivalue", _antipsicoticList },
{ "Antidepressants_Medication_Multivalue", _antidepressantsList },
{ "Neuro_Medication_Multivalue", _neuroMedicationList },
{ "Crystalloid_Serum_Medication_Multivalue", _serumCrystalloidList },
{ "Colloid_Serum_Medication_Multivalue", _serumColloidList },
{ "Antihypertensives_Medication_Multivalue", _antihypertensivesList }
};
foreach (var category in medicationCategories)
{
@@ -668,8 +809,15 @@ public class CalculatedObservations : ICalculatedObservations
}
/// <summary>
/// Creates a new multi-value patient observation containing the names of the provided medications, expiring any
/// previous non-expired observation with the same name for the patient before inserting the new one.
/// </summary>
/// <param name="medications">The collection of medications whose names will be stored as the observation values.</param>
/// <param name="patientId">The identifier of the patient the observation belongs to.</param>
/// <param name="obsName">The name used to group and look up the previous observation for the same concept.</param>
private async Task CreateMedicationMultivalueObservation(IEnumerable<Medicine?> medications, ObjectId patientId,
string obsName)
string obsName)
{
var newObs = new PatientObservation
{
@@ -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