Backend
API contract, database changes, business logic orchestration, and integration points for the Reflex Management backend in crelio-app.
1. Prescription Reflex Metadata Initialization
The Prescription Reflex workflow is initialized during the billing process through the http POST billing/ API.
When Prescription Reflex is enabled during billing, the frontend automatically adds Prescription drugs into the confirmation component
Prescription Reflex Flow
User Adds Prescription Drugs
↓
Prescription Reflex Enabled
↓
Frontend Adds Prescription Drugs into Confirmation
↓
billing/ API Triggered
↓
prepare_and_save_meta()
↓
save_components()
↓
Confirmation Metadata StoredFrontend Payload Transformation
When:
- Prescription Reflex is enabled
- Prescription drugs are selected during billing
the frontend automatically injects those Prescription drugs into the confirmation component array before calling the billing API.
Example Payload
component_instances = {
"disableScreeningReflex": True,
"disablePrescriptionReflex": False
"screening": [{"id": 1}, {"id": 2}],
"confirmation": [{"id": 1}, {"id": 2}, {"id": 3}],
"prescription": [
{
"id": 1,
"label": "Ketamine"
},
{
"id": 2,
"label": "Diazepam"
}
],
}Important Logic
The key behavior is:
Prescription Drugs
↓
Automatically Added into Confirmation Array
↓
Sent Through Billing APIThis means the backend does not dynamically generate Prescription Reflex drugs.
Instead:
- The frontend prepares the final Confirmation payload
- The backend simply stores the provided component metadata
Relevant Billing Logic
component_instances = testList[itr].get("component_instances", {})
labReport.prepare_and_save_meta(
from_billing=True,
should_append_defaults=False,
component_instances=component_instances
)prepare_and_save_meta()
Purpose
prepare_and_save_meta() initializes Toxicology component metadata for the generated report.
Its responsibility is to:
- Read component_instances
- Normalize component structure
- Store Toxicology metadata
Main Responsibility in Prescription Reflex
For Prescription Reflex specifically:
prepare_and_save_meta()
↓
save_components()
↓
Store Confirmation ComponentThe most important step is:
save_components()because the frontend has already injected Prescription drugs into the Confirmation component.
save_components()
Purpose
save_components() is responsible for persisting component-level Toxicology metadata against the generated report.
It stores:
- Screening drugs
- Confirmation drugs
- Prescription drugs
inside report metadata.
Why save_components() Is Important
For Prescription Reflex:
- Prescription drugs are already added into Confirmation by the frontend
save_components()persists this transformed Confirmation structure
Without this function:
- Prescription Reflex additions would not be saved
- Confirmation workflows would lose billing-selected drugs
save_components() Workflow
Receive component_instances
↓
Read confirmation component
↓
Persist confirmation drugs
↓
Store report metadataBackend Responsibility
The backend does not:
- Calculate Prescription Reflex mappings
- Inject Prescription drugs dynamically
Instead, it:
- Accepts transformed component payload
- Persists it into Toxicology metadata
Important Notes
- Prescription Reflex is primarily frontend-driven
- Prescription drugs are automatically injected into Confirmation before billing
- Backend only persists the transformed component structure
prepare_and_save_meta()initializes Toxicology metadatasave_components()stores Confirmation component metadata- Confirmation metadata becomes the source of truth for future workflows
Screening Reflex Processing From Device Data
The Screening Reflex workflow is triggered when a Toxicology device sends screening results through the: http POST dataPartialFromToxDevice/ API.
When a screening drug result exceeds its configured cutoff value, the system automatically adds its configured Reflex drugs into the Confirmation Component
Example Workflow
Consider the following configuration:
| Primary Drug | Reflex Drugs | Cutoff |
|---|---|---|
| Ketamine | Noroxycodone, Naltrexone | 50 |
Workflow
Ketamine Added to Screening
↓
Device Sends Ketamine Result
↓
System Checks Cutoff
↓
Result > 50
↓
Fetch Reflex Drugs
↓
Add Reflex Drugs to ConfirmationAPI Endpoint
POST dataPartialFromToxDevice/API View Class
class GetToxDataForPending(APIView):Example Device Payload
The Toxicology device sends screening results using the following payload structure.
{
"labId": 9,
"sampleId": "000212626",
"deviceAuth": "8db30815-c319-48c6-9f7a-d1d1c6272001",
"data": {
"values": [
{
"testName": "Ketamine",
"value": 110.99
},
{
"testName": "Diazepam",
"value": 17.99
}
]
}
}Payload Fields
| Field | Purpose |
|---|---|
labId | Lab identifier |
sampleId | Sample ID for the billed report |
deviceAuth | Device authentication token |
data.values | Drug result values sent by the device |
values Array
The values array contains all drug results received from the device.
Each object represents:
- Drug code mapped to device
- Device result value
Drug Result Structure
{
"testName": "Ketamine",
"value": 110.99
}Device Mapping
The API maps testName to configured Toxicology drugs using DeviceDrugs mapping.
Example:
| Device Value | Mapped Drug |
|---|---|
| Ketamine | Ketamine |
| Diazepam | Diazepam |
Screening Reflex Configuration
The Screening Reflex setting is stored inside the Confirmation Component Meta using the key screening_reflex_enabled
Example Meta
{
"screening_reflex_enabled": 1
}Loading Screening Reflex Configuration
Relevant Code
if current_component == 'screening':
report_format_conf_obj = report_format_obj.filter(
component_type='confirmation'
)
if report_format_conf_obj.exists():
conf_report_meta = json.loads(
report_format_conf_obj[0].meta or '{}'
)
screening_reflex_enabled = conf_report_meta.get(
'screening_reflex_enabled',
0
)
conf_column_refs = [
column["column_ref"]
for column in conf_report_meta.get("columns", [])
]Purpose
This block:
- Loads the Confirmation component
- Reads Confirmation metadata
- Checks whether Screening Reflex is enabled
- Loads Confirmation column configuration
Processing Device Results
After the device sends data, the API processes each screening drug result individually.
Building Device Result Object
Relevant Code
curr_val['is_positive'] = int(
parse_float(curr_val.get('result_1'))
>=
parse_float(curr_val.get('cut_off'))
)Purpose
The API compares:
- Device result
- Drug cutoff value
to determine whether the drug is positive.
Example Result Evaluation
| Drug | Device Result | Cutoff | Positive |
|---|---|---|---|
| Ketamine | 110.99 | 50 | Yes |
| Diazepam | 17.99 | 25 | No |
Billing-Time Reflex Override
The API also checks whether Screening Reflex was disabled during billing.
Relevant Code
reflex_test_details = ReflexTestDetails.objects.filter(
lab_report_id=lab_report_relation_obj.labReportId
).values("extra_data").first()
extra_data = json.loads(
reflex_test_details.get("extra_data") or "{}"
if reflex_test_details else "{}"
)
disable_screening_reflex = extra_data.get(
"disableScreeningReflex",
False
)Purpose
This reads billing-time reflex preferences stored through:
store_drug_reflex_status()If the user disabled Screening Reflex during billing:
- Reflex drugs will not be added
- Even if cutoff conditions are satisfied
Screening Reflex Trigger Logic
Relevant Code
if (
screening_reflex_enabled
and curr_val.get('result_1') > curr_val.get('cut_off')
and not disable_screening_reflex
):Conditions Required
Screening Reflex executes only when:
| Condition | Required |
|---|---|
| Screening Reflex enabled | Yes |
| Result exceeds cutoff | Yes |
| Billing-time reflex not disabled | Yes |
Fetching Reflex Drugs
Relevant Code
related_drugs = RelatedDrugs.objects.filter(
lab_id=data_json.get("labId"),
primary_drug_id=curr_val.get("id"),
relationship="Reflex"
)Purpose
This fetches all Reflex drugs configured for the positive screening drug.
Example:
| Primary Drug | Reflex Drug |
|---|---|
| Ketamine | Noroxycodone |
| Ketamine | Naltrexone |
Building Confirmation Drugs
Relevant Code
conf_val.update({
"is_reflex": 1,
"value": conf_val.get('id'),
"id": model_to_dict(
related_drug.related_drug
).get('id')
})Purpose
The API transforms each Reflex drug into a Confirmation-compatible structure.
The generated object is later inserted into:
- Confirmation metadata
- Report values
Reflex Drug Metadata
Each inserted Reflex drug is marked using:
"is_reflex": 1This helps identify:
- Auto-added Reflex drugs
- Manually added Confirmation drugs
Updating Confirmation Component
Relevant Code
report_value = ReportValue.get_values(
index=report_format_conf_obj.first().index,
reportForId_id=lab_report_id
)Purpose
The API loads the existing Confirmation component values for the report.
This allows:
- Preventing duplicates
- Merging Reflex drugs safely
Duplicate Prevention
Relevant Code
existing_drugs = [
element['id']
for element in report_value[0]['value']
]Purpose
Before inserting Reflex drugs:
- Existing Confirmation drugs are checked
- Duplicate Reflex insertion is prevented
Final Confirmation Merge
Relevant Code
if conf_element['id'] not in existing_drugs:
final_conf_array.append(conf_element)Purpose
Only new Reflex drugs are inserted into Confirmation.
Existing drugs remain unchanged.
Saving Confirmation Values
Relevant Code
labReportObj.add_report_values([report_value_array])Purpose
The updated Confirmation component is saved back into the report metadata.
This finalizes the Screening Reflex workflow.
Complete Screening Reflex Flow
Device Sends Screening Result
↓
Check Screening Reflex Enabled
↓
Validate Result > Cutoff
↓
Check Billing-Time Reflex Override
↓
Fetch Reflex Drugs
↓
Build Confirmation Drug Objects
↓
Prevent Duplicate Entries
↓
Update Confirmation ComponentImportant Notes
- Screening Reflex is completely device-driven
- Reflex processing only works for Screening components
- Reflex enablement is controlled from Confirmation component meta
- Reflex drugs are fetched from
RelatedDrugs - Billing-time reflex overrides are respected
- Duplicate Confirmation drugs are automatically prevented
- Reflex drugs are inserted directly into Confirmation report values
- Added Reflex drugs are marked using
is_reflex = 1