# Class PatientRepository

Namespace
  adas_core.Infrastructure.Repositories

Assembly
  adas-core.Infrastructure.dll

Provides a MongoDB-backed repository implementation for managing patient data, exposing patient-specific data access operations defined by the IPatientRepository contract.

    public class PatientRepository : MongoRepository<Patient>, IPatientRepository, IMongoRepository<Patient>

Inheritance
  object
  MongoRepository<Patient>
  PatientRepository

Implements
  IPatientRepository
  IMongoRepository<Patient>

Inherited Members
  MongoRepository<Patient>.Db
  MongoRepository<Patient>.Collection
  MongoRepository<Patient>.UpdateOneAsync(ObjectId, Patient)
  MongoRepository<Patient>.DeleteAsync(ObjectId)
  MongoRepository<Patient>.InsertInitialLoad()
  MongoRepository<Patient>.InsertManyAsync(List<Patient>)
  MongoRepository<Patient>.UpdateManyObjectIdAsync(string, ObjectId, ObjectId)
  MongoRepository<Patient>.DeleteAsync(string)
  MongoRepository<Patient>.CollectionExists(string)
  object.Equals(object)
  object.Equals(object, object)
  object.GetHashCode()
  object.GetType()
  object.MemberwiseClone()
  object.ReferenceEquals(object, object)
  object.ToString()

Extension Methods
  NumberUtils.IsNumber(object)
  NumberUtils.ToDouble(object)
  ObjectUtils.ToStr(object?)

## Constructors

### PatientRepository(IOptions<ApiSettings>, IMongoDatabase)

    public PatientRepository(IOptions<ApiSettings> apiSettings, IMongoDatabase database)

#### Parameters

`apiSettings` IOptions<ApiSettings>
`database` IMongoDatabase

## Methods

### CountByUnitId(ObjectId)

Asynchronously counts the number of patients associated with the specified unit identifier. Returns 0 and logs the error if an exception occurs during the operation.

    public Task<long> CountByUnitId(ObjectId unitId)

#### Parameters

`unitId` ObjectId

  The unit identifier used to filter patients.

#### Returns

Task<long>

  The number of patients matching the specified unit identifier, or 0 if an error occurs.

### CreateIndexes()

Creates MongoDB indexes for the Patient collection, including a unique index on the `patientNumber` field and a non-unique index on the `admTime` field, using background index creation.

    public override Task CreateIndexes()

#### Returns

Task

### Delete(ObjectId)

Deletes a patient from the collection that matches the specified identifier.

    public Task Delete(ObjectId id)

#### Parameters

`id` ObjectId

  The unique identifier of the patient to remove.

#### Returns

Task

### DeleteMasterListOption(List<ObjectId>, OptionList, string)

Deletes the specified master list option and returns the patients affected by its removal.

    public Task<IEnumerable<Patient>> DeleteMasterListOption(List<ObjectId> unitIds, OptionList opt, string typeName)

#### Parameters

`unitIds` List<ObjectId>

  The identifiers of the units whose master list option should be deleted.

`opt` OptionList

  The master list option to remove.

`typeName` string

  The name of the master list type to which the option belongs.

#### Returns

Task<IEnumerable<Patient>>

  A task that yields the collection of patients impacted by deleting the master list option.

### FindAll()

Retrieves all Patient records from the data store.

    public Task<List<Patient>> FindAll()

#### Returns

Task<List<Patient>>

  A task that represents the asynchronous operation, containing a list of all patients.

### FindAllByPointOfCareId(ObjectId)

Asynchronously retrieves all patients associated with the specified point of care identifier.

    public Task<List<Patient>> FindAllByPointOfCareId(ObjectId pointOfCare)

#### Parameters

`pointOfCare` ObjectId

  The ObjectId of the point of care used to filter the patients.

#### Returns

Task<List<Patient>>

  A task that represents the asynchronous operation, containing a list of patients matching the specified point of care.

### FindAllPatientWithFinishedProcedures(int)

Asynchronously retrieves all patients who have completed procedures, filtering by the number of minutes that have elapsed since the procedure end date for archival purposes.

    public Task<List<Patient>> FindAllPatientWithFinishedProcedures(int archiveProcedureEndDateAfterMinutes)

#### Parameters

`archiveProcedureEndDateAfterMinutes` int

  The number of minutes after the procedure end date used to determine which finished procedures are eligible for archive retrieval.

#### Returns

Task<List<Patient>>

  A task that represents the asynchronous operation. The task result contains a list of patients with finished procedures matching the archive criteria.

### FindAllPatientWithFinishedTests(int)

