The Elo Cloud family
One system
A hospital isn't five systems — EloHIMS runs all of it.

One patient, one MRN, one built-in ledger, one live command centre — from the registration counter to the operating theatre.

Why EloHIMS
Guide

Building an Accounting-First HIMS: Why Hospital Software Needs a Real General Ledger

BBy the IT Vision team — builders of EloHIMS, a cloud HIMS for hospitals in Pakistan. Learn more at elohims.net.··5 min read

How we integrated double-entry accounting and ISO 15189 LIMS into a unified hospital management system without the reconciliation nightmare

1. Introduction: The Reconciliation Nightmare

If you've ever worked with healthcare software, you've probably seen this pattern: a hospital runs three separate systems—one for patient billing, one for accounting, and one for lab operations. At the end of each month, someone manually reconciles these systems by exporting spreadsheets, comparing numbers, and hunting down discrepancies.

This approach creates data silos, timing mismatches, and manual entry errors. Revenue gets recorded in billing but doesn't flow into the general ledger until days later. Lab test costs hit accounting at the wrong time. Insurance claims create receivables that accountants can't track. The finance team spends days chasing down a balanced P&L.

Most hospital management systems treat accounting as an afterthought—something you bolt on through an integration with QuickBooks or a similar external tool. The problem with this approach is that it fundamentally misunderstands how healthcare finance works. Healthcare transactions are complex: mixed cash and credit payments, partial payments, pharmacy cost-of-goods-sold calculations, insurance claims with delayed collection, and multi-branch consolidation.

When we built EloHIMS, we made a different architectural choice: build the general ledger first, then layer the clinical workflows on top of it. Every charge, every payment, every inventory movement posts to a double-entry ledger in real time. There's no month-end reconciliation because there's nothing to reconcile—the books are always balanced.

In this article, I'll walk through the technical challenges of building an accounting-first hospital information management system (HIMS) and how we integrated double-entry accounting with ISO 15189-compliant laboratory workflows without creating a reconciliation nightmare.

2. The Double-Entry Challenge

