# Class UnitService

Namespace
  adas_core.Application.Services

Assembly
  adas-core.Application.dll

    public class UnitService : IUnitService

Inheritance
  object
  UnitService

Implements
  IUnitService

Inherited Members
  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

### UnitService(IUnitRepository, Lazy<IPatientService>, ILogger<UnitService>, IMasterListServiceFactory, ISubscribersService, Lazy<IClientMessageService>, IPointOfCareService, IHttpContextAccessor, ILocalAuditService)

    public UnitService(IUnitRepository unitRepository, Lazy<IPatientService> patientService, ILogger<UnitService> logger, IMasterListServiceFactory masterListServiceFactory, ISubscribersService subscribersService, Lazy<IClientMessageService> clientMessageService, IPointOfCareService pointOfCareService, IHttpContextAccessor httpContextAccessor, ILocalAuditService auditService)

#### Parameters

`unitRepository` IUnitRepository
`patientService` Lazy<IPatientService>
`logger` ILogger<UnitService>
`masterListServiceFactory` IMasterListServiceFactory
`subscribersService` ISubscribersService
`clientMessageService` Lazy<IClientMessageService>
`pointOfCareService` IPointOfCareService
`httpContextAccessor` IHttpContextAccessor
`auditService` ILocalAuditService

## Methods

### CountUnitsByMasterListId(ObjectId, MasterListType)

Asynchronously counts the number of units associated with the specified master list identifier and master list type by delegating to the unit repository.

    public Task<long> CountUnitsByMasterListId(ObjectId masterListId, MasterListType masterListType)

#### Parameters

`masterListId` ObjectId

  The unique identifier of the master list whose units should be counted.

`masterListType` MasterListType

  The type of the master list used to filter the units to be counted.

#### Returns

Task<long>

  A Task<TResult> representing the asynchronous operation, containing the total number of units that match the given master list identifier and type.

### DeleteUnitById(Unit)

Deletes a unit from the repository by its identifier and records an audit log entry for the operation. Throws a ConflictException when the underlying delete operation does not complete successfully.

    public Task<bool> DeleteUnitById(Unit unit)

#### Parameters

`unit` Unit

  The unit entity to delete, identified by its `Id`.

#### Returns

Task<bool>

  A task that resolves to `true` when the unit is successfully deleted.

#### Exceptions

ConflictException

  Thrown when the delete operation fails (returns `null`).

### FindById(ObjectId?)

Retrieves a unit by its identifier. Returns null when the provided identifier is null; otherwise, delegates the lookup to the unit repository.

    public Task<Unit?> FindById(ObjectId? id)

#### Parameters

`id` ObjectId?

  The identifier of the unit to find.

#### Returns

Task<Unit>

  The unit matching the specified identifier, or null if the identifier is null.

### FindByLocation(PatientLocation)

Retrieves a list of Unit entries that contain a point of care matching the specified PatientLocation, based on bed and unit name criteria.

    public Task<List<Unit>?> FindByLocation(PatientLocation location)

#### Parameters

`location` PatientLocation

  The PatientLocation providing the `Bed` and `UnitName` values used to filter the results.

#### Returns

Task<List<Unit>>

  A task containing a list of Unit entries whose point of care matches the given location, or `null` if an error occurs while retrieving the data.

### FindByName(string?)

Retrieves a Unit by its name, returning null when the provided name is null or empty. Otherwise, delegates the lookup to the unit repository.

    public Task<Unit?> FindByName(string? name)

#### Parameters

`name` string

  The name of the unit to look up. Can be null or empty.

#### Returns

Task<Unit>

  A Task<TResult> containing the matching Unit, or null if no name was provided.

### FindByPatientId(ObjectId)

Finds the Unit associated with a given patient by resolving the patient record and returning its linked unit. Returns the unit only when the patient exists and has a non-null `UnitId`; otherwise, throws a not-found exception.

    public Task<Unit?> FindByPatientId(ObjectId patientId)

#### Parameters

`patientId` ObjectId

  The identifier of the patient whose associated unit should be retrieved.

#### Returns

Task<Unit>

  A Task<TResult> containing the associated Unit if found, or `null` when no matching unit exists.

#### Exceptions

NotFoundException

  Thrown when the patient has no associated `UnitId` (i.e., the resource is missing).

### FindByUnitNameOrPocName(string?, string?)

Finds a unit by its name, or alternatively by a point of care bed identifier when no name is provided. If the name is supplied, the unit is looked up directly; otherwise, the point of care is resolved from the bed and the associated unit is returned. Returns `null` when neither a name nor a matching point of care is available, or when no unit is found.

    public Task<Unit?> FindByUnitNameOrPocName(string? name, string? pocName)

#### Parameters

