Skip to content

Document Linking

CreateCareContextDTO

Bases: BaseModel

Request DTO for creating a care context.

Attributes:

Name Type Description
patient_reference str

Unique reference for the patient.

patient_abha_address Optional[str]

Patient's ABHA address, if available.

practitioner_reference str

Unique reference for the practitioner.

appointment_reference str

Unique reference for the appointment.

hi_type HealthInformationTypes

Type of health information being linked.

appointment_date str

Date of the appointment (ISO format).

resend_otp bool

Whether to resend the OTP for authentication.

Example Usage
dto = CreateCareContextDTO(
    patientReference="pat-123",
    practitionerReference="prac-456",
    appointmentReference="appt-789",
    hiType=HealthInformationTypes.OPConsultation,
    appointmentDate="2024-07-30",
    resendOtp=False
)

UpdateVisitRecordsDTO

Bases: BaseModel

Data Transfer Object (DTO) for updating visit records.

Attributes:

Name Type Description
care_context_reference str

Unique reference for the care context.

patient_reference str

Unique reference for the patient.

practitioner_reference str

Unique reference for the practitioner.

appointment_reference str

Unique reference for the appointment.

patient_abha_address Optional[str]

Patient's ABHA address, if available.

health_records list[HealthInformationDTO]

List of health records to be updated.

mobile_number Optional[str]

Patient's mobile number.

request_id Optional[str]

Unique request identifier for the update operation.

Validation
  • All required fields should not be empty.
  • health_records list must not be empty.
  • If provided, mobile_number must not contain '*' characters.

Bases: BaseModel

Data Transfer Object (DTO) for linking a care context to a patient and appointment.

Attributes:

Name Type Description
request_id str

Unique request identifier for the linking operation.

appointment_reference str

Unique reference for the appointment.

patient_address str

Address of the patient.

patient_name str

Name of the patient.

patient_reference str

Unique reference for the patient.

care_context_reference str

Unique reference for the care context.

auth_mode AuthMode

Authentication mode used for linking.

Validation
  • All fields should not be empty.
  • auth_mode must be a valid AuthMode value.

HealthDocumentLinkingDTO

Bases: BaseModel

Request DTO for linking health documents to a care context or appointment.

Attributes:

Name Type Description
patient_reference str

Unique reference for the patient.

practitioner_reference str

Unique reference for the practitioner.

patient_address str

Address of the patient.

patient_name str

Name of the patient.

appointment_start_date str

Start date/time of the appointment (ISO format).

appointment_end_date str

End date/time of the appointment (ISO format).

appointment_priority Optional[AppointmentPriority]

Priority of the appointment.

organization_id str

Unique identifier for the organization.

appointment_slot Optional[str]

Slot information for the appointment.

reference Optional[str]

Optional reference string.

patient_abha_address Optional[str]

Patient's ABHA address, if available.

hi_type HealthInformationTypes

Type of health information being linked.

mobile_number str

Patient's mobile number.

health_records list[HealthInformationDTO]

List of health records to be linked.

Example
dto = HealthDocumentLinkingDTO(
    patientReference="pat-123",
    practitionerReference="prac-456",
    patientAddress="123 Main St",
    patientName="John Doe",
    appointmentStartDate="2024-07-30T09:00:00",
    appointmentEndDate="2024-07-30T09:30:00",
    appointmentPriority=AppointmentPriority.ROUTINE,
    organizationId="org-789",
    appointmentSlot="slot-001",
    reference="ref-001",
    patientAbhaAddress="john@abdm",
    hiType=HealthInformationTypes.OPConsultation,
    mobileNumber="+911234567890",
    healthRecords=[...]
)

HealthInformationDTO

Bases: BaseModel

Data Transfer Object (DTO) representing health information data for document linking.

Attributes:

Name Type Description
raw_fhir Optional[bool]

Indicates if the FHIR document is in raw format.