What Double-Entry Means (and Why It's Hard in Healthcare)

Double-entry accounting is a principle that dates back to 15th-century Venice: every financial transaction affects at least two accounts, with one debit and one credit, and the sum of all debits always equals the sum of all credits. It's the foundation of modern accounting because it makes the books self-balancing and detects errors automatically.

Here's a simple example: when a patient pays ₨1,000 for a consultation, you debit Cash (asset increases by ₨1,000) and credit Consultation Revenue (income increases by ₨1,000). The books stay balanced.

But healthcare workflows make this harder:

Most hospital software sidesteps this complexity by recording charges in a billing module and leaving accounting to a separate system. But that creates the reconciliation problem: the billing system knows what was charged, the accounting system knows what was paid, and no single source of truth exists.

Our Approach: Event-Driven Accounting Posts

We solved this by making every clinical and operational event generate accounting entries automatically. Here's how it works:

Every charge generates a journal entry: - OPD consultation: Debit Accounts Receivable (or Cash, if paid immediately), Credit Consultation Revenue - Lab test: Debit Accounts Receivable, Credit Lab Revenue - Pharmacy sale: Debit Accounts Receivable (or Cash), Credit Pharmacy Revenue; simultaneously post COGS (Debit Cost of Goods Sold, Credit Inventory) - Bed charge (IPD): Daily automated posting—Debit Accounts Receivable, Credit Room Revenue

Payments reduce receivables: - Cash payment: Debit Cash, Credit Accounts Receivable - Insurance payment: Debit Bank, Credit Accounts Receivable (Insurance Panel)

Refunds and discounts: - Refund: Debit Revenue (reversal), Credit Cash - Discount: Debit Revenue, Credit Accounts Receivable

Pharmacy COGS automation: Pharmacy is one of the trickiest parts. When a pharmacist dispenses a drug, the system needs to post the cost-of-goods-sold (COGS) from the correct purchase batch. We use FEFO (first-expiry-first-out) logic: the system automatically selects units from the batch expiring soonest, retrieves the purchase cost from that batch, and posts: - Debit: Cost of Goods Sold (expense account) - Credit: Inventory (asset account)

This happens in real time, so the P&L always reflects accurate gross margin.

Insurance panels as accounts receivable: Each insurance panel (e.g., Adamjee, EFU, State Life) is modeled as a subledger under Accounts Receivable. When a patient covered by insurance receives treatment: - Debit: Accounts Receivable (Adamjee panel) - Credit: Revenue

When the panel pays the claim: - Debit: Bank - Credit: Accounts Receivable (Adamjee panel)

This gives you automatic aging reports and tracks how much each panel owes at any moment.

Technical Implementation: Event Sourcing and Immutability

To make this work reliably, we used two key patterns:

1. Event-driven architecture: Every domain event (patient registered, consultation completed, lab test ordered, payment received) triggers accounting posts. The clinical modules don't know or care about accounting—they just emit events. A separate accounting service subscribes to these events and posts journal entries.

This separation of concerns means: - Clinical staff never see accounting complexity - The accounting layer can be modified without touching clinical code - Events are immutable and auditable

2. Immutable ledger: Once a journal entry is posted, it cannot be edited or deleted. If you need to correct an error, you post a reversal entry. This is a fundamental accounting principle, and it's also a compliance requirement for lab accreditation (more on that in the next section).

At the database level, we enforce double-entry validation with constraints: every journal entry must have equal debit and credit sums. If they don't match, the database rejects the transaction.

Bounded Contexts: Clinical vs. Financial

We organize the system into bounded contexts (a Domain-Driven Design concept): - Clinical context: Manages patients, appointments, EMR, prescriptions, lab orders - Financial context: Manages accounts, ledger entries, invoicing, payments - Inventory context: Manages pharmacy stock, batches, expiry tracking

These contexts communicate via internal APIs and domain events, not shared database tables. This loose coupling makes the system easier to maintain and scale.

3. The ISO 15189 LIMS Layer

Healthcare software isn't just about money—it's about patient safety and regulatory compliance. For diagnostic laboratories, ISO 15189 is the international accreditation standard (similar to CAP—College of American Pathologists—in the US). In Pakistan, labs seeking PNAC (Pakistan National Accreditation Council) accreditation must implement ISO 15189 workflows.

ISO 15189 compliance requires specific workflows that most off-the-shelf LIMS (Laboratory Information Management Systems) don't support. We built these workflows into EloHIMS from day one.

What ISO 15189 Requires

ISO 15189 specifies how laboratories must handle samples and results to ensure accuracy and safety. Key requirements:

1. Two-tier verification: Every lab result must be verified twice: - Technical validation: The laboratory technician who performed the test verifies the result is technically correct (no instrument errors, controls passed, result within expected range) - Medical authorization: A pathologist or senior medical officer reviews the result in clinical context and authorizes release to the patient

No result can be released without both signatures.

2. Turnaround time (TAT) tracking: Labs must track the time from sample collection to result release for every test type. If a test exceeds its SLA (e.g., CBC must complete within 2 hours), the system must flag it.

3. Sample rejection logging: If a sample arrives hemolyzed, clotted, mislabeled, or insufficient, the lab must reject it and log the rejection reason. ISO auditors check these logs.

4. Critical value alerts (panic values): Some results indicate life-threatening conditions (e.g., blood glucose <40 mg/dL, potassium >6.5 mEq/L). These results must be flagged immediately and cannot be released without senior authorization and immediate communication to the treating physician.

5. Chain of custody: Every sample must be tracked from collection to disposal. Barcode scanning ensures the right sample goes to the right test and the right patient gets the right result.

Our Approach: State Machines and Workflow Engines

We model the sample lifecycle as a finite state machine with these states:

Ordered → Collected → Received → Analyzed → Validated → Authorized → Released

Each state transition is governed by business rules: - Ordered → Collected: Phlebotomist scans patient barcode and sample barcode, logs collection time - Collected → Received: Lab accessioner scans sample into LIS, checks for hemolysis/clotting, accepts or rejects - Received → Analyzed: Technician enters results (manually or via instrument interface) - Analyzed → Validated: Technician signs off (technical validation) - Validated → Authorized: Pathologist signs off (medical authorization) - Authorized → Released: Result printed or sent to EMR

Panic values trigger a special workflow: if a result is flagged as critical, it moves to a separate queue and cannot be released until a senior pathologist reviews it and the system logs notification to the treating doctor.

TAT Breach Detection

Turnaround time is calculated in real time: - Collection time is captured when the sample barcode is scanned - Release time is captured when the result is authorized - TAT = Release Time - Collection Time

Each test type has a configured TAT SLA (e.g., CBC: 2 hours, HbA1c: 24 hours). If a test exceeds its SLA, it appears on a breach dashboard, and a notification is sent to the lab manager.

This is implemented with time-based database triggers and a background job that checks every pending test every 15 minutes.

Audit Trail for Compliance

ISO 15189 auditors need to see who touched a sample, when, and why. Every state transition is logged: - Who scanned the sample - When it was received - Who validated the result - Who authorized it - If it was rejected, why

This audit trail is immutable—once logged, it cannot be edited. (This is the same immutability principle we used for accounting entries.)

Barcode Integration

Barcode tracking is essential for chain of custody. Here's how it works: 1. Patient registration: System generates a unique Medical Record Number (MRN) and prints a barcode wristband 2. Sample collection: Phlebotomist scans patient wristband, then scans pre-printed sample tube barcode. The system links sample → patient → test order. 3. Lab accessioning: Accessioner scans sample barcode to receive it into LIS 4. Result entry: Technician scans sample barcode before entering results (prevents result entry on wrong patient)

This eliminates the "wrong result to wrong patient" error, which is one of the most dangerous failures in lab operations.

4. Integration Pain Points We Solved

Building a unified system that handles both clinical workflows and financial transactions created several integration challenges. Here's how we solved them.

Pain Point 1: Pharmacy COGS Accounting

The problem: When a pharmacist dispenses a drug, the billing module charges the patient a fixed price (e.g., ₨50 per tablet). But the pharmacy may have three batches of that drug in stock, purchased at different costs (₨30, ₨35, ₨40 per tablet). Which cost do you post to the general ledger?

Our solution: The pharmacy module uses FEFO (first-expiry-first-out) batch allocation. When a drug is dispensed: 1. The system identifies all batches of that drug in stock 2. It selects the batch expiring soonest 3. It retrieves the purchase cost from that batch 4. It posts COGS to the ledger: Debit Cost of Goods Sold, Credit Inventory (at the batch cost)

This ensures accurate gross margin reporting and prevents expired stock from sitting unused.

Pain Point 2: Insurance Claim Timing

The problem: Revenue recognition rules say you should recognize revenue when you earn it (accrual accounting), not when cash is collected. But insurance panels pay claims 30–90 days later. How do you track revenue vs. cash flow?

Our solution: We use accounts receivable subledgers for each insurance panel: - When a patient is treated: Debit Accounts Receivable (Panel Name), Credit Revenue - When the panel pays: Debit Bank, Credit Accounts Receivable (Panel Name)

This separates revenue (earned at time of treatment) from cash collection (received later). The accounts receivable aging report shows which panels are slow to pay, and finance can follow up.

Pain Point 3: Lab Result Flow (Clinical + Financial Sync)

The problem: Lab results live in the LIMS (clinical data), but lab charges live in billing (financial data). If a test is canceled, the LIMS needs to cancel the order AND the billing module needs to reverse the charge. If these two systems aren't in sync, you get phantom charges or unbilled tests.

Our solution: The LIMS and billing modules communicate via domain events: - Event: Lab test ordered → Billing module creates a charge (Debit Accounts Receivable, Credit Lab Revenue) - Event: Lab test canceled → Billing module reverses the charge (Debit Lab Revenue, Credit Accounts Receivable) - Event: Lab result released → No financial impact, but event is logged for reporting

This event-driven approach keeps clinical and financial data in sync without tight coupling.

Pain Point 4: Multi-Branch Accounting

The problem: Hospital groups with multiple branches need consolidated financial statements (group-level P&L) but also branch-level reporting (which branch is profitable?). If each branch maintains separate books, consolidation is a nightmare.

Our solution: We use a single centralized general ledger with branch-level segment tracking: - Every journal entry includes a branch_id dimension - The chart of accounts is shared across all branches (same account codes everywhere) - The ledger supports multidimensional reporting: you can pull P&L for Branch A, Branch B, or consolidated group

This eliminates the consolidation problem—there's only one ledger, and reports are just filtered views.

5. Tech Stack and Architecture Choices

Here's how we approached the architecture for a system that needs to handle clinical workflows, financial transactions, and regulatory compliance simultaneously.

Why We Chose Event Sourcing

Event sourcing is a pattern where you store every state change as an immutable event, rather than updating records in place. For example, instead of updating a balance column in a database, you store a series of events: - AccountCredited { amount: 1000 } - AccountDebited { amount: 300 }

The current balance is derived by replaying the events.

We chose event sourcing for two reasons:

1. Immutability is non-negotiable for both accounting and lab accreditation: Accounting rules prohibit editing or deleting ledger entries—you can only post reversals. ISO 15189 requires an immutable audit trail of every sample state transition. Event sourcing gives us immutability by design.

2. Debugging and compliance audits are easier: If a hospital reports a discrepancy ("Why was this patient charged twice?"), we can replay the event stream and see exactly what happened, in order.

Database Design: Bounded Contexts with Eventual Consistency

We organized the system into bounded contexts: - Clinical context: Patient records, appointments, EMR, lab orders, prescriptions - Financial context: Accounts, ledger, invoicing, payments - Inventory context: Pharmacy stock, batches, expiry tracking

Each context has its own database schema and communicates with other contexts via internal APIs and asynchronous events. This means: - Changes in one context don't break another (loose coupling) - Each context can be scaled independently (if lab traffic is high, scale the LIMS service) - Eventual consistency is acceptable: if a lab test is ordered, the charge is posted to accounting within seconds (not microseconds), and that's fine

Cloud-Native Considerations

We built EloHIMS as a multi-tenant SaaS application, which introduces additional constraints:

1. Data isolation: Each hospital's data is logically isolated (row-level security via tenant_id columns). No hospital can see another hospital's data.

2. Backup and disaster recovery: Daily automated backups to cloud object storage. In Pakistan, electricity outages are common, so hospitals need confidence that cloud hosting is more reliable than on-premise servers.

3. Scalability: Multi-tenancy means we serve dozens of hospitals from a single codebase. As we add customers, we scale horizontally (add more application instances) rather than provisioning separate infrastructure for each hospital.

API-First Approach

Every module exposes its functionality via internal APIs: - The billing module exposes an API to create charges, apply payments, issue refunds - The LIMS module exposes an API to order tests, enter results, release reports - The accounting module exposes an API to post journal entries, query balances, generate reports

This loose coupling makes it easier to add new modules or replace existing ones without breaking the system.

6. Lessons Learned

Building an accounting-first HIMS taught us several lessons about healthcare software architecture.

Lesson 1: Accounting Rules Are Non-Negotiable

Early in development, a developer proposed allowing manual edits to ledger entries "for convenience" when a user makes a mistake. We rejected this. Accounting rules are non-negotiable: once an entry is posted, it's permanent. If there's an error, you post a reversal.

This discipline prevents fraud and makes audits possible. It's harder to build, but it maintains accounting integrity.

Lesson 2: Compliance Workflows Need Workflow Engines, Not Hard-Coded Logic

ISO 15189 and CAP requirements are specific and inflexible: two-tier verification, TAT tracking, panic value alerts. Hardcoding these rules into the application makes the system brittle—if ISO updates its requirements, you have to change code.

Instead, we built a workflow engine: lab workflows are configured as state machines with rules. If ISO adds a new requirement (e.g., a third verification step for molecular tests), we update the configuration, not the code.

Lesson 3: Hide Accounting Complexity from Clinical Staff

Doctors and nurses should never see debits and credits. They should see "Patient charged ₨1,000" and "Payment received ₨1,000." The accounting layer is hidden in the architecture.

This separation of concerns is crucial for usability. Clinical users don't care how the ledger works—they just want the system to do the right thing automatically.

Lesson 4: Event-Driven Architecture Keeps Systems in Sync

Before we adopted event-driven architecture, we tried keeping billing and accounting in sync with database triggers. It was a nightmare—race conditions, circular dependencies, impossible-to-debug failures.

Events solved this: when a payment is received, the billing module emits a PaymentReceived event. The accounting service listens for that event and posts the journal entry. The two modules don't directly call each other, so they can evolve independently.

7. Conclusion: Start with the Ledger, Not the UI

If you're building healthcare software—or any complex ERP-like system—here's the most important lesson we learned:

Build the accounting layer first, then layer the workflows on top.

Most teams do it backwards: they build a beautiful UI for patient registration, OPD queues, and lab orders, then try to bolt accounting on at the end. By that point, you've baked in assumptions that make double-entry accounting hard or impossible.

If you start with the ledger, every feature you build automatically posts to the correct accounts. There's no reconciliation because there's nothing to reconcile. The books are always balanced.

The same principle applies to compliance workflows: if you're building a LIMS, start with the ISO 15189 state machine, not the result-entry screen.

It's harder upfront, but it eliminates a decade of technical debt.

Discussion

If you're working on healthcare software, ERP systems, or any domain where financial accuracy and regulatory compliance are non-negotiable, I'd love to hear your thoughts:

Drop a comment below—let's learn from each other.

About the authors: We're the engineering team at IT Vision, builders of EloHIMS—a cloud hospital information and management system for hospitals in Pakistan. We built EloHIMS to solve the reconciliation nightmare by integrating double-entry accounting, ISO 15189-compliant LIMS, and clinical workflows into a single platform.

If you're curious about how we implemented specific features (barcode chain-of-custody, multi-branch consolidation, etc.), feel free to ask in the comments or reach out via our site.

Sources

Tagshealthcaresoftwareaccountingiso15189architecturesaaserp
Back to all articles

Run your whole hospital on one system

See how EloHIMS unifies patient records, OPD, inpatient, pharmacy, lab and billing on one platform. Book a quick demo.

Start 15-Day Free TrialBook a demo