`name` string

  The name of the unit to search for. Takes precedence over `pocName` when provided.

`pocName` string

  The point of care bed identifier used as a fallback to locate the unit when `name` is not supplied.

#### Returns

Task<Unit>

  A task containing the matching Unit, or `null` if no unit can be resolved from the given inputs.

### FindUnitsByMasterListId(ObjectId)

Retrieves a collection of units associated with the specified master list identifier. On failure, logs the exception and returns an empty list as a fallback.

    public Task<IEnumerable<Unit>> FindUnitsByMasterListId(ObjectId masterListId)

#### Parameters

`masterListId` ObjectId

  The identifier of the master list whose units should be retrieved.

#### Returns

Task<IEnumerable<Unit>>

  A task that yields the collection of Unit items matching the master list identifier, or an empty list if an error occurs.

### FindUnitsByMasterListId(ObjectId, MasterListType)

Asynchronously retrieves a collection of Unit entities associated with the specified master list identifier and type. If an exception occurs during the lookup, the error is logged and `null` is returned.

    public Task<IEnumerable<Unit>?> FindUnitsByMasterListId(ObjectId masterListId, MasterListType masterListType)

#### Parameters

`masterListId` ObjectId

  The identifier of the master list used to find the associated units.

`masterListType` MasterListType

  The type of the master list used to filter the units.

#### Returns

Task<IEnumerable<Unit>>

  A task that represents the asynchronous operation, containing a collection of Unit entities if found, or `null` if an error occurs.

### Get(string)

Retrieves a Unit by attempting multiple lookup strategies: first by ObjectId, then by title, and finally by name.

    public Task<Unit?> Get(string id)

#### Parameters

`id` string

  The identifier used to locate the unit. It can be an ObjectId, a title, or a name.

#### Returns

Task<Unit>

  The matching Unit if found; otherwise, `null`.

### GetAll(bool)

Retrieves all units, optionally including their associated PointOfCares. When `withPoCs` is `true`, the PointOfCares collection is populated for each unit using the point of care service; otherwise, only the unit data is returned.

    public Task<List<Unit>> GetAll(bool withPoCs = false)

#### Parameters

`withPoCs` bool

  If `true`, loads and assigns the PointOfCares for each unit; if `false`, returns units without their PointOfCares.

#### Returns

Task<List<Unit>>

  A task representing the asynchronous operation, containing the list of all units, with PointOfCares populated when requested.

### GetAllCompact()

Retrieves all units in a compact representation, mapping each unit to a UnitInfoDto containing its identifier, name, and title, with null name and title values safely replaced by empty strings.

    public Task<List<UnitInfoDto>> GetAllCompact()

#### Returns

Task<List<UnitInfoDto>>

  A task that represents the asynchronous operation. The task result contains a list of UnitInfoDto objects for all available units.

### GetByName(string)

Retrieves a unit by its name from the repository. If no matching unit is found, a not-found exception is thrown.

    public Task<Unit?> GetByName(string itemUnitName)

#### Parameters

`itemUnitName` string

  The name of the unit to search for.

#### Returns

Task<Unit>

  The unit matching the specified name.

#### Exceptions

NotFoundException

  Thrown when no unit exists with the provided name.

### GetInfo(ObjectId, bool, bool)

Retrieves a unit by its identifier and, when requested, enriches it with its associated points of care (including their devices).

    public Task<Unit?> GetInfo(ObjectId id, bool withPoCs = true, bool withDevices = true)

#### Parameters

`id` ObjectId

  The identifier of the unit to look up.

`withPoCs` bool

  When true, loads and assigns the unit's points of care to the result.

`withDevices` bool

  Flag intended to control device inclusion alongside the points of care.

#### Returns

Task<Unit>

  The matching Unit instance.

#### Exceptions

NotFoundException

  Thrown when no unit exists for the supplied `id`.

### GetInfo(ObjectId, LocaleEnum?, bool, bool)

Retrieves a Unit by its identifier, optionally hydrating its related master lists (e.g., allergy, diagnosis, origin, doctor, procedure, service, treatment, visit option, access control, language barrier, passive sitting, generic lists) for the specified locale, and optionally including its associated Points of Care.

    public Task<Unit?> GetInfo(ObjectId id, LocaleEnum? dataLocale, bool fillLists = true, bool withPoCs = false)

#### Parameters

`id` ObjectId

  The unique identifier of the unit to retrieve.

`dataLocale` LocaleEnum?

  The locale used to resolve localized values for the related master lists; can be null.

`fillLists` bool

  When true (default), populates every available related master list referenced by the unit using the given locale; when false, only the base unit is returned.

`withPoCs` bool

  When true, also loads and assigns the Points of Care associated with the unit; when false (default), the Points of Care collection is not populated.

#### Returns

