# Specimen

Technical reference for the `Specimen` module in Care EMR. For what a specimen is, see the [Specimen](https://docs.ohc.network/concepts/clinical/specimen.md) concept.

A `Specimen` records material collected from a patient for a service request. You create one through the service request, then update it as the specimen moves through collection, receipt, and processing.

Several of the model's fields (`care/emr/models/specimen.py`) are opaque `JSONField`s whose structure lives only in the Pydantic resource specs (`care/emr/resources/specimen/`). The specs define the enums, nested JSON shapes, value-set bindings, validation, and the read/write schemas, so you need both layers to work with this resource.

**Source:**

* Model: [`care/emr/models/specimen.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/specimen.py)
* Resource specs: [`care/emr/resources/specimen/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/specimen/spec.py), [`valueset.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/specimen/valueset.py)
* Specimen type value set: [`care/emr/resources/specimen_definition/valueset.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/specimen_definition/valueset.py)
* Viewset: [`care/emr/api/viewsets/specimen.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/specimen.py)
* Creation: [`care/emr/api/viewsets/service_request.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/service_request.py) (`create_specimen`, `create_specimen_from_definition`), [`care/emr/resources/specimen_definition/specimen.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/specimen_definition/specimen.py) (`convert_sd_to_specimen`)
* Authorization: [`care/security/authorization/service_request.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/authorization/service_request.py)

## Models

| Model | Purpose |
| - | - |
| `Specimen` | A sample collected from a patient to fulfil a service request |

`Specimen` extends [`EMRBaseModel`](https://docs.ohc.network/references/foundation/base-model.md), the shared Care EMR base providing `external_id`, audit fields, soft-delete through `deleted`, and `history`/`meta` JSON.

## `Specimen` fields

### Identity & status

| Field | Model type | Spec shape / values | Notes |
| - | - | - | - |
| `accession_identifier` | `CharField(255)`, `db_index=True` | `str`, default `""` | Lab accession identifier; indexed for lookup, not unique. Defaults to `""`, so it is optional on write. On create, a blank value becomes the specimen's `external_id`. On update, a blank value keeps the stored identifier. |
| `status` | `CharField(20)` | `SpecimenStatusOptions` enum | Required in `BaseSpecimenSpec`, optional in `SpecimenUpdateSpec`. `create_specimen_from_definition` defaults it to `available`. See [status values](#specimenstatusoptions-values). |
| `specimen_type` | `JSONField` | `Coding` bound to value set `system-specimen_type-code` | Kind of material collected, as a single coding. Required in `BaseSpecimenSpec`, optional in `SpecimenUpdateSpec`. `create_specimen_from_definition` takes it from the definition's `type_collected` unless the request sends one. |

### Clinical links

| Field | Model type | Notes |
| - | - | - |
| `facility` | `FK → Facility` | `PROTECT`, nullable; the facility the specimen belongs to. Set on create from the service request's facility. Excluded from all specs (`__exclude__`). |
| `patient` | `FK → Patient` | `CASCADE`; the patient the specimen was collected from. Set on create from the service request's patient. |
| `encounter` | `FK → Encounter` | `CASCADE`, nullable; set on create from the service request's encounter. |
| `service_request` | `FK → ServiceRequest` | `CASCADE`, nullable; the order this specimen fulfills. Set on create to the service request the create action runs on. Authorization checks run against it. |
| `specimen_definition` | `FK → SpecimenDefinition` | `CASCADE`, nullable; the specimen definition this specimen was created from. Set by `create_specimen_from_definition`. |

### Collection & processing

| Field | Model type | Spec shape | Notes |
| - | - | - | - |
| `collection` | `JSONField` `default=dict` | `CollectionSpec \| None`, default `None` | A single collection event: collector, collected time, quantity, method, body site, fasting. See [CollectionSpec](#collectionspec). |
| `received_time` | `DateTimeField`, nullable | `str \| None`, default `None` | When the specimen was received. |
| `condition` | `JSONField` `default=list` | `list[Coding]` bound to `system-specimen-condition-code`, default `[]` | Coded conditions of the specimen (HL7 v2-0493). |
| `processing` | `JSONField` `default=list` | `list[ProcessingSpec]`, default `[]` | Processing steps applied. See [ProcessingSpec](#processingspec). |
| `note` | `TextField`, nullable | `str \| None`, default `None` | Free-text annotation. |

## Enums

### `SpecimenStatusOptions` values

The `status` enum (`str`). `draft` is Care's own addition.

| Value | Meaning |
| - | - |
| `draft` | Care-specific. The web frontend creates a specimen as `draft` before collection. |
| `available` | Default status from `convert_sd_to_specimen`. The web frontend sets it when the specimen is collected. |
| `unavailable` | Discard reason in the web frontend: "The specimen is lost, destroyed, or consumed". |
| `unsatisfactory` | Discard reason in the web frontend: "The specimen is unusable due to quality issues". |
| `entered_in_error` | Discard reason in the web frontend: "The specimen record was created by mistake". |

## Nested JSON specs

These define the real structure behind the model's `JSONField`s.

### `CollectionSpec`

Shape of the `collection` JSON field: a single collection event.

| Field | Type | Required | Notes |
| - | - | - | - |
| `collector` | `UUID4 \| None` | optional | External ID of the collecting `User`. Validated to exist (`User.objects.filter(external_id=...)`), else rejected with `"Collector user not found"`. Serialized output adds `collector_object`, the resolved `UserSpec` from cache. |
| `collected_date_time` | `datetime \| None` | optional | When the specimen was collected. |
| `quantity` | `QuantitySpec \| None` | optional | Amount collected. See [QuantitySpec](#quantityspec). |
| `method` | `Coding \| None` bound to `system-collection-method-code` | optional | Collection method (SNOMED CT). See [collection method values](#collection-method-value-set). |
| `body_site` | `Coding \| None` bound to `system-body-site-observation` | optional | Anatomical site collected from. |
| `fasting_status_codeable_concept` | `Coding \| None` bound to `system-fasting-status-code` | optional | Patient fasting status (HL7 v2-0916). |
| `fasting_status_duration` | `DurationSpec \| None` | optional | Fasting duration. See [DurationSpec](#durationspec). |

### `ProcessingSpec`

One element of the `processing` list.

| Field | Type | Required | Notes |
| - | - | - | - |
| `description` | `str` | required | Description of the processing step. |
| `method` | `Coding \| None` bound to `system-specimen-processing-method-code` | optional | Processing method (SNOMED CT, descendants of `9265001`). |
| `performer` | `UUID4 \| None` | optional | External ID of the performing `User`. Validated to exist, else rejected with `"Performer user not found"`. Serialized output adds `performer_object`, the resolved `UserSpec` from cache. |
| `time_date_time` | `str` | required | When the step was performed. |

### `QuantitySpec`

| Field | Type | Notes |
| - | - | - |
| `value` | `Decimal` | `max_digits=20`, `decimal_places=0`, so integer-valued. |
| `unit` | `Coding` | Required unit coding. |

This is a specimen-local quantity spec, distinct from the shared [`Quantity`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/common/quantity.py) common type, which allows `decimal_places=6`, optional `value`/`unit`, plus `code`/`meta`.

### `DurationSpec`

| Field | Type | Notes |
| - | - | - |
| `value` | `int` | Duration magnitude. |
| `unit` | `Coding` | Required unit coding. |

### `Coding` (shared common type)

Every coded field above uses [`Coding`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/common/coding.py) (`extra="forbid"`):

| Field | Type | Required |
| - | - | - |
| `system` | `str \| None` | optional |
| `version` | `str \| None` | optional |
| `code` | `str` | required |
| `display` | `str \| None` | optional |

## Bound value sets

The coded fields in the table below bind to Care value sets through `ValueSetBoundCoding[<slug>]`, which validates the submitted `code` against the value set at write time.

| Field | Value set | Slug | Source system |
| - | - | - | - |
| `specimen_type` | Specimen Type Code | `system-specimen_type-code` | HL7 v2-0487 |
| `condition[]` | Specimen Condition | `system-specimen-condition-code` | HL7 v2-0493 (v2.0.0) |
| `collection.method` | Collection Method | `system-collection-method-code` | SNOMED CT (enumerated, see below) |
| `collection.body_site` | Body Site | `system-body-site-observation` | (observation body-site value set) |
| `collection.fasting_status_codeable_concept` | Fasting Status | `system-fasting-status-code` | HL7 v2-0916 (v2.0.0) |
| `processing[].method` | Specimen Processing Method | `system-specimen-processing-method-code` | SNOMED CT (`< 9265001`) |

The Specimen Type Code value set is defined in `care/emr/resources/specimen_definition/valueset.py`, not in the specimen's own value set file. Body Site is defined in `care/emr/resources/observation/valueset.py`. The others are in `care/emr/resources/specimen/valueset.py`.

### Collection Method value set

The `system-collection-method-code` value set enumerates these SNOMED CT codes:

| Code | Display |
| - | - |
| `129316008` | Aspiration - action |
| `129314006` | Biopsy - action |
| `129300006` | Puncture - action |
| `129304002` | Excision - action |
| `129323009` | Scraping - action |
| `73416001` | Urine specimen collection, clean catch |
| `225113003` | Timed urine collection |
| `70777001` | Urine specimen collection, catheterized |
| `386089008` | Collection of coughed sputum |
| `278450005` | Finger-prick sampling |

Fasting Status (`http://terminology.hl7.org/CodeSystem/v2-0916`), Specimen Condition (`v2-0493`) and Specimen Type (`v2-0487`) are pulled in by code-system reference rather than a fixed concept list. Specimen Processing Method uses a SNOMED CT filter (`< 9265001`). Body Site combines a fixed list of SNOMED CT concepts with an `is-a 442083009` filter.

## Resource specs (API schema)

`BaseSpecimenSpec` and its subclasses extend `EMRResource` (`care/emr/resources/base.py`), which provides `serialize` (DB object → pydantic, through `get_database_mapping`) and `de_serialize` (pydantic → DB object), plus the `perform_extra_serialization` / `perform_extra_deserialization` hooks. `__exclude__ = ["facility", "request"]` on the base keeps those fields from being copied field-for-field.

| Spec class | Role | Key fields / behaviour |
| - | - | - |
| `BaseSpecimenSpec` | shared base; request body of `create_specimen`; read spec of a specimen shared in a referral | `id`, `accession_identifier`, `status` (required), `specimen_type` (required), `received_time`, `collection`, `processing`, `condition`, `note`. `__model__ = Specimen`, `__exclude__ = ["facility", "request"]`. |
| `SpecimenCreateSpec` | defined, not used | Adds `subject_patient: UUID4` (required), `subject_encounter: UUID4` (required), `request: UUID4 \| None`. No endpoint uses this spec: both create actions take other specs and copy the links from the service request. |
| `SpecimenUpdateSpec` | write · update; also the `specimen` part of the `create_specimen_from_definition` body | Relaxes `status` and `specimen_type` to optional (`\| None`) for partial updates. |
| `SpecimenReadSpec` | read · embedded: the `specimens` list of the service request detail response, and the response of both create actions | Adds `specimen_definition: dict \| None`. `perform_extra_serialization` sets `id = external_id` and, when present, embeds the linked specimen definition through `SpecimenDefinitionReadSpec.serialize(...).to_json()`. |
| `SpecimenRetrieveSpec` | read · detail: retrieve, the update response, and the accession identifier lookup | Extends `SpecimenReadSpec`, adds `service_request: dict \| None`; serialization additionally embeds the linked service request through `ServiceRequestReadSpec.serialize(...).to_json()`. |

Nested specs (defined in the same module): `CollectionSpec`, `ProcessingSpec`, `QuantitySpec`, `DurationSpec`. See [Nested JSON specs](#nested-json-specs).

### Validation & server behaviour

* `collection.collector` and `processing[].performer` must reference existing users by `external_id`; serialization then injects the resolved `collector_object` / `performer_object` (cached `UserSpec`).
* The bound coded fields (`ValueSetBoundCoding`) are validated against their value sets on write; a `code` outside the value set is rejected.
* The read specs embed related resources as nested JSON: the linked specimen definition in `SpecimenReadSpec` and `SpecimenRetrieveSpec`, and the linked service request in `SpecimenRetrieveSpec` only.
* Care skips fields left at their default when it saves a request, so an empty `accession_identifier` sent on update keeps the stored identifier.
* No rule controls status changes: an update can set any status. Neither create nor update checks the service request's status.
* The specimen specs don't override `perform_extra_deserialization`, so Care appends no server-side status history on write.

## API integration notes

* The API sits under a facility: `/api/v1/facility/{facility}/specimen/`.
* The viewset (`SpecimenViewSet`) mixes in retrieve and update only (`EMRRetrieveMixin`, `EMRUpdateMixin`), plus the custom action `POST retrieve_by_accession_identifier`. It has no create, no list and no delete.
* The viewset sets `pydantic_model = BaseSpecimenSpec`, `pydantic_update_model = SpecimenUpdateSpec`, `pydantic_read_model = SpecimenReadSpec` and `pydantic_retrieve_model = SpecimenRetrieveSpec`.
* The viewset has no `get_queryset` of its own, so it does not filter specimens by the facility in the URL: it uses the base queryset of all specimens.
* The custom action `POST retrieve_by_accession_identifier` looks up a specimen by `accession_identifier`, which must be at least 5 characters ("Accession identifier must be at least 5 characters long").
* The lookup matches the identifier exactly among all specimens, not only those of the facility in the URL. It returns a `SpecimenRetrieveSpec`.
* Because `accession_identifier` is not unique, the lookup can find more than one specimen. It then fails with "Multiple specimens found with the same accession identifier".
* When no specimen matches, the lookup answers 404. The message "Specimen not found with the given accession identifier" in the code is never sent.
* The service request detail response embeds every specimen of the request, in any status, as `SpecimenReadSpec`.

### Creation through the service request

* The specimen API has no create. Specimens are created through two detail `POST` actions on the service request: `create_specimen` and `create_specimen_from_definition`.
* `create_specimen` takes a `BaseSpecimenSpec` body. `create_specimen_from_definition` takes `specimen_definition` (UUID) and `specimen` (a `SpecimenUpdateSpec`).
* The web frontend calls only `create_specimen_from_definition`. Its `create_specimen` call is commented out.
* Care finds the service request among the service requests of the facility in the URL.
* Both actions check `can_write_specimen` on the service request. Without it they answer 403 "You do not have permission to create a specimen for this encounter".
* `create_specimen_from_definition` looks up the specimen definition by `external_id` in the facility in the URL. A definition of another facility gives 404.
* `convert_sd_to_specimen` builds the new specimen: it links the specimen definition, sets `specimen_type` to the definition's `type_collected`, and sets `status` to `available`.
* A `status` or `specimen_type` sent in the request's `specimen` overrides these values. The web frontend sends `status` `draft` and the definition's `type_collected`.
* Both actions copy `patient`, `encounter` and `facility` from the service request and link the specimen to the service request.
* If `accession_identifier` is blank, Care sets it to the specimen's `external_id`.
* Both actions return a `SpecimenReadSpec`.
* Neither action checks the service request's status. Service request update, by contrast, refuses a completed or cancelled request.

### Authorization

Authorization keys off the linked `service_request`. One service request may own many specimens.

| Action | Check | Permission | Refusal |
| - | - | - | - |
| retrieve | `can_read_specimen` on the specimen's service request | "Can Read Specimen" (`can_read_specimen`) | 403 "You do not have permission to read this specimen" |
| update | `can_write_specimen` on the specimen's service request | "Can Create Specimen on Facility" (`can_write_specimen`) | 403 "You do not have permission to write this specimen" |
| `retrieve_by_accession_identifier` | `can_read_specimen` on the matched specimen's service request, after the match | "Can Read Specimen" (`can_read_specimen`) | 403 "You do not have permission to read this specimen" |
| `create_specimen`, `create_specimen_from_definition` | `can_write_specimen` on the service request | "Can Create Specimen on Facility" (`can_write_specimen`) | 403 "You do not have permission to create a specimen for this encounter" |

* Both checks use the service-request rule. The user must hold the permission in the encounter's departments, or in a department of one of the request's locations.
* The encounter's departments are the departments added to the encounter with their parents, the departments of the encounter's current location, and the facility's Administration department.
* A location's departments are the departments linked to the location with their parents, the departments of its parent location, and the facility's Administration department.
* The user passes when they hold, in one of those departments, a role that carries the permission. A superuser always passes.
* By default, Facility Admin, Doctor and Nurse hold "Can Create Specimen on Facility". Facility Admin, Administrator, Staff, Doctor, Nurse and Pharmacist hold "Can Read Specimen".
* Opening a service request checks only `can_read_service_request`. The specimens embedded in that response are not checked against "Can Read Specimen".
* Attaching a specimen to a referral checks `can_read_specimen` on the specimen's service request. A user who opens the shared specimen in the referral needs access to the referral only.

## Related models

| Field | Target | On delete | Set on create |
| - | - | - | - |
| `facility` | `Facility`, nullable | `PROTECT` | From the service request; excluded from specs |
| `patient` | `Patient` | `CASCADE` | From the service request |
| `encounter` | `Encounter`, nullable | `CASCADE` | From the service request |
| `service_request` | `ServiceRequest`, nullable | `CASCADE` | The service request the create action runs on |
| `specimen_definition` | `SpecimenDefinition`, nullable | `CASCADE` | The definition used by `create_specimen_from_definition` |

A `Specimen` is created through a [`ServiceRequest`](https://docs.ohc.network/references/clinical/service-request.md) and may be created from a [`SpecimenDefinition`](https://docs.ohc.network/references/definitions/specimen-definition.md). A [`DiagnosticReport`](https://docs.ohc.network/references/clinical/diagnostic-report.md) has no link to a specimen: a specimen and a report meet only through their shared service request.

## Related

* Concept: [Specimen](https://docs.ohc.network/concepts/clinical/specimen.md)
* Reference: [Specimen Definition](https://docs.ohc.network/references/definitions/specimen-definition.md)
* Reference: [Service Request](https://docs.ohc.network/references/clinical/service-request.md)
* Reference: [Diagnostic Report](https://docs.ohc.network/references/clinical/diagnostic-report.md)
* Reference: [Patient](https://docs.ohc.network/references/clinical/patient.md)
* Reference: [Base Model](https://docs.ohc.network/references/foundation/base-model.md)
* Source (model): [specimen.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/specimen.py)
* Source (spec): [specimen/spec.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/specimen/spec.py)
* Source (value sets): [specimen/valueset.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/specimen/valueset.py), [specimen\_definition/valueset.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/specimen_definition/valueset.py)
* Source (creation): [service\_request.py viewset on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/service_request.py)