fhir_document dict[str, Any]

The FHIR document data.

information_type HealthInformationTypes

The type of health information (e.g., OPConsultation, DischargeSummary).

Validation
  • If raw_fhir is True, fhir_document must be provided.
  • information_type must not be empty.

DocumentLinking

DocumentLinking(config: ClientConfig)

Bases: BaseService

Service responsible for linking health documents through a multi-step process.

This service manages the workflow for associating health records, care contexts, and visit records with a patient, ensuring data validation, serialization, and robust error handling throughout the process.

Key Features

  • Validates and serializes DTOs for document linking operations.
  • Handles creation of care contexts, updating visit records, and linking care contexts.
  • Maintains transaction state for traceability and error reporting.
  • Provides detailed logging and error messages for each step.

Methods:

Name Description
create_care_context

Maps and validates care context data.

send_care_context_request

Sends care context creation request to the API.

update_visit_records

Updates visit records with consultation data.

link_care_context

Links the care context to the health document.

link_health_document

Orchestrates the complete document linking process.

Parameters:

Name Type Description Default
config ClientConfig

API credentials and settings for service initialization.

required

Raises:

Type Description
EhrApiError

For validation, API, or unexpected errors during operations.

Example Usage
config = ClientConfig(
    api_key="your_api_key",
)
service = DocumentLinking(config)

health_document_linking_dto = HealthDocumentLinkingDTO(
    patientReference="pat-123",
    practitionerReference="prac-456",
    appointmentReference="appt-789",
    patientAddress="123 Main St",
    patientName="John Doe",
    appointmentStartDate="2024-07-30T09:00:00",
    appointmentEndDate="2024-07-30T10:00:00",
    appointmentPriority=AppointmentPriority.ROUTINE,
    appointmentType=AppointmentType.VISIT,
    organizationId="org-789",
    appointmentSlot="slot-001",
    reference="ref-001",
    mobileNumber="1234567890",
    healthRecords=[HealthInformationDTO(
        rawFhir=True,
        fhirDocument={"key": "value"},
        informationType=HealthInformationTypes.OPConsultation
    )]
)
await service.link_health_document(health_document_linking_dto)

create_care_context async

create_care_context(health_document_linking_dto: HealthDocumentLinkingDTO) -> CreateCareContextDTO

Creates care context data from the provided health document linking information.

This method maps the incoming HealthDocumentLinkingDTO into a CreateCareContextDTO, then validates the mapped DTO before returning it for further processing.

Parameters:

Name Type Description Default
health_document_linking_dto HealthDocumentLinkingDTO

DTO containing health document linking data, including patient/practitioner references, appointment dates, priority, organization, mobile number, and health records.

required

Returns:

Name Type Description
CreateCareContextDTO CreateCareContextDTO

A new DTO representing the care context ready to be sent to the API.

Raises:

Type Description
ValueError

If the input data is None or not a HealthDocumentLinkingDTO instance, or if validation fails.

Example
linking_dto = HealthDocumentLinkingDTO(
    patientReference="123e4567-e89b-12d3-a456-426614174000",
    practitionerReference="321e4567-e89b-12d3-a456-426614174000",
    patientAddress="123 Elm St",
    patientName="John Doe",
    appointmentStartDate="2025-08-01T09:00:00Z",
    appointmentEndDate="2025-08-01T09:30:00Z",
    appointmentPriority="ROUTINE",
    organizationId="Org123",
    mobileNumber="9876543210",
    hiType="OPConsultation",
    healthRecords=[rawFhir=True, fhirDocument={"key": "value"}, informationType=HealthInformationTypes.OPConsultation]
)
care_context_dto = await service._create_care_context(linking_dto)
print(care_context_dto)
Response:
The returned `CreateCareContextDTO` instance, validated and ready for API use.
{
    "patientReference": "123e4567-e89b-12d3-a456-426614174000",
    "practitionerReference": "321e4567-e89b-12d3-a456-426614174000",
    "appointmentReference": "appt-123",
    "appointmentDate": "2025-08-01T09:00:00Z",
    "resendOtp": false,
    "hiType": "OPConsultation"
}