Task<Unit>

  A Task<TResult> that yields the requested Unit with its optional related lists and Points of Care, or null when no unit matches the identifier.

#### Exceptions

NotFoundException

  Thrown when no unit is found for the supplied `id`.

### GetOneCompact(ObjectId)

Retrieves a compact representation of a unit by its identifier, returning a UnitInfoDto populated with the unit's id, name, and title. If no unit is found for the given id, the returned DTO contains a null id with empty name and title values.

    public Task<UnitInfoDto> GetOneCompact(ObjectId id)

#### Parameters

`id` ObjectId

  The unique identifier of the unit to retrieve.

#### Returns

Task<UnitInfoDto>

  A Task<TResult> containing the compact unit information, or a DTO with null/empty fields if the unit does not exist.

### GetPaginatedUnits(PaginationFilter, bool)

Retrieves a paginated list of units, optionally enriched with their associated Points of Care (PoCs). When `withPoCs` is true, all PoCs for the returned units are loaded in a single batch call and assigned to each unit.

    public Task<PaginationResponse<Unit>> GetPaginatedUnits(PaginationFilter filter, bool withPoCs = false)

#### Parameters

`filter` PaginationFilter

  The pagination parameters controlling the page number, page size, and total count.

`withPoCs` bool

  Indicates whether the response units should be populated with their related Points of Care. Defaults to false.

#### Returns

Task<PaginationResponse<Unit>>

  A Task<TResult> containing the requested page of units along with pagination metadata.

### InsertOne(Unit)

Inserts a new unit into the repository and records an audit log entry for the operation using the current HTTP context user. Throws a ConflictException when the repository fails to create the unit.

    public Task<Unit?> InsertOne(Unit unit)

#### Parameters

`unit` Unit

  The unit entity to be inserted.

#### Returns

Task<Unit>

  The newly created unit returned by the repository.

#### Exceptions

ConflictException

  Thrown when the repository returns null, indicating that the unit could not be created.

### UpdateConfiguration(ObjectId, UnitConfiguration)

Updates the configuration of an existing unit and records an audit log entry capturing the previous and resulting state.

    public Task<bool> UpdateConfiguration(ObjectId unitIdParsed, UnitConfiguration unitConfiguration)

#### Parameters

`unitIdParsed` ObjectId

  The parsed identifier of the unit whose configuration should be updated.

`unitConfiguration` UnitConfiguration

  The new configuration values to apply to the unit.

#### Returns

Task<bool>

  A task that resolves to `true` when the configuration was successfully updated; otherwise, `false`.

#### Exceptions

NotFoundException

  Thrown when the unit cannot be found either before or after the update operation.

ConflictException

  Thrown when the underlying update operation fails to persist the new configuration.

### UpdateUnit(Unit)

Updates an existing Unit in the repository, creating an audit log entry and broadcasting the change to interested parties.

    public Task<Unit?> UpdateUnit(Unit unit)

#### Parameters

`unit` Unit

  The unit containing the updated information, including the identifier of the existing unit to modify.

#### Returns

Task<Unit>

  The updated Unit if the operation succeeded; `null` if the repository could not persist the update.

#### Exceptions

NotFoundException

  Thrown when no unit exists with the specified identifier.

### UpdateUnitInfo(ObjectId, string, string, string?)

Updates the name and title of an existing unit, records the change in the audit log, and broadcasts the update to subscribed clients.

    public Task<Unit?> UpdateUnitInfo(ObjectId unitId, string name, string title, string? configObsId = null)

#### Parameters

`unitId` ObjectId

  The unique identifier of the unit to update.

`name` string

  The new name to assign to the unit.

`title` string

  The new title to assign to the unit.

`configObsId` string

  Optional configuration observer identifier associated with the update.

#### Returns

Task<Unit>

  The updated unit when the operation succeeds; otherwise, null.

#### Exceptions

NotFoundException

  Thrown when no unit is found for the provided identifier.

ConflictException

  Thrown when the underlying unit update operation fails.

### UpdateUnitMasterList(UpdateUnitIdListDto)

Updates the master list information of an existing unit identified by the provided identifier. Throws a not found exception if the unit does not exist and a conflict exception if the update operation fails.

    public Task<Unit?> UpdateUnitMasterList(UpdateUnitIdListDto updateUnitListDto)

#### Parameters

`updateUnitListDto` UpdateUnitIdListDto

  The data transfer object containing the unit identifier and the updated master list information.

#### Returns

Task<Unit>

  The updated Unit if the operation succeeds; otherwise, `null` when the underlying update returns no result.

#### Exceptions

NotFoundException

  Thrown when no unit is found matching the identifier specified in `updateUnitListDto`.

ConflictException

  Thrown when the update operation performed by the repository fails to produce a result.