Skip to main content
Version: 3.1

Charge Item Definition

Technical reference for the ChargeItemDefinition module in Care EMR. For the plain-language view, see the Charge Item Definition concept.

A charge item definition is a facility's pricing template for a billable service or item. Its price components are evaluated when a charge item is created from it: from an activity definition, a product dispense, a schedule booking, or a direct apply call.

The resource spans two layers. The Django model is storage: price_components and discount_configuration are opaque JSONFields. The Pydantic specs are the API: they define the status enum, shape those JSON fields with MonetaryComponent and DiscountConfiguration, validate them, and split the read and write schemas. See Resource specs (API schema).

Source:

Models​

ModelPurpose
ChargeItemDefinitionFacility-scoped pricing template that holds the price components applied to a billable resource

ChargeItemDefinition extends SlugBaseModel (FACILITY_SCOPED = True), which extends EMRBaseModel. From that chain it inherits external_id, audit fields, soft delete, and the history/meta JSON fields, and gets the slug helpers listed in Methods & save behaviour.

ChargeItemDefinition fields​

Identity & versioning​

FieldTypeRequiredNotes
facilityFK → facility.FacilityyesPROTECT. Set by the viewset on create
versionIntegerField—Default 1. Read-only in the spec. No code increments it; an update changes the record in place
statusCharField(255)yesConstrained by ChargeItemDefinitionStatusOptions. See Status values
titleCharField(255)yesDisplay name
slugCharField(255)yesStored as f-<facility external id>-<slug_value>. The client sends slug_value
derived_from_uriTextFieldnoNullable. URI of the source this definition derives from

Descriptive​

FieldTypeRequiredNotes
descriptionTextFieldnoNullable
purposeTextFieldnoNullable

Pricing & rules​

FieldTypeRequiredNotes
price_componentsJSONFieldyesDefault []. A list of MonetaryComponent. See Price components shape
discount_configurationJSONFieldkey required, value nullableDefault None. Shaped as DiscountConfiguration. See Discount configuration shape
can_edit_charge_itemBooleanFieldyesDefault True. Controls whether a charge item created from this definition keeps its price on update. See Methods & save behaviour
categoryFK → emr.ResourceCategorynoPROTECT, nullable. Supplied on write as an ExtendedSlugType slug
tagsArrayField[int]—Default []. Not in the write spec; written by set_tags/remove_tags or a tags list on create, rendered to objects on read
tags_dataJSONField—Default {}. Per-tag data keyed by tag id, such as expiry. Rendered tags carry expiry, and expired: true once it has passed

Enum values​

Status values​

ChargeItemDefinitionStatusOptions (spec.py) constrains status. The model CharField is not constrained at the database level.

ValueMeaning
draftNot ready for use. The frontend definition pickers list only active
activeIn use
retiredWithdrawn. The frontend Delete action sets this status

The backend does not check status when it applies a definition. A draft or retired definition still produces charge items wherever it is linked.

Monetary component type values​

MonetaryComponentType (common/monetary_component.py) sets the monetary_component_type of each price component.

ValueMeaning
baseThe unit price. Must carry an amount; may not have conditions
surchargeAdded to the base before discounts
discountSubtracted after surcharges, subject to the discount configuration
taxCalculated on the price after discounts
informationalNot counted in the total. The frontend stores MRP and Purchase Price as informational components

Discount applicability values​

DiscountApplicability (common/monetary_component.py) sets discount_configuration.applicability_order.

ValueMeaning
total_ascSort applicable discounts by amount, smallest first, before max_applicable is applied
total_descSort applicable discounts by amount, largest first, before max_applicable is applied

JSON field shapes​

Price components shape​

price_components is a list[MonetaryComponent]. Each entry (common/monetary_component.py):