send_care_context_request async

send_care_context_request(care_context_data: CreateCareContextDTO) -> CreateCareContextResponse

Sends the care context creation request to the backend API.

Serializes the care context DTO to a dictionary, sends it to the specified endpoint, and parses the response into CreateCareContextResponse.

Parameters:

Name Type Description Default
care_context_data CreateCareContextDTO

Validated care context data to transmit.

required

Returns:

Name Type Description
CreateCareContextResponse CreateCareContextResponse

API response containing care context reference, request ID, and status.

Example
response = await service._send_care_context_request(care_context_dto)
print(response.care_context_reference, response.request_id)
Response:
Sample Output:
{
    "careContextReference": "cc-12345",
    "requestId": "req-12345",
    "authModes": ["DEMOGRAPHICS", "MOBILE_OTP"]
}

update_visit_records async

update_visit_records(health_document_linking_dto: HealthDocumentLinkingDTO, care_context_response: CreateCareContextResponse) -> UpdateVisitRecordsResponse

Updates visit records with the consultation data mapped from health document linking information.

This method maps the DTO into UpdateVisitRecordsDTO, validates it, serializes it, and calls the update visit records API endpoint.

Parameters:

Name Type Description Default
health_document_linking_dto HealthDocumentLinkingDTO

Input data containing health document details.

required
care_context_response CreateCareContextResponse

Response from care context creation to extract references.

required
Returns:
UpdateVisitRecordsResponse: API response indicating success or failure of the visit record update.
Example
update_response = await service._update_visit_records(
    linking_dto, care_context_response
)
print(update_response.success)
Response:
Sample Output:
{
    "success": True,
}
link_care_context(health_document_linking_dto: HealthDocumentLinkingDTO, care_context_response: dict[str, Any]) -> bool

Links the care context with the existing health document.

This performs the linkage by mapping to a LinkCareContextDTO, validating, and invoking the API. Returns True if linkage was successful.

Parameters:

Name Type Description Default
health_document_linking_dto HealthDocumentLinkingDTO

DTO with document linking info.

required
care_context_response dict[str, Any]

Response containing careContextReference and requestId.

required

Returns:

Name Type Description
bool bool

True if link operation succeeded, False otherwise.

Raises:

Type Description
ValueError

If required fields are missing or invalid in the DTO.

EhrApiError

If the API call fails or returns an error status.

Example
success = await service._link_care_context(
    linking_dto, care_context_resp.model_dump()
)
print("Link success:", success)
True  # Indicates linking succeeded
False  # Indicates linking failed, possibly due to missing care context reference or request ID.
link_health_document(health_document_linking_dto: HealthDocumentLinkingDTO) -> bool
Executes the complete health document linking workflow in three key steps
  1. Creation of a care context in the system using the provided healthcare document details.
  2. Updating visit records if health records exist within the provided DTO.
  3. Linking the care context with the existing health document to finalize the association.

This method orchestrates the entire transaction, ensuring validation of all input data, managing intermediate responses, maintaining transactional state, logging progress comprehensively, and raising detailed exceptions on failures.

Parameters:

Name Type Description Default
health_document_linking_dto HealthDocumentLinkingDTO

A fully populated DTO containing all necessary patient, practitioner, appointment, and health information required for the linking operation. This includes references, appointment timings, priority, mobile number, health records, and document type.

required

Returns:

Name Type Description
bool bool

Returns True if all steps succeed and the health document is fully linked. Returns False or raises exceptions if any step fails.

Raises:

Type Description
ValueError

Raised when the input data or any intermediate DTO fails validation checks.

EhrApiError

Raised when any interaction with the backend API returns a failure status. The error message includes a detailed transaction state snapshot for easier debugging.

