Lab Approval Consistency: A Robust Workflow in Documedic
In a clinical decision support system (CDSS) built on NestJS, React, PostgreSQL and OpenRouter, the lab approval chain is a critical touchpoint. Clinicians must approve or correct lab results before they influence patient care plans, and any duplication or accidental re‑approval can propagate errors through the entire medical record.
The Problem
When a lab result is ingested, the system stores a single record that contains the patient identifier, the time the blood was drawn, the test type and the numeric result. In practice, laboratories sometimes submit the same sample twice or a clinician may click the Approve button multiple times. Two scenarios emerge:
- Duplicate blood draws – The same sample, drawn at the same time, is entered twice. If both entries are approved, the patient’s chart now shows two identical results, which can skew trend analysis and 탈…
- Repeating approvals – A clinician may inadvertently re‑approve a lab report that has already been approved. The current implementation would duplicate every result inside the report, effectively doubling the count of each test and inflating billing.
Both problems were addressed in the recent 13‑commit cycle. The backend now refuses a duplicate blood draw and prevents re‑approving a lab report from multiplying its contents.
How the Feature Works
1. Duplicate Blood Draw Check
The LabResultService performs a lightweight query before persisting any new lab entry. The check is wrapped in a transaction to avoid race conditions.
// src/lab-result/lab-result.service.ts
async createLabResult(dto: CreateLabResultDto): Promise<LabResult> {
const { patientId, bloodDrawTime } = dto;
const exists = await this.prisma.labResult.findFirst({
where: { patientId, bloodDrawTime },
});
if (exists) {
throw new BadRequestException('Duplicate blood draw detected');
}
return this.prisma.labResult.create({ data: dto });
}
The PostgreSQL schema enforces a compound unique constraint on (patient_id, blood_draw_time) to guarantee that the database itself will reject any duplicate attempts.
2. Idempotent Approval Logic
The approval endpoint is guarded by a service that checks whether the report has already been approved by the same clinician. The key is a unique index on (lab_report_id, clinician_id, approved_at).
// src/approval/approval.service.ts
async approveReport(dto: ApproveReportDto) {
const { reportId, clinicianId } = dto;
const alreadyApproved = await this.prisma.approval.findFirst({
where: { labReportId: reportId, clinicianId },
});
if (alreadyApproved) {
throw new ConflictException('Report already approved');
}
const approval = await this.prisma.approval.create({
data: { labReportId: reportId, clinicianId, approvedAt: new Date() },
});
await this.auditLog(approval);
return approval;
}
The audit log is a separate table that records the approval action. A lond‑running commit, test(api): pin the ban on clinician free text in the audit payload, ensures that the audit payload remains deterministic by stripping any free‑text fields that could unintentionally alter the hash.
3. AI‑Driven Decision Support
Once a lab report is approved, the system forwards the result set to OpenRouter for inference. The request is small, containing only the patient ID, the list of test codes and values. The AI returns a recommendation flag that the UI can surface.
// src/ai/ai.service.ts
async evaluateLabResults(patientId: string, results: LabResultDto[]) {
const prompt = `Patient ${patientId} has the following labs: ${results
.map(r => `${r.code}: ${r.value}`)
.join(', ')}. Provide a risk assessment.`;
return this.openRouter.client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: prompt }],
});
}
The AI output is cached per patient to avoid repeated calls for the same data set, a change reflected in the perf(api) commit that stopped reading the entire guideline corpus on every request.
4. Frontend Interaction
On the React side, a clinician opens a lab report card that lists the tests. The Approve button triggers a POST to /api/approvals.
// src/components/LabReportCard.tsx
const handleApprove = async () => {
setLoading(true);
try {
await fetch('/api/approvals', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reportId, clinicianId }),
});
refreshReport();
} finally {
setLoading(false);
}
};
The UI disables the button if the report is already approved, using the approved flag returned from the API. Error handling displays a concise message such as Duplicate blood draw detected or Report already approved,هة.
What It Looks Like For a Clinician
- Navigate to the patient’s chart and open the lab report section.
- Review the list of tests; the AI‑generated risk assessment appears beneath the table.
- Click Approve. If the report has never been approved, the button becomes disabled and the audit log is updated.
- Repeat: If the clinician clicks Approve again, the system responds with Report already approved, preventing a duplicate entry.
The result is a clean, auditable record that cannot be contaminated by accidental re‑approvals or duplicate lab draws.
Maintaining Consistency Across Patients
The commit test(api): drive decision support off an ingested chart, several patients at once demonstrates that the API can handle parallel approvals for multiple patients. Internally, each approval is routed through a separate transaction, ensuring isolation.
Moreover, the system’s design allows for horizontal scaling: the NestJS layer can run behind a load balancer, while PostgreSQL leverages read replicas for audit queries. The AI inference layer (OpenRouter) can be rate‑limited per client to prevent bursts.
Summary
By tightening the data model, enforcing unique constraints, and providing clear API feedback, Documedic’s lab approval feature resolves two of the most common sources of data duplication in clinical decision support. The result is a more reliable CDSS that safeguards patient safety and streamlines clinician workflows.
Top comments (0)