Asynchronously retrieves all patients whose tests have finished based on the specified archive end date threshold.

    public Task<List<Patient>> FindAllPatientWithFinishedTests(int archiveTestEndDateAfterMinutes)

#### Parameters

`archiveTestEndDateAfterMinutes` int

  The number of minutes after which a test is considered finished and eligible for retrieval.

#### Returns

Task<List<Patient>>

  A task that represents the asynchronous operation, containing a list of patients with finished tests.

### FindAllPatientWithFinishedTreatment(int)

Retrieves all patients whose treatment has been finished and is eligible for archival based on the specified end date threshold.

    public Task<List<Patient>> FindAllPatientWithFinishedTreatment(int archiveTreatmentEndDateAfterMinutes)

#### Parameters

`archiveTreatmentEndDateAfterMinutes` int

  The number of minutes after the treatment end date used as the archival threshold.

#### Returns

Task<List<Patient>>

  A task that represents the asynchronous operation, containing a list of patients with finished treatments that meet the archival criteria.

### FindById(ObjectId)

Asynchronously finds a patient by their unique identifier in the underlying collection. Returns `null` if no matching patient is found or if an error occurs while querying, with the error being logged.

    public Task<Patient?> FindById(ObjectId id)

#### Parameters

`id` ObjectId

  The unique identifier of the patient to locate.

#### Returns

Task<Patient>

  A Patient instance matching the provided id, or `null` if not found or on error.

### FindByLocation(PatientLocation?)

Finds a patient based on the provided location information. Returns null if the location is null or no matching patient is found. When both unit name and bed are specified, the search filters by both criteria; otherwise, it falls back to filtering by bed only, or returns the first available patient if neither is provided.

    public Task<Patient?> FindByLocation(PatientLocation? location)

#### Parameters

`location` PatientLocation

  The location information used to locate the patient. Can be null.

#### Returns

Task<Patient>

  A Patient matching the location criteria, or null if no match is found or the location is null.

### FindByPatientId(ObjectId)

Asynchronously retrieves a patient from the data store by their unique identifier.

    public Task<Patient?> FindByPatientId(ObjectId patientId)

#### Parameters

`patientId` ObjectId

  The unique identifier of the patient to look up.

#### Returns

Task<Patient>

  A task that represents the asynchronous operation. The task result contains the matching Patient if one is found; otherwise, `null`.

### FindByPatientId(string)

Asynchronously retrieves a Patient that matches the specified patient identifier.

    public Task<Patient?> FindByPatientId(string patientId)

#### Parameters

`patientId` string

  The unique identifier of the patient to look up.

#### Returns

Task<Patient>

  A task that represents the asynchronous operation, containing the matching Patient if found; otherwise, `null`.

### FindByPatientNumber(string)

Asynchronously retrieves a Patient by their unique patient number. Returns `null` when no patient matches the provided identifier.

    public Task<Patient?> FindByPatientNumber(string patientNumber)

#### Parameters

`patientNumber` string

  The unique patient number used to look up the patient.

#### Returns

Task<Patient>

  A Task<TResult> containing the matching Patient, or `null` if no patient is found.

### FindByPointOfCare(ObjectId)

Asynchronously retrieves all patients associated with the specified point of care.

    public Task<List<Patient>> FindByPointOfCare(ObjectId pointOfCare)

#### Parameters

`pointOfCare` ObjectId

  The identifier of the point of care used to filter the patient records.

#### Returns

Task<List<Patient>>

  A task that represents the asynchronous operation, containing a list of patients matching the specified point of care.

### FindByPointOfCare(string)

Asynchronously retrieves all patients associated with the specified point of care from the collection.

    public Task<List<Patient>> FindByPointOfCare(string pointOfCare)

#### Parameters

`pointOfCare` string

  The unit or point of care used to filter the patients.

#### Returns

Task<List<Patient>>

  A task containing a list of Patient objects whose unit matches the specified point of care; an empty list is returned when no matches are found.

### FindByPointOfCareId(ObjectId)

Retrieves a Patient matching the specified point of care identifier. Returns the first matching patient, or `null` if no patient is found or an error occurs while querying the data store.

    public Task<Patient?> FindByPointOfCareId(ObjectId id)

#### Parameters

`id` ObjectId

  The point of care identifier used to locate the patient.

#### Returns

Task<Patient>

  A Patient instance if a match is found; otherwise, `null`.

### FindByUnitAndPocId(ObjectId, ObjectId)

