# adas-core.Domain — Core Domain Layer

> The innermost layer of the ADAS Core platform.  
> Contains pure business concepts: entities, value objects, domain enumerations, shared DTOs, domain exceptions, and utility abstractions. This layer has **zero project references** beyond the .NET runtime and primitive packages.

---

## Table of Contents

1. [Overview](#overview)
2. [Responsibilities](#responsibilities)
3. [Project Structure](#project-structure)
4. [Dependencies](#dependencies)
5. [Domain Entities](#domain-entities)
6. [Enumerations](#enumerations)
7. [Shared DTOs](#shared-dtos)
8. [Domain Exceptions](#domain-exceptions)
9. [Utilities](#utilities)
10. [Design Rules](#design-rules)

---

## Overview

`adas-core.Domain` is the foundational layer of the ADAS Core architecture. It encapsulates everything the business cares about, expressed as plain C# constructs with no knowledge of databases, HTTP, UI frameworks, or infrastructure concerns.

Key characteristics:

- **Zero Project References** — No references to any other project in the solution. This is the innermost circle of Clean Architecture.
- **Primitive-Only NuGet** — Only `MongoDB.Bson` (for `ObjectId`), `Newtonsoft.Json` (serialization), and `BCrypt` (hashing algorithm) are allowed.
- **Rich Domain Model** — Entities carry both data and behavior. Business rules are expressed through methods on domain objects, not in services.
- **Immutable Where Possible** — Value objects and DTOs favor immutability to prevent accidental mutation across layers.
- **Self-Describing** — Every public API carries XML documentation comments.

---

## Responsibilities

| Concern | What this project contains |
|---------|--------------------------|
| **Domain Entities** | Rich business objects (`User`, `Patient`, `Observation`, `Alarm`, `Device`, etc.) with identity and behavior. |
| **Value Objects** | Immutable constructs (`ChartValue`, `Medicine`, `Timing`, `TreatmentRoute`). |
| **Enumerations** | Strongly-typed enums for business states, types, and classifications. |
| **Shared DTOs** | Data transfer objects used by Application services and consumed by the Host layer. |
| **Filter Models** | Pagination, sorting, and query specification objects. |
| **Domain Exceptions** | Core exception types for business rule violations. |
| **Pure Utilities** | Framework-agnostic helpers with no side effects. |
| **Repository Contracts** | `IDefaultRepository` and other foundational interfaces. |
| **Settings Models** | Strongly-typed configuration sections for options-pattern binding. |
| **Master Lists** | Reference data entities shared across clinical workflows. |

---

## Project Structure

```
adas-core.Domain/
├── Enums/                              # Business enumerations (~24 files)
│   ├── UserEnum.cs                     # LoginMethod, Type
│   ├── PatientEnum.cs, AlarmEnum.cs
│   ├── DeviceType.cs, PumpEnum.cs, RelayEnum.cs
│   ├── ObservationEnum.cs, MedicineEnum.cs
│   ├── PermissionEnum.cs, StatusEnum.cs
│   ├── MasterListType.cs, LightBeaconColor.cs
│   └── ...
├── Exceptions/                         # Domain-level exceptions
│   ├── AdasException.cs                # Root domain exception
│   ├── BusinessException.cs
│   ├── LoginServicesException.cs
│   ├── LoginServicesNotFoundException.cs
│   └── UserNotFoundException.cs
├── Models/
│   ├── MongoModels/                    # Persistent domain entities
│   │   ├── User.cs, Patient.cs
│   │   ├── Admission.cs, Discharge.cs
│   │   ├── Observation.cs, ConfigObservation.cs
│   │   ├── AlarmConfig.cs, AlarmItem.cs
│   │   ├── Device.cs, Camera.cs, LightBeacon.cs, Relay.cs
│   │   ├── PumpElement.cs, Display.cs, DisplayConfig.cs
│   │   ├── ServiceConfig.cs, Unit.cs
│   │   ├── PointOfCare.cs, PoCMapping.cs
│   │   ├── Notice.cs, Section.cs, Box.cs
│   │   ├── Authorizations.cs
│   │   └── ...
│   ├── DTO/                            # Data transfer objects
│   │   ├── PatientDto.cs, ObservationDto.cs
│   │   ├── DeviceDto.cs, PumpDto.cs
│   │   ├── CreateUserWithAuthDto.cs, UpdateUserWithAuthDto.cs
│   │   ├── PaginationPairDto.cs
│   │   └── Display/*.cs
│   ├── Filter/                         # Query/filter contracts
│   │   ├── FilteredRequest.cs
│   │   ├── FilterOptionListElement.cs
│   │   └── PaginationFilter.cs
│   ├── Responses/                      # Response wrappers
│   │   ├── LoginResponse.cs
│   │   ├── PaginationResponse.cs
│   │   ├── BeaconResponse.cs
│   │   └── Response.cs
│   ├── AppSettings/                    # Strongly-typed config models
│   │   ├── DatabaseSettings.cs, AuthSettings.cs
│   │   ├── RedisSettings.cs, RabbitMQSettings.cs
│   │   └── CacheSettings.cs, ListSettings.cs
│   ├── Masters/                        # Master-list domain types
│   │   ├── MasterList.cs, OptionList.cs
│   │   ├── DoctorList.cs, DiagnosisList.cs
│   │   ├── TreatmentList.cs, AllergyList.cs
│   │   └── ...
│   ├── Observations/                   # Observation polymorphism
│   │   ├── Observation.cs
│   │   ├── BoolObservation.cs, ChartObservation.cs
│   │   ├── DoubleObservation.cs, StringObservation.cs
│   │   ├── FullObservation.cs, Medication.cs
│   ├── Pumps/                          # Pump telemetry types
│   │   ├── CommonPumpTypes.cs, PumpState.cs
│   │   ├── PumpObservation.cs, PumpAlarmEvent.cs
│   │   └── PumpAlarmState.cs
│   ├── Recording/                      # Recording/media types
│   │   ├── AccessGrant.cs, RecordingData.cs
│   │   └── VideoDto.cs
│   ├── SignalR/                        # Real-time message models
│   │   └── Message.cs
│   ├── SystemAlerts/                   # Health/monitoring
│   │   ├── Performance.cs, Queue.cs
│   ├── Providers/                      # External-provider models
│   │   └── ProvidersSettings.cs
│   ├── BsonConverters/                 # Serialization helpers
│   │   └── DictionaryBsonConverter.cs
│   ├── Entity.cs                       # Base entity contract
│   ├── BasePatientObservation.cs
│   ├── ChartValue.cs, ChatMessage.cs
│   ├── Code.cs, GroupedObservation.cs
│   ├── Medicine.cs, PatientObservation.cs
│   ├── PatientObservationAlarm.cs
│   ├── Person.cs, Timing.cs
│   ├── TreatmentRoute.cs
│   └── WebMessageNotification.cs
├── Utils/                              # Pure utility functions
│   ├── Interfaces/
│   │   └── IMappingUtils.cs
│   ├── AuthUtils.cs, BsonUtils.cs
│   ├── CacheUtils.cs, CryptoAdas.cs
│   ├── EnumUtils.cs, JwtHelper.cs
│   ├── ObjectIdConverter.cs
│   ├── ObjectUtils.cs, StringEx.cs
│   └── JsonExtensions.cs, ...
├── Permissions.cs
├── QueryCustomizer.cs
└── IDefaultRepository.cs
```

---


## Dependencies

### Downstream References

None. This project has **zero project references**.

### Upstream References (all other projects depend on this)

| Project | Reason |
|---------|--------|
| `adas-core.Application` | Consumes domain entities, DTOs, filters, enums, and settings models. |
| `adas-core.Infrastructure` | Persists domain entities through repository implementations of domain contracts. |
| `adas-core.Authentication` | Uses `User`, `Authorization`, `UserEnum.LoginMethod`, and DTOs like `CreateUserWithAuthDto`. |
| `adas-core.LdapLogin` | Needs `User` entity and `UserEnum.LoginMethod`. |
| `adas-core.LocalLogin` | Needs `User` entity and `UserEnum.LoginMethod`. |
| `adas-core.module.LightBeacons` | Uses domain entities and enums within the module's bounded context. |
| `adas-core.module.ProxyDevices` | Uses domain entities and enums within the module's bounded context. |
| `adas-core.module.Relays` | Uses domain entities and enums within the module's bounded context. |
| `adas-core` (Host) | Passes domain entities and DTOs through controllers. |
| `adas-core.Test` | Mocks and asserts against domain objects. |

### External Packages

| Package | Version | Purpose |
|---------|---------|---------|
| `MongoDB.Bson` | 3.9.0 | `ObjectId` type used as entity identifiers. |
| `Newtonsoft.Json` | 13.0.4 | JSON serialization primitives for converters. |
| `BCrypt.Net-Next` | 4.2.0 | Cryptographic hashing primitive for password fields. |

> **Note:** No `MongoDB.Driver`, no ASP.NET Core, no Redis, no Serilog. Only primitives that enable identity (`ObjectId`), serialization (`Newtonsoft.Json`), and hashing (`BCrypt`) are permitted.

---

## Domain Entities

Entities in `Models/MongoModels/` are the persistent backbone of the system. They carry identity (typically `ObjectId`), mutable state, and often encapsulated behavior.

### Identity & Entity Base

`Entity.cs` provides the foundational identity contract shared by all persistent models. Each concrete entity extends this base, ensuring consistent identification across repositories.

### Core Entity Families

| Family | Representative Entities | Identity Scope |
|--------|------------------------|----------------|
| **Identity** | `User`, `Authorization` | System-wide; referenced by JWT claims and RBAC. |
| **Patient** | `Patient`, `PatientCarePlan`, `Admission`, `Discharge` | Medical record continuity; linked to observations and treatments. |
| **Observations** | `PatientObservation`, `PatientObservationAlarm` | Generated continuously; high-volume time-series data. |
| **Devices** | `Device`, `Camera`, `LightBeacon`, `Relay` | Hardware inventory with status and configuration state. |
| **Pumps** | `PumpElement`, `PumpState` | Real-time infusion device telemetry (scoped for per-request tracking). |
| **Displays** | `Display`, `DisplayConfig`, `DisplayCardConfig` | Bedside and ward visualization layout definitions. |
| **Configuration** | `ConfigObservation`, `ConfigPumps`, `ConfigUnits`, `ServiceConfig` | Hospital-specific deployment settings. |
| **Location** | `Unit`, `PointOfCare`, `PoCMapping`, `Section` | Physical and logical organizational structure. |
| **Communication** | `Notice`, `ChatMessage` | In-system and SignalR-delivered messaging. |

### Value Objects

Value objects (flat POCOs without identity) include `ChartValue`, `Timing`, `TreatmentRoute`, `Medicine`, `Person`, `BasePatientObservationValue`, and others. They are compared by structural equality and often nested inside entities.

---

## Enumerations

All domain enumerations live in `Enums/` and use standard C# `enum` declarations where possible. Richer enums requiring metadata map to static class dictionaries or dedicated types.

| Enumeration | Purpose |
|-------------|---------|
| `UserEnum` | Login methods (`Local`, `Ldap`), token types, and user states. |
| `PatientEnum` | Patient status codes, gender, and clinical classification. |
| `AlarmEnum` | Severity levels, acknowledgment states, and escalation rules. |
| `ObservationEnum` | Observation categories, value types (`Bool`, `Double`, `String`, `Chart`), and units. |
| `DeviceType` | Classification of medical and auxiliary devices. |
| `PumpEnum` | Pump modes, alarm categories, and operational states. |
| `RelayEnum` | Relay positions (`On`, `Off`, `Auto`) and health states. |
| `LightBeaconColor` | Visual alert color patterns for beacon devices. |
| `PermissionEnum` | System-wide permission identifiers for RBAC. |
| `StatusEnum` | Generic active/inactive/deleted entity states. |
| `MasterListType` | Taxonomy for configurable master-list option sets. |
| `RetentionPolicy` | Data retention and archival trigger policies. |
| `VirtualPointOfCare` | Named virtual units for bed management. |

---

## Shared DTOs

`Models/DTO/` houses lightweight data structures consumed by Application services and serialized by the Host. They are intentionally flat and serializable.

| DTO | Purpose |
|-----|---------|
| `PatientDto` | Flat patient summary for list views and transfers. |
| `ObservationDto` | Serialized observation payload with typed values. |
| `CreateUserWithAuthDto` / `UpdateUserWithAuthDto` | User + authority bundle for atomic creation/update. |
| `PaginationPairDto` | Page number and size pair for list endpoints. |
| `Display/*` | Specialized display configuration DTOs (nurse view, smart display, minimal, etc.). |
| `MasterListWithPaginatedOptionsDto` | Master list with paginated options for admin UIs. |
| `UpdatePasswordDto` | Old/new password pair for secure password changes. |

> **Rule:** DTOs never contain behavior. Validation is the responsibility of the Application layer.

---

## Domain Exceptions

Exceptions in `Exceptions/` represent business rule violations that higher layers translate into HTTP status codes.

| Exception | Inherits From | Meaning |
|-----------|--------------|---------|
| `AdasException` | `Exception` | Root domain exception. |
| `BusinessException` | `AdasException` | A business rule was violated. |
| `LoginServicesException` | `AdasException` | Authentication strategy encountered an internal error. |
| `LoginServicesNotFoundException` | `LoginServicesException` | Requested authentication strategy is not registered. |
| `UserNotFoundException` | `AdasException` | User lookup failed after login attempt. |

> **Rule:** Domain exceptions carry a semantic message. Infrastructure exceptions (`TimeoutException`, `MongoException`) must not leak into the Domain layer.

---

## Utilities

Utilities in `Utils/` are pure, stateless, and framework-agnostic.

| Utility | Responsibility |
|---------|---------------|
| `BsonUtils` | BSON serialization helpers (type converters, `ObjectId` helpers). |
| `EnumUtils` | Safe enum parsing, description extraction, and flag manipulation. |
| `CryptoAdas` | Hashing and cryptography primitives used by the domain. |
| `ObjectIdConverter` | JSON/BSON conversion for `ObjectId` in non-Mongo contexts. |
| `JwtHelper` | JWT claim extraction without token validation (read-only parsing). |
| `StringEx` | String sanitization, truncation, and invariant culture formatting. |
| `JsonExtensions` | Safe JSON deserialization helpers with error resilience. |
| `CacheUtils` | Cache key generation conventions shared between layers. |
| `AuthUtils` | Permission evaluation helpers operating on domain authorization data. |
| `Mapper.cs` / `IMappingUtils` | Lightweight entity-to-DTO mapping contracts. |
| `GlobalData` | Application-wide invariants (version info, build timestamps). |

> **Rule:** Utilities must not reference Infrastructure, Application, or Host assemblies. They operate exclusively on primitives and domain types.

---

## Design Rules

1. **Zero Outbound References** — The Domain layer references no other project and no framework beyond `MongoDB.Bson`. It is the innermost circle of Clean Architecture.
2. **Entities Own Their Behavior** — Business rules belong on entities. If a rule involves multiple aggregates, it belongs in the Application layer.
3. **Value Object Immutability** — All value objects must be immutable after construction. Equality is structural, not referential.
4. **Enumeration Extensibility** — Use static-class dictionaries for enums requiring runtime labels or localization; reserve standard `enum` for fixed business states.
5. **DTOs Are Contracts** — DTOs are shared serialization contracts. They never reference infrastructure types or contain methods with side effects.
6. **Settings Are Plain Objects** — Settings models in `AppSettings/` are simple POCOs. No validation logic, no configuration-loading code.
7. **Exceptions Are Semantic** — Every domain exception must convey enough meaning for the Application layer to select the correct HTTP status and error message.
8. **No Persistence Knowledge** — Entities must not know about MongoDB collections, indexes, or ORM mapping. That concern is owned entirely by `adas-core.Infrastructure`.
9. **Thread-Safe Defaults** — Entity mutation should occur within a single request scope. If concurrent mutation is possible, use optimistic concurrency tokens at the Infrastructure level.
10. **XML Documentation Required** — Every public member must carry a `<summary>` XML doc comment. This project is the canonical reference for business concepts.

---

<p align="center">
  Back to <a href="../README.md">adas-core Root README</a>
</p>

