# Charge Item

A `ChargeItem` is a single billable line for a service or product supplied to a patient — what was charged, the quantity, the unit and total price components, and any discounts or override reasons. You create one against a patient (and optionally an encounter); it always settles onto an [`Account`](https://docs.ohc.network/references/billing/account.md).

**Source:**

* Model: [`care/emr/models/charge_item.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/charge_item.py)
* Resource specs: [`care/emr/resources/charge_item/`](https://github.com/ohcnetwork/care/tree/develop/care/emr/resources/charge_item) ([`spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/charge_item/spec.py), [`sync_charge_item_costs.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/charge_item/sync_charge_item_costs.py), [`apply_charge_item_definition.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/charge_item/apply_charge_item_definition.py), [`handle_charge_item_cancel.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/charge_item/handle_charge_item_cancel.py), [`queryset.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/charge_item/queryset.py))
* Viewset: [`care/emr/api/viewsets/charge_item.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/charge_item.py)

The Django model is only the storage layer. Several fields are opaque `JSONField`s whose structure lives in the Pydantic resource specs under `care/emr/resources/charge_item/`, which also define the enums, validation, read/write API schemas, server-side cost calculation, and status side effects. The field tables below tell you what's stored; the spec and behaviour sections tell you what happens on write.

## Models

| Model | Purpose |
| - | - |
| `ChargeItem` | A single billable line item for a service or product rendered to a patient |

`ChargeItem` extends `EMRBaseModel` (shared Care EMR base with `external_id`, audit fields — `created_by`/`updated_by`/`created_date`/`modified_date` — and soft-delete semantics — see [Base model](https://docs.ohc.network/references/foundation/base-model.md)).

## `ChargeItem` fields

### Context & relationships

| Field | Type | Notes |
| - | - | - |
| `facility` | `FK → facility.Facility` (`PROTECT`) | Set server-side from the URL; a body value is ignored |
| `patient` | `FK → emr.Patient` (`CASCADE`) | When you supply an `encounter`, the patient is taken from it rather than the request |
| `encounter` | `FK → emr.Encounter` (`CASCADE`) | Nullable; the encounter the charge relates to |
| `charge_item_definition` | `FK → emr.ChargeItemDefinition` (`CASCADE`) | Nullable; the template the charge was applied from. Not on any write spec — only `apply_charge_item_definition` sets it (for example through `apply_charge_item_defs`) |
| `account` | `FK → emr.Account` (`CASCADE`) | The account this charge lands on. Falls back to the patient's default account when omitted. On create, a supplied account must belong to the URL facility and is looked up for the resolved patient |

### Description & status

| Field | Type | Notes |
| - | - | - |
| `title` | `CharField(255)` | Required; display title for the charge |
| `description` | `TextField` | Nullable; longer description |
| `status` | `CharField(255)` | Lifecycle status, constrained to `ChargeItemStatusOptions` — see [Status values](#status-values). Required on create (`ChargeItemWriteStatusOptions` only); optional on update |
| `code` | `JSONField` | Nullable; a `Coding` that identifies the charge (e.g. a billing code), shape `Coding { system?, version?, code, display? }` — see [Coding shape](#coding-shape). No bound value set |
| `note` | `TextField` | Nullable; free-text (markdown) comments |

### Pricing

| Field | Type | Notes |
| - | - | - |
| `quantity` | `DecimalField(20, 6)` | Nullable in DB; required on write; the quantity serviced. Multiplies the base/per-unit components during cost sync |
| `unit_price_components` | `JSONField` | Nullable in DB; required on write; list of `MonetaryComponent` — see [MonetaryComponent shape](#monetarycomponent-shape). At most one `base` component; duplicate component codes are rejected |
| `total_price_components` | `JSONField` | Nullable; server-computed list of `MonetaryComponent` (as dicts) — the resolved breakdown after base × quantity, surcharges, discounts, and taxes. Not client-writable |
| `total_price` | `DecimalField(20, 6)` | Nullable; server-computed total. Must be ≥ 0 unless the charge is a reversal, or `apply_charge_item_defs` runs for a user with `can_create_negative_charge_item_in_facility` |
| `override_reason` | `JSONField` | Nullable; `ChargeItemOverrideReason { text: str, code?: Coding }` explaining a list-price/factor override. No bound value set |
| `discount_configuration` | `JSONField` | Nullable (default `None`); `DiscountConfiguration { max_applicable: int (≥0), applicability_order: total_asc \| total_desc }`. Populated from the definition/facility config when applied from a definition |

### Service source

These fields trace the charge back to the resource that produced it.

| Field | Type | Notes |
| - | - | - |
| `service_resource` | `CharField(255)` | Nullable (default `None`); resource type, constrained to `ChargeItemResourceOptions` — see [Service resource types](#service-resource-types) |
| `service_resource_id` | `CharField(255)` | Nullable (default `None`); external id of the originating resource. Required once `service_resource` is set |
| `performer_actor` | `FK → users.User` (`CASCADE`) | Nullable (default `None`); the user who performed the service. Must be a member of an organization of the facility. Create and `apply_charge_item_defs` check this; update does not |

### Invoicing & tags

| Field | Type | Notes |
| - | - | - |
| `paid_invoice` | `FK → emr.Invoice` (`CASCADE`) | Nullable (default `None`); denormalized link to the settling invoice. Platform-maintained; cleared on cancel |
| `paid_on` | `DateTimeField` | Nullable (default `None`); when the charge was paid. Platform-maintained; cleared on cancel |
| `tags` | `ArrayField[int]` | Tag IDs, default `[]`. Managed through the tag mixin (`SingleFacilityTagManager`), serialized as objects on read |
| `tags_data` | `JSONField` | Default `{}`. Per-tag metadata keyed by tag ID string: `{ "<tag_id>": { "expiry": "<datetime>" } }`. Written when a tag with an expiry is set; removed when the tag is unset or expires. On read, each rendered tag gets `expiry`, plus `expired: true` after that time. Not on any spec |

## Enums

### Status values

`status` is a plain `CharField` in storage, but every write passes through `ChargeItemStatusOptions` (`care/emr/resources/charge_item/spec.py`):

| Value | Meaning |
| - | - |
| `billable` | Ready to be invoiced |
| `not_billable` | Will not be billed |
| `aborted` | Charge was cancelled before billing |
| `billed` | Included on an invoice |
| `paid` | Settled (links to `paid_invoice` / `paid_on`) |
| `entered_in_error` | Recorded in error |

(`planned` exists in the source as a commented-out option and is **not** currently selectable.)

`not_billable`, `aborted`, and `entered_in_error` form the cancelled set (`CHARGE_ITEM_CANCELLED_STATUS`). Moving into this set on update triggers the cancel side effect (see [Methods & save behaviour](#methods--save-behaviour)). `billed` and `paid` cannot be set by hand — only an invoice sets them.

### Write status values

`ChargeItemWriteSpec.status` (create) uses `ChargeItemWriteStatusOptions`, a subset of `ChargeItemStatusOptions` without `billed` and `paid`:

| Value |
| - |
| `billable` |
| `not_billable` |
| `aborted` |
| `entered_in_error` |

`ChargeItemUpdateSpec.status` accepts any `ChargeItemStatusOptions` value or `null`. The viewset then rejects a change into `billed` or `paid` (`"Billed and paid statuses can only be set by an invoice"`).

### Service resource types

`service_resource` is constrained by `ChargeItemResourceOptions`:

| Value |
| - |
| `service_request` |
| `medication_dispense` |
| `appointment` |
| `bed_association` |

On create, the viewset validates the referenced resource: `service_request` must exist (and not be completed) for the patient/encounter, and `bed_association` must reference a `FacilityLocationEncounter` on a non-completed encounter in the facility. Any other value (`medication_dispense`, `appointment`) fails this check with `"Invalid service resource"`. Only server flows, such as medication dispense and appointment booking, set those two types.

### MonetaryComponentType values

Used by every entry in `unit_price_components` / `total_price_components` (`care/emr/resources/common/monetary_component.py`):

| Value | Role in cost sync |
| - | - |
| `base` | Per-unit base price. At most one allowed; must carry `amount` (not `factor`); no `conditions`. `base.amount × quantity` seeds the running total |
| `surcharge` | Added on top of base; `amount` or `factor` (% of base) |
| `discount` | Subtracted from the net price; `amount` or `factor` (% of net). Filtered/limited by `discount_configuration` |
| `tax` | Added on the post-discount taxable price; `amount` or `factor` (% of taxable) |
| `informational` | Ignored by cost sync. Stays in `unit_price_components`; not copied to `total_price_components` and does not affect `total_price` |

### DiscountApplicability values

`discount_configuration.applicability_order` (`care/emr/resources/common/monetary_component.py`):

| Value | Effect |
| - | - |
| `total_asc` | Sort candidate discounts by amount ascending before applying `max_applicable` |
| `total_desc` | Sort by amount descending before applying `max_applicable` |

`max_applicable = 0` drops all discounts. With no `discount_configuration`, every discount applies.

## JSON field shapes

### Coding shape

`code`, plus the `code` field inside components and `override_reason` (`care/emr/resources/common/coding.py`, `extra="forbid"`):

```
Coding {

  system?:  str

  version?: str

  code:     str        # required

  display?: str

}
```

### MonetaryComponent shape

Each entry of `unit_price_components` and `total_price_components` (`care/emr/resources/common/monetary_component.py`):

```
MonetaryComponent {

  monetary_component_type: base | surcharge | discount | tax | informational   # required

  code?:                Coding

  factor?:              Decimal(20,6)      # percentage; mutually exclusive with amount

  amount?:              Decimal(20,6)      # absolute; mutually exclusive with factor

  tax_included_amount?: Decimal(20,6)      # base component only

  global_component:     bool = False       # resolved against facility monetary config

  conditions:           [EvaluatorConditionSpec] = []   # not allowed on base

}
```

Validation: exactly one of `amount`/`factor` (unless `global_component` with a `code`); `base` must have `amount`, no `factor`, no `conditions`; `tax_included_amount` only on `base`; duplicate component `code`s are rejected. A zero `amount` or `factor` counts as present.

Cost sync re-reads the list as `MonetaryComponents`. When the `base` component has `tax_included_amount`, the tax components plus `tax_included_amount` must equal the base `amount`.

`EvaluatorConditionSpec { metric: str, operation: str, value: dict | str }` — conditions are evaluated against patient/facility/encounter context when a definition is applied; a component whose conditions fail is dropped.

### ChargeItemOverrideReason shape

`override_reason` (`care/emr/resources/charge_item/spec.py`):

```
ChargeItemOverrideReason {

  text: str            # required

  code?: Coding        # no bound value set

}
```

### DiscountConfiguration shape

`discount_configuration` (`care/emr/resources/common/monetary_component.py`):

```
DiscountConfiguration {

  max_applicable:      int (>= 0)               # 0 drops all discounts

  applicability_order: total_asc | total_desc

}
```

## Resource specs (API schema)

Charge items are exposed through `ChargeItemViewSet` (create / retrieve / update / upsert / list / tag actions, plus the `apply_charge_item_defs` and `change_account` custom actions). The Pydantic specs in `care/emr/resources/charge_item/spec.py` build on `EMRResource` (`serialize` / `de_serialize`, with `perform_extra_serialization` / `perform_extra_deserialization` hooks).

| Spec | Role | Notes |
| - | - | - |
| `ChargeItemSpec` | shared base | `__model__ = ChargeItem`, `__exclude__ = ["encounter", "account"]`. Fields: `id`, `title`, `description`, `status`, `code`, `quantity`, `unit_price_components`, `note`, `override_reason`. Validators: no duplicate component codes, ≤1 `base` component |
| `ChargeItemWriteSpec` | write · create | Extends base with `encounter`, `patient`, `account`, `service_resource`, `service_resource_id`, `performer_actor` (all `UUID4`/enum, optional). Narrows `status` to `ChargeItemWriteStatusOptions`. Requires `encounter` **or** `patient`; requires `service_resource_id` when `service_resource` set |
| `ChargeItemUpdateSpec` | write · update | Base fields + `performer_actor`; `status` becomes optional (`ChargeItemStatusOptions \| None`). Does not re-bind patient/encounter/account |
| `ChargeItemReadSpec` | read · list & detail | Base fields + server-side: `total_price_components`, `total_price`, `charge_item_definition` (nested), `paid_invoice` (nested), `tags` (objects), `service_resource(_id)`, `created_date`, `modified_date`, `paid_on`, `performer_actor`, `created_by`, `updated_by`, `discount_configuration` |

Notable validation and binding:

* `code`, `override_reason.code`, and component `code`s are FHIR-aligned `Coding`s with **no bound value set**.
* `ChargeItemWriteSpec.perform_extra_deserialization` resolves `patient`/`encounter`/`account`/`performer_actor` from external ids; supplying `encounter` overrides `patient` with the encounter's patient, and `account` is looked up scoped to that patient.
* `ChargeItemReadSpec.perform_extra_serialization` nests the full `ChargeItemDefinitionReadSpec` and `InvoiceReadSpec`, renders tags, and resolves `performer_actor` / `created_by` / `updated_by` from the user cache.

### Nested / related specs

| Spec | Used by | Shape |
| - | - | - |
| `Coding` | `code`, component & override codes | see [Coding shape](#coding-shape) |
| `MonetaryComponent` | `unit_price_components`, `total_price_components` | see [MonetaryComponent shape](#monetarycomponent-shape) |
| `ChargeItemOverrideReason` | `override_reason` | `{ text, code? }` |
| `DiscountConfiguration` | `discount_configuration` | `{ max_applicable, applicability_order }` |
| `ChargeItemDefinitionReadSpec` | `charge_item_definition` (read) | full nested definition — see [Charge Item Definition](https://docs.ohc.network/references/definitions/charge-item-definition.md) |
| `InvoiceReadSpec` | `paid_invoice` (read) | full nested invoice — see [Invoice](https://docs.ohc.network/references/billing/invoice.md) |
| `UserSpec` | `performer_actor`, audit users (read) | see [User](https://docs.ohc.network/references/access-governance/user.md) |

## Related models

`ChargeItem` is a leaf model — it holds foreign keys rather than owning child rows:

```
facility               → FK facility.Facility (PROTECT)

patient                → FK emr.Patient (CASCADE)

encounter              → FK emr.Encounter (CASCADE, nullable)

charge_item_definition → FK emr.ChargeItemDefinition (CASCADE, nullable)

account                → FK emr.Account (CASCADE)

paid_invoice           → FK emr.Invoice (CASCADE, nullable)

performer_actor        → FK users.User (CASCADE, nullable)
```

## Methods & save behaviour

Cost resolution and status side effects live in the spec helpers and the viewset, not in the model's `save()`.

* **Cost sync (`sync_charge_item_costs`)** — runs on every create and on update (unless suppressed). It walks `unit_price_components`: multiplies the `base` amount by `quantity` to seed `total_price`/`base`, adds `surcharge`s, applies `discount`s (filtered by `discount_configuration` via `apply_discount_configuration`), then adds `tax`es on the taxable price. It skips `informational` components. It writes the resolved breakdown to `total_price_components` and the sum to `total_price`, and raises `ValidationError` if `total_price < 0` on a non-reversal charge.
* **Apply from definition (`apply_charge_item_definition` / `POST apply_charge_item_defs`)** — builds a `ChargeItem` from a `ChargeItemDefinition`: copies `title`/`description`, merges the category's `calculated_monetary_components` with the definition's components, replaces each `global_component` with the facility override when one exists, evaluates each component's `conditions` against patient/facility/encounter context (dropping unmet ones), sets `status = billable`, resolves `discount_configuration` (definition first, then facility config), defaults the account to the patient's default account, and runs cost sync. `reverse` negates component amounts to produce a credit; only the return-invoice flow passes it.
* **`apply_charge_item_defs` request** — a `requests` list of `ApplyChargeItemDefinitionRequest` items: `charge_item_definition` (the definition slug in this facility), `quantity` (`int`), `encounter` or `patient`, and optional `account`, `performer_actor`, `service_resource`, `service_resource_id`. A supplied `account` must be `active` and belong to the facility and patient. All items save in one transaction.
* **Cancel (`handle_charge_item_cancel`)** — detaches a charge item from its invoice when the item is cancelled. If the invoice is a **draft**, it removes the item from the invoice, rebalances and saves the invoice, and clears `paid_invoice` / `paid_on`. A non-draft invoice raises `"Cannot cancel charge item in a non-draft invoice"`; an item missing from the invoice's `charge_items` raises `"Charge item not found in invoice"`. Service request, booking, medication dispense, and dispense order cancellations call it without `account_locked`. `handle_charge_item_cancel` then takes `AccountLock` itself, re-reads the item, and raises `ObjectLocked` if the item changed account. Those callers then set the item to `aborted`. The charge item update endpoint calls it when `status` moves into `CHARGE_ITEM_CANCELLED_STATUS`. That endpoint first rejects a status change on an item that is on an invoice, so through it only items without an invoice cancel. Cost sync is skipped for cancellations.
* **Update guards (`validate_data` / `perform_update`)** — a charge in a cancelled status can't be updated; updates are blocked when the linked invoice is `balanced`/`issued`; `status` can't be moved by hand into `billed`/`paid`; `status` can't change while the item has a `paid_invoice` (`"Remove charge item from its invoice before changing its status"`); and if the source definition has `can_edit_charge_item = False`, the pricing fields (`unit_price_components`, `total_price_components`, `total_price`, `quantity`) are reset from the previous object and cost sync is skipped. After update, a draft `paid_invoice` is re-synced.
* **Update locking (`handle_update`)** — every update runs inside `AccountLock` on the item's account and re-reads the item. If the item moved to another account meanwhile, the update fails with `ObjectLocked` (HTTP 423).
* **Cancel authorization (`authorize_cancel`)** — cancellation is free within `CHARGE_ITEM_FREE_CANCEL_PERIOD_MINUTES` of creation (default `0`); after that it needs the `can_cancel_charge_item_in_facility` permission.
* **Change account (`POST change_account`)** — moves 1 to 100 charge items to a target account in the facility. It needs `can_create_charge_item_in_facility`. Each item must belong to the target account's patient, be `billable`, and have no `paid_invoice`. It locks every affected account, saves the items, then runs `rebalance_account_task` inline for each affected account. It returns HTTP 201.

## API integration notes

* The viewset sets `facility` from the URL and ignores any body value; `patient` is derived from `encounter` when one is supplied.
* A charge item must resolve to an `account` — with none supplied, the patient's default account is used. `encounter` and `charge_item_definition` are optional.
* `total_price`, `total_price_components`, `paid_invoice`, and `paid_on` are server-maintained; don't set them from clients.
* Create and `apply_charge_item_defs` enforce that `performer_actor` is a member of an organization of the facility. Update does not re-check it.
* On create, a supplied `encounter` and `account` must belong to the URL facility.
* List and retrieve load items through `charge_items_for_serialization` (`queryset.py`). It prefetches the definition, its category, and `paid_invoice`, and defers the invoice's large JSON fields.
* `discount_configuration` and `tags` are structured but deployment-tunable: `discount_configuration` follows `DiscountConfiguration`, and tags resolve through the single-facility tag manager.

## Related

* Reference: [Account](https://docs.ohc.network/references/billing/account.md)
* Reference: [Charge Item Definition](https://docs.ohc.network/references/definitions/charge-item-definition.md)
* Reference: [Invoice](https://docs.ohc.network/references/billing/invoice.md)
* Reference: [Payment Reconciliation](https://docs.ohc.network/references/billing/payment-reconciliation.md)
* Reference: [Patient](https://docs.ohc.network/references/clinical/patient.md)
* Reference: [Encounter](https://docs.ohc.network/references/clinical/encounter.md)
* Reference: [User](https://docs.ohc.network/references/access-governance/user.md)
* Reference: [Base model](https://docs.ohc.network/references/foundation/base-model.md)
* Source: [charge\_item.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/charge_item.py)
* Source: [charge\_item resource specs on GitHub](https://github.com/ohcnetwork/care/tree/develop/care/emr/resources/charge_item)