Exception

Raised for any unexpected errors that occur during processing. Wrapped in EhrApiError with status code 500 and transaction state details.

Workflow Steps Overview
  • Validation of the top-level HealthDocumentLinkingDTO.
  • Mapping and validation of CreateCareContextDTO derived from input.
  • Sending create care context request and storing references.
  • Conditional updating of visit records if health records provided.
  • Linking care context to the health document.
  • Updating and logging transaction state throughout.
Example
# Prepare a DTO with all necessary fields filled
linking_dto = HealthDocumentLinkingDTO(
    patientReference="123e4567-e89b-12d3-a456-426614174000",
    practitionerReference="321e4567-e89b-12d3-a456-426614174000",
    patientAddress="123 Cedar Street",
    patientName="Jane Doe",
    appointmentStartDate="2025-08-15T14:00:00Z",
    appointmentEndDate="2025-08-15T14:30:00Z",
    appointmentPriority="ROUTINE",
    organizationId="Org987",
    mobileNumber="9998887776",
    hiType="OPConsultation",
    healthRecords=[rawFhir=True, fhirDocument={"key": "value"}, informationType=HealthInformationTypes.OPConsultation]
)
# Execute the linking process
success = await service._link_health_document(linking_dto)
print("Document linked successfully:", success)
Sample Response:
True  # Indicates the health document was successfully linked
False  # Indicates the linking process did not complete successfully, possibly due to missing health records or other issues.
False if no health records were provided, indicating no visit record update was needed.
- This method assumes the existence of mapping functions:
  `map_to_create_care_context_dto`, `map_to_consultation_dto`, and `map_to_link_care_context_dto`
  to transform data between DTOs.
- The `TransactionState` object tracks the stages completed and is included in exceptions for traceability.
- Logging at each step provides detailed insights in case of issues.

schema

format_appointment_date

format_appointment_date(start_date: str, end_date: str) -> str

Converts ISO-formatted appointment start and end datetime strings into a human-readable time range string in hh:mm am/pm - hh:mm am/pm format.

This function handles UTC ā€˜Z’ suffix by converting it to a timezone-aware datetime, then formats the times in 12-hour AM/PM notation in lowercase letters.

Parameters:

Name Type Description Default
start_date str

ISO 8601 formatted start datetime (e.g., "2025-07-30T09:30:00Z").

required
end_date str

ISO 8601 formatted end datetime (e.g., "2025-07-30T10:30:00Z").

required

Returns:

Name Type Description
str str

Formatted time range string, e.g., "09:30 am - 10:30 am".

Example
result = format_appointment_date("2025-07-30T09:30:00Z", "2025-07-30T10:45:00Z")
print(result)
Response:
Sample output for the given example:
"09:30 am - 10:45 am"

map_to_create_care_context_dto

map_to_create_care_context_dto(data: HealthDocumentLinkingDTO) -> CreateCareContextDTO

Transforms a HealthDocumentLinkingDTO instance into a CreateCareContextDTO instance, preparing the data for care context creation API calls.

The function derives a human-readable appointment date string by formatting the original start and end datetime fields, and maps corresponding fields between the DTOs. It sets resendOtp to False by default, assuming a new request.

Parameters:

Name Type Description Default
data HealthDocumentLinkingDTO

Source DTO containing raw health linking data including patient, practitioner info, appointment times, and more.

required

Returns:

Name Type Description
CreateCareContextDTO CreateCareContextDTO

The resulting DTO with mapped and formatted fields, ready for API submission.

