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
@@ -14,6 +14,14 @@ using MongoDB.Bson;
namespace adas_core.Application.Services;
/// <summary>
/// Provides the concrete implementation of the <see cref="IDischargeService"/> contract,
/// encapsulating the business logic required to process discharge operations.
/// </summary>
/// <remarks>
/// This service acts as the default in-memory or infrastructure-backed implementation
/// of the discharge operations defined by <see cref="IDischargeService"/>.
/// </remarks>
public class DischargeService : IDischargeService
{
private readonly ILocalAuditService _auditService;
@@ -52,6 +60,12 @@ public class DischargeService : IDischargeService
}
/// <summary>
/// Deletes a discharge record asynchronously. The method is intended to validate that the patient
/// can be discharged (requiring both medical and administrative discharge values and an allowed
/// discharge status), and otherwise falls back to deleting the discharge by its identifier.
/// </summary>
/// <param name="discharge">The discharge entity to be deleted.</param>
public async Task DeleteDischargeAsync(Discharge discharge)
{
//var patient = await _patientServiceLazy.Value.FindById(discharge.PatientId);
@@ -65,6 +79,10 @@ public class DischargeService : IDischargeService
await DeleteDischargeByIdAsync(discharge.Id);
}
/// <summary>
/// Deletes a discharge record by its identifier. If the discharge is not found, an error is logged and the operation is skipped; otherwise the record is removed, an audit log entry is created, and a delete broadcast is sent.
/// </summary>
/// <param name="dischargeId">The unique identifier of the discharge to delete.</param>
public async Task DeleteDischargeByIdAsync(ObjectId dischargeId)
{
try
@@ -95,11 +113,25 @@ public class DischargeService : IDischargeService
}
}
/// <summary>
/// Asynchronously counts the number of discharge records associated with the specified unit identifier.
/// </summary>
/// <param name="unitId">The identifier of the unit whose discharge records will be counted.</param>
/// <returns>A task representing the asynchronous operation, containing the total number of discharges for the given unit.</returns>
public async Task<long> CountDischargesByUnitId(ObjectId unitId)
{
return await _dischargeRepository.CountByUnitId(unitId);
}
/// <summary>
/// Retrieves a discharge by its identifier, enriching the result with patient location details
/// when an associated point of care is available.
/// </summary>
/// <param name="dischargeId">The unique identifier of the discharge to retrieve.</param>
/// <returns>The matching <see cref="Discharge"/>, populated with <see cref="PatientLocation"/>
/// information if a point of care is linked; otherwise the discharge as stored.</returns>
/// <exception cref="NotFoundException">Thrown when no discharge is found for the specified
/// <paramref name="dischargeId"/>.</exception>
public async Task<Discharge?> GetDischargeByIdAsync(ObjectId dischargeId)
{
var result = await _dischargeRepository.FindById(dischargeId) ??
@@ -107,17 +139,26 @@ public class DischargeService : IDischargeService
if (result.PointOfCareId == null)
return result;
var poc = await _pointOfCareService.GetInfo(result.PointOfCareId.Value, null,false);
var poc = await _pointOfCareService.GetInfo(result.PointOfCareId.Value, null, false);
result.PatientLocation = new PatientLocation(poc?.UnitName, poc?.Bed, poc?.Room);
return result;
}
/// <summary>
/// Asynchronously retrieves all discharge records from the repository.
/// </summary>
/// <returns>A task that represents the asynchronous operation, containing an enumerable collection of <see cref="Discharge"/> records.</returns>
public async Task<IEnumerable<Discharge>> GetDischargesAsync()
{
return await _dischargeRepository.FindAll();
}
/// <summary>
/// Retrieves the discharge record associated with the specified patient identifier, enriching it with patient location details when a point of care is linked.
/// </summary>
/// <param name="patientId">The unique identifier of the patient whose discharge record should be retrieved.</param>
/// <returns>A <see cref="Discharge"/> object populated with patient location information when a point of care is associated, or <c>null</c> if no discharge is found or an error occurs.</returns>
public async Task<Discharge?> GetDischargeByPatientId(ObjectId patientId)
{
try
@@ -127,7 +168,7 @@ public class DischargeService : IDischargeService
_logger.LogError("Discharge not found by patient Id {id}", patientId);
if (discharge is { PointOfCareId: not null })
{
var poc = await _pointOfCareService.GetInfo(discharge.PointOfCareId.Value, null,false);
var poc = await _pointOfCareService.GetInfo(discharge.PointOfCareId.Value, null, false);
discharge.PatientLocation = new PatientLocation(poc?.UnitName, poc?.Bed, poc?.Room);
}
@@ -140,6 +181,13 @@ public class DischargeService : IDischargeService
}
}
/// <summary>
/// Inserts a new discharge record into the repository, verifies its persistence, logs the operation, and broadcasts a notification.
/// Throws a <see cref="ConflictException"/> if the discharge cannot be retrieved after insertion, indicating a creation failure.
/// </summary>
/// <param name="discharge">The discharge entity to be inserted.</param>
/// <returns>The persisted <see cref="Discharge"/> entity retrieved from the repository after insertion.</returns>
/// <exception cref="ConflictException">Thrown when the inserted discharge cannot be found by its identifier, indicating that the creation failed.</exception>
public async Task<Discharge?> InsertDischarge(Discharge discharge)
{
await _dischargeRepository.InsertOneAsync(discharge);
@@ -152,6 +200,12 @@ public class DischargeService : IDischargeService
return dischargeAux;
}
/// <summary>
/// Asynchronously retrieves the <see cref="Discharge"/> associated with the specified patient location.
/// Returns <c>null</c> if an exception occurs while accessing the underlying repository.
/// </summary>
/// <param name="location">The patient location used to look up the associated discharge record.</param>
/// <returns>A <see cref="Discharge"/> if one is found for the given location; otherwise, <c>null</c> when an error occurs.</returns>
public async Task<Discharge?> GetDischargeByLocation(PatientLocation location)
{
try
@@ -165,6 +219,13 @@ public class DischargeService : IDischargeService
}
}
/// <summary>
/// Retrieves a discharge record by the specified point of care identifier and enriches it with patient location details.
/// If the discharge is not found, an information message is logged; when a related point of care is available, its unit, bed, and room are mapped to the discharge's <see cref="PatientLocation"/>.
/// On failure, the error is logged and <c>null</c> is returned.
/// </summary>
/// <param name="poc">The point of care identifier used to look up the discharge record.</param>
/// <returns>A <see cref="Discharge"/> with the patient location populated when available, or <c>null</c> if the discharge is not found or an error occurs.</returns>
public async Task<Discharge?> GetDischargeByPointOfCareId(ObjectId poc)
{
try
@@ -174,7 +235,7 @@ public class DischargeService : IDischargeService
_logger.LogInformation("Discharge not found by PointOfCareId {id}", poc);
if (discharge is { PointOfCareId: not null })
{
var pocInfo = await _pointOfCareService.GetInfo(discharge.PointOfCareId.Value, null,false);
var pocInfo = await _pointOfCareService.GetInfo(discharge.PointOfCareId.Value, null, false);
discharge.PatientLocation = new PatientLocation(pocInfo?.UnitName, pocInfo?.Bed, pocInfo?.Room);
}
@@ -187,6 +248,13 @@ public class DischargeService : IDischargeService
}
}
/// <summary>
/// Retrieves a discharge record by its point of care (location) identifier and applies locale-specific data using the associated unit.
/// Returns the discharge as-is if no associated unit is found, or <c>null</c> if no discharge exists for the given location.
/// </summary>
/// <param name="location">The ObjectId identifying the point of care (location) whose discharge record should be retrieved.</param>
/// <param name="dataLocale">The locale used to localize the discharge data when the associated unit is found.</param>
/// <returns>A <see cref="Task{Discharge}"/> containing the localized discharge, the unmodified discharge when its unit cannot be found, or <c>null</c> when no discharge exists for the specified location.</returns>
public async Task<Discharge?> GetDischargeByPointOfCareIdWithLocale(ObjectId location, LocaleEnum dataLocale)
{
var discharge = await GetDischargeByPointOfCareId(location);
@@ -197,6 +265,11 @@ public class DischargeService : IDischargeService
return dischargeWithLocale;
}
/// <summary>
/// Updates an existing discharge record, auditing the change and broadcasting the update. Throws a conflict exception if the discharge cannot be found by its identifier.
/// </summary>
/// <param name="discharge">The discharge entity to be updated.</param>
/// <exception cref="ConflictException">Thrown when no discharge is found with the specified identifier, preventing the update from proceeding.</exception>
public async Task UpdateDischargeAsync(Discharge discharge)
{
var oldDischarge = await GetDischargeByIdAsync(discharge.Id) ??
@@ -228,39 +301,39 @@ public class DischargeService : IDischargeService
switch (apiRequest.Type)
{
case "NewDischarge":
{
//TODO: ver qué tipos llegan
if (!"Altable".Equals(apiRequest.Discharge.Patient.DischargeStatus?.OptionType))
{
_logger.LogError("Error discharging. Patient not altable: {patient}", patient);
return;
//TODO: ver qué tipos llegan
if (!"Altable".Equals(apiRequest.Discharge.Patient.DischargeStatus?.OptionType))
{
_logger.LogError("Error discharging. Patient not altable: {patient}", patient);
return;
}
await _dischargeRepository.InsertOneAsync(apiRequest.Discharge);
await _auditService.CreateAuditLogAsync(_httpContextAccessor.HttpContext?.User!, null,
apiRequest.Discharge);
SendDischargeBroadcast(apiRequest.Discharge, OperationType.NewDischarge);
break;
}
await _dischargeRepository.InsertOneAsync(apiRequest.Discharge);
await _auditService.CreateAuditLogAsync(_httpContextAccessor.HttpContext?.User!, null,
apiRequest.Discharge);
SendDischargeBroadcast(apiRequest.Discharge, OperationType.NewDischarge);
break;
}
case "UpdateDischarge":
{
await GetDischargeByIdAsync(apiRequest.Discharge.Id);
await UpdateDischargeAsync(apiRequest.Discharge);
break;
}
case "DeleteDischarge":
{
if (StatusEnum.Discharge.NoAltable.ToString().Equals(patient.DischargeStatus?.OptionType))
{
_logger.LogError("Error deleting discharge. Patient altable: {patient}", patient);
return;
await GetDischargeByIdAsync(apiRequest.Discharge.Id);
await UpdateDischargeAsync(apiRequest.Discharge);
break;
}
case "DeleteDischarge":
{
if (StatusEnum.Discharge.NoAltable.ToString().Equals(patient.DischargeStatus?.OptionType))
{
_logger.LogError("Error deleting discharge. Patient altable: {patient}", patient);
return;
}
await DeleteDischargeAsync(apiRequest.Discharge);
break;
}
await DeleteDischargeAsync(apiRequest.Discharge);
break;
}
}
}
catch (Exception ex)
@@ -270,12 +343,22 @@ public class DischargeService : IDischargeService
}
}
/// <summary>
/// Asynchronously persists the specified API request by executing the save operation on a background thread.
/// </summary>
/// <param name="apiRequest">The API request to save.</param>
/// <returns>A task that completes when the request has been saved.</returns>
public Task SaveRequestAsync(ApiRequest apiRequest)
{
return Task.FromResult(Task.Run(async () => { await SaveRequest(apiRequest); }));
}
// Revisar
/// <summary>
/// Sends a discharge broadcast to all subscribers associated with the discharge's point of care, grouped by their locale. Validates that the point of care identifier is present; logs and returns early if it is null. Exceptions during the broadcast are caught and logged without rethrowing.
/// </summary>
/// <param name="discharge">The discharge whose point of care is used to locate matching subscribers and whose data is sent in the broadcast.</param>
/// <param name="operation">The operation type associated with the outgoing message sent to each subscriber.</param>
public async void SendDischargeBroadcast(Discharge discharge, OperationType operation)
{
try
@@ -311,8 +394,14 @@ public class DischargeService : IDischargeService
}
}
/// <summary>
/// Updates the master list option for the specified units and type, then records an audit log entry and broadcasts the change for each affected discharge.
/// </summary>
/// <param name="opt">The master list update options to apply to the discharges.</param>
/// <param name="unitList">The collection of units whose associated discharges will be updated.</param>
/// <param name="typeName">The name of the master list type used to target the update.</param>
public async Task UpdatePatientMasterListItemChange(UpdateOptionMasterListDto opt, IEnumerable<Unit> unitList,
string typeName)
string typeName)
{
var unitIds = unitList.Select(x => x.Id).ToList();
await _dischargeRepository.GetDischargesByUnitIds(unitIds);
@@ -326,6 +415,12 @@ public class DischargeService : IDischargeService
}
}
/// <summary>
/// Deletes a patient master list option for the specified units and type, then processes the resulting updated discharge records by creating audit log entries and broadcasting update notifications (only when the updated discharge record is found).
/// </summary>
/// <param name="opt">The option list entry to be removed from the patient master list.</param>
/// <param name="unitList">The collection of units whose identifiers are used to scope the deletion.</param>
/// <param name="typeName">The name of the master list type/category to which the option belongs.</param>
public async Task DeletePatientMasterListItem(OptionList opt, IEnumerable<Unit> unitList, string typeName)
{
var unitIds = unitList.Select(x => x.Id).ToList();
@@ -339,11 +434,24 @@ public class DischargeService : IDischargeService
}
}
/// <summary>
/// Asynchronously deletes all discharge records associated with the specified unit identifier by delegating the operation to the discharge repository.
/// </summary>
/// <param name="unitId">The unique identifier of the unit whose discharge records should be removed.</param>
public async Task DeleteDischargesByUnitId(ObjectId unitId)
{
await _dischargeRepository.DeleteByUnitId(unitId);
}
/// <summary>
/// Returns the given <paramref name="discharge"/> with its configurable option names translated according to the specified <paramref name="locale"/>.
/// When <paramref name="unit"/> is null or the locale is <see cref="LocaleEnum.Default"/>, the discharge is returned unchanged.
/// Otherwise, the configured service and destination options are looked up in the locale-specific master lists and their <c>Name</c> values are updated; fields without a matching list, missing properties, null values, or without a translation are left untouched.
/// </summary>
/// <param name="unit">Source of the master list identifiers used to resolve locale-specific options; when null, no translation is performed.</param>
/// <param name="discharge">Discharge instance whose option names may be translated in place.</param>
/// <param name="locale">Target locale used to load the appropriate master list; when set to <see cref="LocaleEnum.Default"/>, the discharge is returned without changes.</param>
/// <returns>The same <paramref name="discharge"/> instance, with translated option names when a matching locale-specific entry is found.</returns>
private async Task<Discharge> GetDischargeWithLocale(Unit? unit, Discharge discharge, LocaleEnum locale)
{
if (unit == null)