Finds a patient by the specified unit identifier and point of care identifier. Returns the first matching patient, or null if no match is found or if an error occurs during the search.

    public Task<Patient> FindByUnitAndPocId(ObjectId unit, ObjectId pointOfCare)

#### Parameters

`unit` ObjectId

  The identifier of the unit to filter by.

`pointOfCare` ObjectId

  The identifier of the point of care to filter by.

#### Returns

Task<Patient>

  The first matching Patient, or null if no patient is found or an error is encountered.

### FindDischargedPatients()

Retrieves all patients whose discharge time (DisTime) has been recorded, indicating they have been discharged. If an error occurs during the database operation, the exception is logged and an empty list is returned instead of propagating the failure.

    public Task<List<Patient>> FindDischargedPatients()

#### Returns

Task<List<Patient>>

  A task that resolves to a list of discharged Patient records, or an empty list if the operation fails.

### FindInActivePoC()

Asynchronously retrieves a list of patients who have an inactive Point of Care (PoC) assignment.

    public Task<List<Patient>> FindInActivePoC()

#### Returns

Task<List<Patient>>

  A task that represents the asynchronous operation. The task result contains a list of Patient objects with inactive PoC status.

### FindInInactivePoC()

Asynchronously retrieves a list of patients who are currently marked as inactive points of contact (PoC).

    public Task<List<Patient>> FindInInactivePoC()

#### Returns

Task<List<Patient>>

  A task that represents the asynchronous operation. The task result contains a list of inactive PoC patients.

### FindPatientsNotUpdatedSince(DateTime)

Retrieves all patients whose `UpdateDate` is older than the specified date or has never been set (null), identifying records that have not been updated since the given threshold.

    public Task<List<Patient>> FindPatientsNotUpdatedSince(DateTime date)

#### Parameters

`date` DateTime

  The cutoff date; patients with an `UpdateDate` strictly earlier than this value, or with no `UpdateDate` set, will be returned.

#### Returns

Task<List<Patient>>

  A task that resolves to a list of Patient instances matching the filter criteria.

### GetCollectionName()

Gets the collection name for patients, returning the configured value from API settings or falling back to the default "patients" if the setting is null.

    public override string GetCollectionName()

#### Returns

string

  The configured patients collection name, or "patients" as a default when the setting is not set.

### GetPaginatedPatients(PaginationFilter)

Retrieves a paginated, sorted (by admission time descending) queryable of patients, applying optional filters for text search across patient names and patient number (and by identifier when the text parses as an ObjectId), time range, unit, and point of care, and falling back to an unfiltered query when no filtered request is provided.

    public IFindFluent<Patient, Patient> GetPaginatedPatients(PaginationFilter filter)

#### Parameters

`filter` PaginationFilter

  The pagination and filtering criteria, including optional text, time range, unit, and point of care filters.

#### Returns

IFindFluent<Patient, Patient>

  A find fluent for the filtered and sorted patient query.

### GetPatientsByUnitIds(List<ObjectId>, string)

Retrieves a list of patients whose unit identifier is contained in the specified collection of unit identifiers. Validates the provided type name against the MasterListType enumeration; if the type name cannot be parsed, an empty list is returned.

    public Task<List<Patient>> GetPatientsByUnitIds(List<ObjectId> unitIds, string typeName)

#### Parameters

`unitIds` List<ObjectId>

  The list of unit identifiers used to filter patients.

`typeName` string

  The name of the type to validate against the MasterListType enumeration.

#### Returns

Task<List<Patient>>

  A task that represents the asynchronous operation. The task result contains a list of Patient objects matching the specified unit identifiers, or an empty list if the type name is invalid.

### InsertOneAsync(Patient)

Asynchronously inserts a new Patient record, setting its creation date to the current UTC time. If the insertion fails but an existing patient with the same patient number is found at the same location, the exception is logged as a warning; otherwise, the error is logged and rethrown.

    public override Task InsertOneAsync(Patient patient)

#### Parameters

`patient` Patient

  The Patient entity to insert into the data store.

#### Returns

Task

### SearchByPatientNumberAndDistinctUnit(string, ObjectId)

Asynchronously searches for a patient by their patient number within a specific unit, ensuring the patient is associated with a distinct unit.

    public Task<Patient?> SearchByPatientNumberAndDistinctUnit(string patientNumber, ObjectId unitId)

#### Parameters

`patientNumber` string

  The unique patient number used to identify the patient.

`unitId` ObjectId

  The identifier of the unit to constrain the search to a distinct unit context.

#### Returns

Task<Patient>

  A task that represents the asynchronous operation. The task result contains the matching Patient if found; otherwise, `null`.

