Skip to main content
Version: 3.1

Consent

Technical reference for the Consent module in Care EMR. For what a consent is and who can work with it, read the Consent concept.

A Consent records a decision, permit or deny, with one category, such as treatment, research or privacy. Each consent belongs to one encounter and reaches its patient through that encounter.

Source:

The Django model is the storage layer: status, category and decision are plain CharFields, and period and verification_details are JSONFields.

The resource specs define the allowed values, the shape of period, and the read and write schemas. The viewset adds the patient match and the one-verification-per-user rule. The closed-encounter block is in the authorization handler can_update_encounter_clinical_data, which the viewset calls.

Models​

ModelPurpose
ConsentA permit-or-deny decision with one category, attached to one encounter

Consent extends EMRBaseModel. The base provides external_id, created_date, modified_date, the soft-delete flag deleted, created_by, updated_by, history and meta.

Storage type is the Django column. Spec type is the type the API enforces. On create is the rule in ConsentCreateSpec.

FieldStorage typeSpec typeOn createNotes
statusCharField(50)ConsentStatusChoicesRequiredSee values
categoryCharField(50)CategoryChoiceRequiredSee values. The app offers six of the seven values
dateDateTimeFielddatetimeRequiredThe date and time the consent was given. The app labels it Consent Given On
periodJSONField, default dictPeriodSpec (start, end)Send it on create. Without it, the create fails with HTTP 500 and stores nothing; {} is acceptedBoth start and end are optional, and each must be timezone-aware when set. start cannot be after end. On create only, start cannot be before date. The app labels the ends Consent Valid From and Consent Valid Until. See PeriodSpec
encounterForeignKey to emr.Encounter (CASCADE, related_name="consents")UUID4 (encounter external_id)RequiredMust belong to the patient in the URL. Cannot change after create. In __exclude__, so the generic field copy skips it
decisionCharField(10)DecisionTypeRequiredSee values
verification_detailsJSONField, default listlist[dict] (read schemas only)Not in the schemaNot in the create or update schema. Only add_verification and remove_verification change it. See Verification actions
noteTextField, nullable, blankstr | NoneOptionalOn update, null keeps the stored note

On update, every field is optional, and a field sent as null or left out keeps its stored value. So PUT behaves like PATCH.

source_attachments is not a model field. The read schemas build it from FileUpload records when they serialize a consent.

Enum values​

ConsentStatusChoices values​

ValueLabel in the app
draftDraft
activeActive
inactiveInactive
not_doneNot Done
entered_in_errorEntered in Error

No consent code reacts to the status value. See Methods & save behaviour.

CategoryChoice values​

ValueLabel in the appDescription in the app
researchResearch"Consent to participate in research protocol and information sharing"
patient_privacyPrivacy Consent"Consent to collect, access, use or disclose (share) information"
treatmentTreatment"Consent to undergo a specific treatment"
dnrDo Not Resuscitate"Consent to not receive CPR or resuscitation initiated in case of a cardiac event"
comfort_careNo labelThe server accepts it. The app does not offer it and has no label for it
acdAdvance Directive"Consent given in anticipation of a potential need for medical treatment"
adrAdvance Care Directive"Consent for actions to be taken if they are no longer able to make decisions for themselves"

CategoryChoice also has a commented-out consent_document member (LOINC 59284-0), so the API does not accept that value. Its code comment says it is used only in migrations, but no migration contains it.

DecisionType values​

ValueLabel in the appText on the consent card
permitPermitPermitted
denyDenyDenied

The app labels the form field Consent Decision.

VerificationType values​

These values are used in verification_type of the add_verification body. The app has no label for them.

ValueMeaning
familyThe consent was given by a family member
validationThe consent was validated by the patient themself

Nested JSON shapes​

PeriodSpec nested shape​

The period field uses PeriodSpec from care/emr/resources/base.py.

FieldTypeNotes
startdatetime | NoneDefault None. Must be timezone-aware if set
enddatetime | NoneDefault None. Must be timezone-aware if set

PeriodSpec enforces these rules wherever a request sets period:

  • A start without a timezone fails with "Start Date must be timezone aware".
  • An end without a timezone fails with "End Date must be timezone aware".
  • A start later than end fails with "Start Date cannot be greater than End Date".

ConsentCreateSpec adds one rule on create only. A start earlier than date fails with "Start of the period cannot be before than the Consent date". A start equal to date passes.

ConsentVerificationSpec nested shape​

ConsentVerificationSpec is the request body of add_verification. Each successful call appends one entry to verification_details, which the read schemas type as list[dict]. A second call by the same user fails.