Example
linking_dto = HealthDocumentLinkingDTO(
    patientReference="patient-uuid-123",
    practitionerReference="practitioner-uuid-456",
    patientAddress="123 Elm Street",
    patientName="John Doe",
    appointmentStartDate="2025-08-01T09:00:00Z",
    appointmentEndDate="2025-08-01T09:30:00Z",
    appointmentPriority="ROUTINE",
    organizationId="Org001",
    mobileNumber="9876543210",
    hiType="OPConsultation",
    healthRecords=[rawFhir=True, fhirDocument={"key": "value"}, informationType=HealthInformationTypes.OPConsultation],
    appointmentSlot="slot-001",
    reference="appt-123",
    patientAbhaAddress="john@abdm"
)
care_context_dto = map_to_create_care_context_dto(linking_dto)
print(care_context_dto.appointmentDate)  # Output: "09:00 am - 09:30 am"
Response:
A CreateCareContextDTO instance with the following fields:
- patientReference: "patient-uuid-123"
- patientAbhaAddress: "123 Elm Street"
- practitionerReference: "practitioner-uuid-456"
- appointmentReference: "appt-123"
- hiType: "OPConsultation"
- appointmentDate: "09:00 am - 09:30 am"
- resendOtp: False
- authMode: "DEMOGRAPHICS"

map_to_consultation_dto

map_to_consultation_dto(data: HealthDocumentLinkingDTO, care_context_reference: str, request_id: str) -> UpdateVisitRecordsDTO

Converts HealthDocumentLinkingDTO and associated care context identifiers into an UpdateVisitRecordsDTO for updating patient consultation and visit records.

This mapping associates the care context reference and request ID with the health document details, carrying forward health records and patient identification information.

Parameters:

Name Type Description Default
data HealthDocumentLinkingDTO

Source health document linking DTO.

required
care_context_reference str

The unique care context identifier received from care context creation.

required
request_id str

The request ID corresponding to the transaction.

required

Returns:

Name Type Description
UpdateVisitRecordsDTO UpdateVisitRecordsDTO

Mapped DTO ready to be used in visit records update API calls.

Example
consultation_dto = map_to_consultation_dto(linking_dto, "care-context-123", "req-456")
print(consultation_dto.careContextReference)  # Output: "care-context-123"
Response:
An UpdateVisitRecordsDTO instance with the following fields:
- careContextReference: "care-context-123"
- patientReference: "patient-uuid-123"
- practitionerReference: "practitioner-uuid-456"
- appointmentReference: "appt-123"
- patientAbhaAddress: "123 Elm Street"
- healthRecords: [rawFhir=True, fhirDocument={"key": "value"}, informationType=HealthInformationTypes.OPConsultation]
- mobileNumber: "9876543210"
- requestId: "req-456"
- appointmentDate: "hh:mm am/pm - hh:mm am/pm"
- authMode: "DEMOGRAPHICS"
- appointmentType: "Emergency"
- appointmentStatus: "scheduled"
map_to_link_care_context_dto(data: HealthDocumentLinkingDTO, care_context_reference: str, request_id: str) -> LinkCareContextDTO

Maps HealthDocumentLinkingDTO along with care context and request identifiers into a LinkCareContextDTO for linking care contexts to existing health documents.

Sets the authorization mode to AuthMode.DEMOGRAPHICS by default, indicating linkage is based on demographic authentication.

Parameters:

Name Type Description Default
data HealthDocumentLinkingDTO

Source health document linking DTO.

required
care_context_reference str

The care context reference to link.

required
request_id str

The unique transaction/request ID.

required

Returns:

Name Type Description
LinkCareContextDTO LinkCareContextDTO

The mapped DTO ready for care context linking API calls.

Example
link_care_context_dto = map_to_link_care_context_dto(linking_dto, "care-context-123", "req-456")
print(link_care_context_dto.authMode)  # Output: AuthMode.DEMOGRAPHICS
A LinkCareContextDTO instance with the following fields:
- requestId: "req-456"
- appointmentReference: "appt-123"
- patientAddress: "123 Elm Street"
- patientName: "John Doe"
- patientReference: "patient-uuid-123"
- careContextReference: "care-context-123"
- authMode: "DEMOGRAPHICS"