MonetaryComponent {
monetary_component_type : MonetaryComponentType # required
code : Coding | null # system, version, code (required), display
factor : Decimal | null # max_digits=20, decimal_places=6; a percentage
amount : Decimal | null # max_digits=20, decimal_places=6; per unit
tax_included_amount : Decimal | null # max_digits=20, decimal_places=6; base only
global_component : bool # default false
conditions : list[EvaluatorConditionSpec] # default []
}

Coding forbids extra keys: system, version and display are optional strings, and code is a required string.

EvaluatorConditionSpec is metric, operation and value (an object or a string). The metric must be registered, otherwise validation fails with "Invalid metric"; the metric's evaluator validates operation and value. The registered metrics are Patient Age, Patient Gender, Patient Tag, Encounter Tag and Encounter Class.

Each MonetaryComponent is checked against these rules:

RuleDetail
tax_included_amount base onlyAllowed only when monetary_component_type is base
Base has no conditionsA base component must have no conditions
Base needs an amountA base component must have an amount
Amount or factor, not bothamount and factor cannot both be set
Amount or factor requiredOne of amount or factor must be set, except when global_component is true and a code is set

The write spec types price_components as a plain list[MonetaryComponent], so it does not apply the "Only one base component is allowed" rule. That rule runs when a charge item is costed, because sync_charge_item_costs validates the components as MonetaryComponents.

Discount configuration shape​

discount_configuration is a DiscountConfiguration | null (common/monetary_component.py):

DiscountConfiguration {
max_applicable : int # required; >= 0; 0 applies no discounts
applicability_order : DiscountApplicability # required; total_asc | total_desc
}

The frontend form and the retire action always send discount_configuration: null. A configuration set through the API is cleared on the next save from the screens.

ChargeItemDefinition references two models by foreign key:

facility → FK facility.Facility (PROTECT)
category → FK emr.ResourceCategory (PROTECT, nullable)
  • A facility cannot be deleted while definitions reference it.
  • A resource category cannot be deleted while a charge item definition uses it or while it has children.

Other models point to a charge item definition: activity definitions (charge_item_definitions), products, and schedules (consultation and re-visit charge).

Resource specs (API schema)​

The API routes through Pydantic specs built on EMRResource, which provide serialize (database to API) and de_serialize (API to database).

Spec classRoleExposes / behaviour
ChargeItemDefinitionSpecshared baseid, status, title, derived_from_uri, description, purpose, price_components, can_edit_charge_item, discount_configuration
ChargeItemDefinitionWriteSpecwrite · create + updateAdds slug_value: SlugType and an optional category: ExtendedSlugType (default None). Validates price_components
ChargeItemDefinitionReadSpecread · list + detailAdds read-only version, category (object), slug_config, tags, slug, created_by, updated_by, created_date, updated_date

Required keys on write: status, title, price_components, can_edit_charge_item, discount_configuration (may be null) and slug_value.

Write-spec validation & side effects​

  • Duplicate code check: no two price_components may share the same (code.code, monetary_component_type) pair: "Same codes for the same component type are not allowed". Only components with a code are checked.
  • perform_extra_deserialization: when category is supplied, it sets obj.category from the category slug, and it sets obj.slug to the plain slug_value. The viewset adds the facility prefix.

Read-spec serialization​

  • id comes from obj.external_id.
  • category is ResourceCategoryReadSpec.serialize(obj.category) when set.
  • slug_config is obj.parse_slug(obj.slug).
  • tags come from SingleFacilityTagManager().render_tags(obj).
  • created_by and updated_by are serialized audit users.

Slug type constraints​

TypeConstraints
SlugType (slug_value)5 to 50 characters; letters, digits, _ and -; starts and ends with a letter or digit
ExtendedSlugType (category)7 to 89 characters; same pattern; must start with f- or i-

Methods & save behaviour​

ChargeItemDefinition defines no methods of its own. The slug helpers come from SlugBaseModel, which defines no save():