### Update(Patient)

Updates an existing patient record, refreshing the update timestamp to the current UTC time before persisting the changes.

    public Task Update(Patient patient)

#### Parameters

`patient` Patient

  The patient entity containing the updated information to be saved.

#### Returns

Task

### UpdateAttendingDoctor(ObjectId, Person)

Updates the attending doctor of a patient identified by the specified identifier and refreshes the update timestamp to the current UTC date and time.

    public Task UpdateAttendingDoctor(ObjectId id, Person attendingDoctor)

#### Parameters

`id` ObjectId

  The unique identifier of the patient whose attending doctor is being updated.

`attendingDoctor` Person

  The new attending doctor to assign to the patient.

#### Returns

Task

### UpdateLocation(ObjectId, ObjectId)

Updates the point of care (location) for the specified patient, also refreshing the modification timestamp to the current UTC time. If no patient is found for the given identifier, a warning is logged and the method returns without making any changes.

    public Task UpdateLocation(ObjectId id, ObjectId location)

#### Parameters

`id` ObjectId

  The unique identifier of the patient whose location will be updated.

`location` ObjectId

  The new point of care (location) identifier to assign to the patient.

#### Returns

Task

### UpdateLocation(ObjectId, PatientLocation)

Updates the location of an existing patient. If no patient is found for the given identifier, the operation is skipped and a warning is logged.

    public Task UpdateLocation(ObjectId id, PatientLocation location)

#### Parameters

`id` ObjectId

  The unique identifier of the patient whose location will be updated.

`location` PatientLocation

  The new location to assign to the patient.

#### Returns

Task

### UpdateMasterListOption(List<ObjectId>, UpdateOptionMasterListDto, string)

Updates a master list option for the specified units and returns the patients affected by the change.

    public Task<List<Patient>> UpdateMasterListOption(List<ObjectId> unitIds, UpdateOptionMasterListDto opt, string typeName)

#### Parameters

`unitIds` List<ObjectId>

  The list of unit identifiers whose patients should be considered for the update.

`opt` UpdateOptionMasterListDto

  The DTO containing the master list option update details.

`typeName` string

  The name of the option type being updated.

#### Returns

Task<List<Patient>>

  A task that resolves to the list of patients impacted by the master list option update.

### UpdateOne(Patient)

Updates an existing patient record in the data store, refreshing the modification timestamp, and returns the updated document. Returns `null` when no patient matching the provided identifier is found.

    public Task<Patient?> UpdateOne(Patient updatedPatient)

#### Parameters

`updatedPatient` Patient

  The patient entity containing the updated values and the identifier of the record to modify.

#### Returns

Task<Patient>

  The updated Patient after the modification is applied, or `null` if no matching document exists.

### UpdatePatientData(ObjectId, string, Person, bool)

Updates the personal data and update timestamp of an existing patient identified by the supplied id. When `updatePatientNumber` is true (the default), the patient number is also updated; otherwise only the person data and update date are persisted.

    public Task UpdatePatientData(ObjectId id, string patientNumber, Person data, bool updatePatientNumber = true)

#### Parameters

`id` ObjectId

  The unique identifier of the patient to update.

`patientNumber` string

  The new patient number to apply when `updatePatientNumber` is true.

`data` Person

  The new Person information to store for the patient.

`updatePatientNumber` bool

  Indicates whether the patient number should be updated as part of the operation; defaults to true.

#### Returns

Task

### UpdatePatientDemographicData(ObjectId, Patient)

Updates the demographic and clinical information of an existing patient, including allergies, language barrier, diagnosis, and person data, while setting the update timestamp to the current UTC time. Returns the updated patient document after the modification has been applied.

    public Task<Patient?> UpdatePatientDemographicData(ObjectId patientId, Patient person)

#### Parameters

`patientId` ObjectId

  The unique identifier of the patient whose data will be updated.

`person` Patient

  The patient object containing the new demographic and clinical values to persist.

#### Returns

Task<Patient>

  The updated Patient document, or `null` if no patient with the specified identifier was found.

### UpdatePatientIncomingData(ObjectId, Patient)

Updates the incoming data fields of an existing patient in the database, refreshing the update timestamp. Returns the updated patient document, or `null` if no patient matches the specified identifier.

    public Task<Patient?> UpdatePatientIncomingData(ObjectId patientId, Patient person)

#### Parameters

`patientId` ObjectId

  The unique identifier of the patient to update.

`person` Patient

  The patient object containing the new values for the incoming data fields.

#### Returns

Task<Patient>

  The updated Patient document after the modification, or `null` if no document was found.