FieldTypeRequiredNotes
verifiedboolRequiredThe entry is stored even when the value is false
verified_byUUID4 | NoneOptionalThe server overwrites it with the requesting user. On read, it becomes that user's UserSpec
verification_datedatetime | NoneOptionalThe server overwrites it with the current time
verification_typeVerificationTypeRequiredfamily or validation
notestr | NoneOptionalFree text

encounter is a foreign key to emr.Encounter with on_delete=CASCADE and related_name="consents". An encounter reaches its consents through consents.

A consent has no patient field. The patient is reached through encounter, and the list is filtered by the encounter's patient.

The read schemas also read FileUpload records (files) and User records (verifiers) when they serialize a consent.

Resource specs (API schema)​

The four consent schemas extend EMRResource through ConsentBaseSpec. ConsentVerificationSpec is a plain Pydantic BaseModel, not an EMRResource.

serialize copies each non-foreign-key model field that is also a spec field and not in __exclude__. Then it runs perform_extra_serialization.

de_serialize dumps the spec with exclude_defaults=True. It assigns each dumped model field except id, external_id and the __exclude__ fields.

Spec classRoleExposes / behaviour
ConsentBaseSpecshared baseid (UUID4 | None), status, category, date, period (PeriodSpec), encounter (UUID4), decision, note (str | None). __model__ = Consent, __exclude__ = ["encounter"]
ConsentCreateSpecwrite · createBase fields. Required: status, category, date, encounter, decision. Optional: id, note. period: send it on create; without it the create fails with HTTP 500, while {} is accepted. Rejects a period.start before date. Sets the model's encounter from its external_id
ConsentUpdateSpecwrite · updateExtends ConsentBaseSpec, not ConsentCreateSpec. status, category, date, period, encounter, decision and note are all optional. No period-versus-date check
ConsentListSpecread · listBase fields plus source_attachments: list[dict] and verification_details: list[dict]
ConsentRetrieveSpecread · detailIdentical to ConsentListSpec
ConsentVerificationSpecwrite · add_verification bodyPlain BaseModel. See the shape

Validation​

  • Create only: a period.start earlier than date fails with "Start of the period cannot be before than the Consent date".
  • Any period in a request: PeriodSpec requires a timezone on start and end, and refuses a start after end.
  • Enums: status, category and decision accept only their enum values. On update, they can be left out.
  • Create and update (viewset): the encounter must belong to the patient in the URL. See Authorization checks.
  • Update: there is no period-versus-date check. A field sent as null or left out keeps its stored value.

Server-maintained behaviour​

  • Encounter on create: ConsentCreateSpec.perform_extra_deserialization sets the model's encounter from the external_id in the body.
  • Encounter on update: the encounter cannot change. The viewset removes encounter from the update body, and __exclude__ keeps the generic field copy away from it.
  • Update hook: ConsentUpdateSpec.perform_extra_deserialization assigns the stored encounter to the spec attribute self.encounter, not to the model.
  • Verifications: add_verification sets verified_by and verification_date on the server. See Verification actions.
  • Files (read): source_attachments lists every FileUpload whose associating_id is the consent's external_id, with file_category consent_attachment and file_type consent.
  • File states (read): source_attachments includes archived files and files whose upload was never marked complete.
  • Verifier details (read): each verified_by in verification_details becomes the verifying user's UserSpec.
  • Identifiers (read): id is the consent's external_id, and encounter is the encounter's external_id.
  • No audit fields (read): the read schemas have no created_date, modified_date, created_by or updated_by.

Methods & save behaviour​

  • Consent overrides neither save() nor delete(), and no signal handler is attached to it.
  • Delete is a soft delete. The viewset sets deleted = True, keeps the row, and returns 204.
  • The default manager hides deleted rows, so a deleted consent no longer appears in any list or lookup.
  • status is a plain field. No consent code reacts to its value, so a consent with status entered_in_error stays in lists and can still be updated.

API integration notes​

  • The base path is /api/v1/patient/{patient_external_id}/consent/. Every request needs a signed-in user.
  • encounter in a body, and the encounter list filter, take the encounter's external_id, not its numeric id.
  • Validation errors return HTTP 400 with an errors list. Each item has type set to validation_error and a msg.
  • The update endpoint accepts changes to category, decision, date and period. The app's edit form resends the stored values, so it changes only status and note.
  • The app always sends period, with start and end each set to a date-time or null.
  • The app calls only list, retrieve, create and update. No screen calls delete, upsert, add_verification or remove_verification.
  • The app defines a remove-verification call that sends verification_id, but the server reads verified_by. No screen uses that call.

Authorization checks​

The roles listed hold each permission by default. The permission definitions also name an Admin role. Roles are matched by name, and the only role named Admin in the database is for role organizations, which the facility screens do not offer. The table below leaves it out.