MethodBehaviour
calculate_slug()Returns f-<facility external id>-<slug> when facility-scoped with a facility, otherwise i-<slug>
calculate_slug_from_facility(facility_external_id, slug)Classmethod. Builds a facility-scoped slug
calculate_slug_from_instance(slug)Classmethod. Builds an instance-scoped slug
parse_slug(slug)Splits a stored slug into facility and slug_value (f- prefix) or slug_value (i- prefix); validates the facility UUID; raises "Invalid slug" for length 2 or less or another prefix

The viewset's perform_create and perform_update set the stored slug with calculate_slug_from_facility. The same slug_value can exist in different facilities.

Applying a definition​

apply_charge_item_definition creates a charge item from a definition:

  1. The category's calculated_monetary_components are merged with the definition's price_components, keyed by code system + code. The definition's component wins on the same code; components without a code are all kept.
  2. Each component with global_component: true is replaced by the facility's discount monetary component with the same code, when the facility has one.
  3. Components whose conditions fail are left out.
  4. The charge item starts as billable. Its discount configuration is the definition's, else the facility's.
  5. sync_charge_item_costs computes the total: base × quantity, plus surcharges, minus discounts (limited by the discount configuration), plus taxes on the price after discounts. Informational components are not counted.
  6. A negative total fails with "Total price is less than 0", unless negatives are allowed.

Negatives are allowed only on charge_item/apply_charge_item_defs/ for a user who holds "Can Create Negative Charge Item" in any organization of the facility. The activity definition path applies without that flag, so an order of an activity definition linked to a negative-priced definition fails and nothing is saved.

Charge items from a non-editable definition​

When can_edit_charge_item is false, an update to a charge item created from the definition keeps the old unit price components, total price components, total price and quantity, without an error.

API integration notes​

  • The client sends slug_value, not slug. category is a slug string on write and an object on read. slug_config, tags, category and the audit users appear only on read.
  • can_edit_charge_item controls derived charge items, not the definition itself.
  • The frontend always clears discount_configuration, so charge items fall back to the facility's discount configuration.

Endpoints​

The viewset is registered under the facility at /api/v1/facility/{facility_id}/charge_item_definition/. Lookup is by slug. It has no destroy endpoint: retire with an update that sets status to retired.

EndpointMethodNotes
/GETList. Filters below; ordering on created_date, modified_date
/POSTCreate
/{slug}/GETRetrieve
/{slug}/PUTUpdate
/upsert/POSTBatch create or update from datapoints
/{slug}/set_tags/, /{slug}/remove_tags/POSTAdd or remove tags
/favorite_lists/GETThe user's favourite lists
/{slug}/add_favorite/, /{slug}/remove_favorite/POSTAdd to or remove from a favourite list

List filters​

FilterBehaviour
statusExact, case-insensitive
titleTrigram similarity above 0.1, ordered by similarity
categoryCategory slug in the same facility. Without include_children, returns the definitions in that category
include_childrenWith category and true, returns only the definitions in descendant categories (category__parent_cache__overlap). The category's own definitions are not returned, because a category's parent_cache holds only its ancestors
can_edit_charge_itemBoolean
tagsFacility tag filter (SingleFacilityTagFilter)

Validation errors​

  • Slug already used in the facility (case-insensitive): "Charge Item Definition with this slug already exists."
  • Unknown category slug in the facility: 404.
  • Duplicate code and type in price_components: "Same codes for the same component type are not allowed".

Authorization​

ActionCheckPermissionHeld where
List, retrieve, add_favorite, remove_favoritecan_list_facility_charge_item_definition (in the queryset)Can Read Charge Item DefinitionAny organization of the facility
Create, update, each upsert datapointcan_write_facility_charge_item_definitionCan Create Charge Item Definition on FacilityThe facility's root organization
set_tags, remove_tagsUpdate check, plus per tag can_apply_tag_configCan Create Charge Item Definition on Facility; Can Apply Tag Config to ResourcesRoot organization; the tag's managing organization or its parents, else any facility organization

Failures return 403 "Access Denied to Charge Item Definition". "Can Set Charge Item Definition on Facility" gates only linking a definition to a schedule.