CheckPasses whenDefault roles
Read check, patient branchThe user holds "Can view clinical data about patients" on the patient. The role can come from a facility organization of an encounter of the patient that is not closed, or of that encounter's current location. It can also come from one of the patient's organizations, or a direct link to the patientStaff, Doctor, Nurse, Facility Admin
Read check, encounter branchOnly when the patient branch fails and the request has ?encounter= with an encounter external_id. The user holds "Can Read encounter related clinical data" in that encounter's organizations or its current location's organizations. The encounter status does not matter. Else the request fails with "Permission denied to user"Doctor, Nurse, Facility Admin
Write checkThe encounter is not closed, and the user holds "Update Encounter related clinical data" in the encounter's organizations or its current location's organizations. Else the request fails with "You do not have permission to update encounter"Doctor, Nurse, Facility Admin
Patient matchOn create and update, the encounter exists and belongs to the patient in the URL. Else the request fails with "Patient external ID mismatch with encounter's patient". An unknown encounter on create gives 404Not a permission

An encounter's organizations are its assigned organizations, their parent organizations, and the facility's root organization, "Administration". A role in "Administration" applies to every encounter of the facility.

A location's organizations include those of its parent location, its own organizations with their parents, and "Administration".

A closed encounter has the status Completed, Cancelled, Discontinued or Entered in error. The write check refuses every change to the consents of a closed encounter.

The closed-encounter rule does not refuse writes on encounters with the status Planned, In Progress, On Hold, Discharged or Unknown.

A closed encounter's facility organizations no longer count for the patient branch of the read check. The encounter branch does not depend on the encounter status.

Endpoints​

Paths are relative to /api/v1/patient/{patient_external_id}. In each path, {id} is the consent's external_id.

ActionMethod and pathPermission pathNotes
listGET /consent/Read checkOne filter, encounter. No search and no ordering parameter. Newest first. Limit and offset, 14 per page by default, 200 at most. Without encounter, it returns the consents of every encounter of the patient
retrieveGET /consent/{id}/Read check, through get_object. No retrieve-specific checkSame shape as a list item
createPOST /consent/Patient match on the body's encounter, then write check on that encounter. No read checkBody: ConsentCreateSpec
update / partial_updatePUT or PATCH /consent/{id}/Read check, through get_object. Then patient match, then write check on the consent's encounterBody: ConsentUpdateSpec. PUT and PATCH take the same path. The viewset removes id, external_id, patient and encounter from the body
destroyDELETE /consent/{id}/Read check, through get_object. Then write check on the consent's encounterSoft delete. Returns 204
upsertPOST /consent/upsert/Per item. An item without id takes the create path. An item with id is loaded without the read check, then patient match and write check runBody: a datapoints list. An empty list fails with "No datapoints provided". More than MAX_DATAPOINTS_PER_UPSERT (100 by default) fails with "Too many datapoints provided"
add_verificationPOST /consent/{id}/add_verification/Read check, through get_object. Then write check on the consent's encounterBody: ConsentVerificationSpec. See Verification actions
remove_verificationPOST /consent/{id}/remove_verification/Read check, through get_object. Then write check on the consent's encounterBody: optional verified_by (a user UUID). See Verification actions

Verification actions​

  • add_verification appends one entry to verification_details. The server sets verified_by to the requesting user and verification_date to the current time, and ignores values sent for them.
  • Each user can verify a consent once. A second attempt by the same user fails with "Consent is already verified by the user". Other users can each add their own entry.
  • The entry is stored whatever the value of verified, so an entry with verified set to false is stored too. The request also sets updated_by to the requesting user.
  • remove_verification without verified_by removes the requesting user's entry. With verified_by, it removes that user's entry, so any user who passes the write check can remove another user's verification.
  • If no entry matches, remove_verification fails with "Consent is not verified by the user".

Files​

  • A consent's files go through the files API, /api/v1/files/, with file_type consent, file_category consent_attachment and associating_id set to the consent's id.
  • Reading a consent file needs the patient-level or the encounter-level read permission, with no encounter parameter. Writing needs the write check, including the closed-encounter rule.
  • A refused file read or write fails with "Cannot View File".
  • The files API has no delete. A file can be archived with an archive_reason.
  • The files API list returns only files whose upload is complete. The consent's own source_attachments also lists incomplete and archived files.
  • A periodic task hard-deletes file records whose upload was never marked complete, after FILE_UPLOAD_EXPIRY_HOURS (24 by default; 0 turns it off).
  • The one-shot base64 endpoint POST /api/v1/files/upload-file/ limits a file to MAX_FILE_UPLOAD_SIZE megabytes (5 by default). The signed-URL flow that the app uses does not apply this limit.
  • A completed, non-archived consent file can be attached to a referral of the same patient.
  • The app accepts jpg, jpeg, png and pdf files for a consent.
  • For the files API itself, see the File upload reference.