Skip to content

Latest commit

 

History

676 Commits

Folders and files

Repository files navigation

SATUSEHAT Integration Library

Open-source PHP library for integrating with SATUSEHAT — Indonesia's national health data platform powered by FHIR R4. Works standalone (native PHP) or with Laravel.

PHP FHIR R4 License Latest Version downloads Downloads XERJ Corpus Hub contributor

Status and coverage (measured, not claimed)

Area Count Evidence
Builder 141 resources src/Builder/PayloadBuilder*.php
Builder methods 1,405 per-resource method surface test
Parser 142 classes one getter per builder element, tests/Parser/ParserSurfaceTest.php
Datatype 34 src/DataType
R5 namespace 142 builders + 34 datatypes src/R5, tests/Version/R5NamespaceTest.php
Tests 1,933 vendor/bin/phpunit tests

R4 conformance is not the same thing as cross-language parity. docs/R4_CONFLICT_TRIAGE.md records the audit against the R4 definitions: 46 builders clean, 68 using a generic setter on a resource that has no such element, 20 needing a per-element decision, 7 resources that do not exist in R4.

R4 is the reference; R5 changes one use line

use Satusehat\Integration\Builder\PayloadBuilderPatient;      // R4 (reference)
use Satusehat\Integration\R5\Builder\PayloadBuilderPatient;   // R5 — this line only

Every R5 class extends its R4 class unchanged, and a test asserts that the method surface is identical. Adding a verified R5 difference: docs/FHIR_VERSIONING.md.


Overview

satusehat-integration is an open-source PHP library for integrating with SATUSEHAT — Indonesia's national health data platform powered by FHIR R4.

Built on the official SATUSEHAT Platform Guidelines. Ships with:

  • 32 DataType classes — composable FHIR R4 value objects
  • 141 PayloadBuilder classes — fluent builders for 139 FHIR R4 resources + 2 SATUSEHAT NON-FHIR builders (BillingStatus, PurificationDecision)
  • SSRequest / SSResponse — HTTP client with OAuth2 + retry
  • Durable queue + worker — SQLite-backed, retry/DLQ, rate limiting, monitoring
  • SSValidationError — maps 558 SATUSEHAT validation rule codes to human messages
  • Master data: ICD-10, Kode Wilayah Indonesia, KFA v2

Deploy as standalone PHP or integrate with Laravel via the service provider.


Quick Install

composer require ivanwilliammd/satusehat-integration
# .env
SATUSEHAT_ENV=DEV          # DEV | STG | PROD
SATUSEHAT_BASE_URL_DEV=https://api-satusehat-dev.dto.kemkes.go.id
CLIENTID_DEV=your_client_id
CLIENTSECRET_DEV=your_client_secret
ORGID_DEV=your_org_id

TerminologyClient — SmarTerm (terminology.ivanmd.id)

TerminologyClient menghubungkan aplikasi ke SmarTerm — layanan kamus terpadu terminologi kesehatan Indonesia (ICD-10, ICD-9-CM, SNOMED CT, LOINC, KPTL, KFA obat/alkes/BZA). Berguna saat aplikasi TIDAK ingin menyimpan dataset nasional locally — just call the REST API to search / validate / resolve FHIR codes.

TERMINOLOGY_BASE_URL=https://terminology.ivanmd.id      # opsional
# Auth — pilih SALAH SATU:
TERMINOLOGY_API_TOKEN=your_pat                           # 1) Sanctum PAT (statis)
TERMINOLOGY_CLIENT_ID=your_oidc_client                   # 2) OIDC client_credentials
TERMINOLOGY_CLIENT_SECRET=your_oidc_secret               #    ke auth.ivanmd.id (auto refresh)
TERMINOLOGY_TOKEN_URL=https://auth.ivanmd.id/oauth/token #    default
use Satusehat\Integration\TerminologyClient;

// PAT statis (atau kosongkan kalau pakai env OIDC → auto-fetch + cache + refresh)
$term = new TerminologyClient('https://terminology.ivanmd.id', 'sanctum-pat-...');

// Fluent chaining — istilah bebas RS → kode resmi
$result = $term->query('pemasangan kateter')->on('kptl')->limit(10)->get();
$result = $term->query('demam berdarah')->category('diagnosis')->first()->get();
$result = $term->query('93004944')->asCode()->get();     // validasi kode, sistem ditebak (93→kfa)
$result = $term->query('91001834')->on('kfa_bza')->asCode()->get(); // paksa sistem

// Atau method langsung:
$result = $term->search('demam berdarah', 'diagnosis', 10);  // unified
$alkes  = $term->searchSystem('kfa_alkes', 'termometer', 5); // per sistem
$ok     = $term->validate('snomed', '44054006');             // { valid, display, active }
$cond   = $term->resolveCondition('E11', 'icd10', 'encounter-diagnosis');
$med    = $term->resolveMedication('93004944');              // KFA obat
$kptl   = $term->kptlCombine('10026', ['OR032', 'PD002']);   // KPTL multi-layer
$map    = $term->map('icd10', 'snomed', 'E11');              // lintas terminologi

Architecture

DataType Classes (src/DataType/)

Atomic FHIR R4 value objects. All extend DataType which provides a recursive toArray() method — nested DataType instances serialize to clean FHIR JSON automatically.

Category Classes
Core Coding, CodeableConcept, Identifier, Period, ContactPoint, Address, HumanName, Reference
Quantity Quantity, SimpleQuantity, Range, Ratio, Age, Count, Distance, Duration, Money
Structured Attachment, Narrative, Annotation, Timing, TimingRepeat, Dosage, DosageDoseAndRate
Utility Extension, Signature, RelatedArtifact, Expression, TriggerDefinition, DataRequirement, ParameterDefinition

Example — HumanName:

use Satusehat\Integration\DataType\HumanName;

$name = new HumanName(
    family: 'Doe',
    given: ['John', 'Michael'],
    use: 'official'
);
// $name->toArray() → ['family' => 'Doe', 'given' => ['John', 'Michael'], 'use' => 'official']

PayloadBuilder Pattern (src/Builder/)

Fluent builder for each FHIR resource. Each builder accepts DataType instances and exposes a build() method returning a clean FHIR JSON payload.

$patient = (new PayloadBuilderPatient)
    ->setId('12345678-1234-1234-1234-123456789012')
    ->addIdentifier($identifier)
    ->addName($name)
    ->setGender('male')
    ->setBirthDate('1990-01-15')
    ->addAddress($address)
    ->addTelecom($phone)
    ->build();

SSRequest / SSResponse

  • SSRequest — HTTP client with get(), post(), put(), delete() methods. Handles OAuth2 bearer tokens, auto-refresh on HTTP 401, retry with exponential backoff on 429/5xx, configurable timeout.
  • SSResponse — Structured response wrapper: isSuccess() / isError(), getErrorMessages(), getResourceId().
use Satusehat\Integration\SSRequest\SSRequest;
use Satusehat\Integration\OAuth2Client;

$oauth2 = new OAuth2Client();
$ss = new SSRequest($oauth2);

$resp = $ss->post('Patient', $patientPayload);

if ($resp->isSuccess()) {
    $patientId = $resp->getResourceId();
} else {
    foreach ($resp->getErrorMessages() as $msg) {
        // handle error
    }
}

Queue + Worker

Durable SQLite queue with background worker. Handles retry, DLQ, rate limiting, and monitoring. Works standalone (no Laravel needed).

use Satusehat\Integration\Queue\SqliteQueue;
use Satusehat\Integration\Queue\Worker;
use Satusehat\Integration\Queue\RateLimiter;
use Satusehat\Integration\Queue\QueueMonitor;

// Setup
$pdo   = new PDO('sqlite:' . __DIR__ . '/queue.db');
$queue = new SqliteQueue($pdo);

// Enqueue a FHIR resource
$job = $queue->enqueue(
    method: 'POST',
    resourceType: 'Patient',
    url: 'Patient',
    payload: $patientPayload,
    idempotencyKey: 'patient:12345:create',
    userId: 'system',
);

// Process with worker (300 RPM rate limit)
$worker = new Worker($queue, [
    'client_id'     => $_ENV['SS_CLIENT_ID'],
    'client_secret' => $_ENV['SS_CLIENT_SECRET'],
    'base_url'     => 'https://api-satusehat-stg.dto.kemkes.go.id',
    'fhir_url'     => 'https://api-satusehat-stg.dto.kemkes.go.id/fhir-r4/v1',
], new RateLimiter(300));

$result = $worker->process(50); // process up to 50 jobs
print_r($result);

// Monitor
$monitor = new QueueMonitor($queue);
print_r($monitor->healthCheck());

Status flow: pending → processing → success | failed (auto-retry) | dlq

Error classification: 401 (retry+token refresh), 429 (honor Retry-After), 422/400/403/404/409/412 (DLQ), 5xx (retry)

Artisan commands (Laravel):

php artisan ss:enqueue POST Patient --payload='{}'
php artisan ss:worker --batch=50
php artisan ss:stats
php artisan ss:dead-letters
php artisan ss:requeue {id}

Usage Examples

Patient

use Satusehat\Integration\SSRequest\SSRequest;
use Satusehat\Integration\OAuth2Client;
use Satusehat\Integration\DataType\Identifier;
use Satusehat\Integration\DataType\HumanName;
use Satusehat\Integration\DataType\Address;
use Satusehat\Integration\DataType\ContactPoint;
use Satusehat\Integration\DataType\CodeableConcept;
use Satusehat\Integration\DataType\Period;
use Satusehat\Integration\Builder\PayloadBuilderPatient;

$ss = new SSRequest(new OAuth2Client());

// Compose DataType objects
$identifier = new Identifier(
    system: 'https://fhir.kemkes.go.id/id/NIK',
    value: '3312345678901234'
);

$name = new HumanName(
    family: 'Doe',
    given: ['John'],
    use: 'official'
);

$phone = new ContactPoint(
    system: 'phone',
    value: '081234567890',
    use: 'mobile'
);

$address = new Address(
    use: 'home',
    line: ['Jl. Sudirman No.1'],
    city: 'Jakarta Selatan',
    district: 'Kebayoran Baru',
    state: 'DKI Jakarta',
    postalCode: '12190',
    country: 'ID'
);

// Build Patient resource
$patient = (new PayloadBuilderPatient)
    ->addIdentifier($identifier)
    ->addName($name)
    ->setGender('male')
    ->setBirthDate('1990-01-15')
    ->addTelecom($phone)
    ->addAddress($address)
    ->setActive(true)
    ->build();

$resp = $ss->post('Patient', $patient);

Encounter

use Satusehat\Integration\DataType\Reference;
use Satusehat\Integration\DataType\CodeableConcept;
use Satusehat\Integration\DataType\Period;
use Satusehat\Integration\Builder\PayloadBuilderEncounter;

$subject = new Reference(
    reference: "Patient/{$patientId}",
    display: 'John Doe'
);

$participant = new Reference(
    reference: 'Practitioner/10009880728',
    display: 'Dr. Smith'
);

$class = new CodeableConcept(
    coding: [new \Satusehat\Integration\DataType\Coding(
        system: 'http://terminology.hl7.org/CodeSystem/v3-ActCode',
        code: 'AMB',
        display: 'ambulatory'
    )]
);

$encounter = (new PayloadBuilderEncounter)
    ->setStatus('finished')
    ->setClass($class)
    ->setSubject($subject)
    ->addParticipantIndividual($participant)
    ->setPeriodStart(now()->toIso8601String())
    ->addReasonText('Pemeriksaan umum')
    ->build();

$resp = $ss->post('Encounter', $encounter);

Observation

use Satusehat\Integration\DataType\CodeableConcept;
use Satusehat\Integration\DataType\Coding;
use Satusehat\Integration\DataType\Reference;
use Satusehat\Integration\DataType\Quantity;
use Satusehat\Integration\DataType\Annotation;
use Satusehat\Integration\Builder\PayloadBuilderObservation;

$category = new CodeableConcept(
    coding: [new Coding(
        system: 'http://terminology.hl7.org/CodeSystem/observation-category',
        code: 'vital-signs',
        display: 'Vital Signs'
    )]
);

$code = new CodeableConcept(
    coding: [new Coding(
        system: 'http://loinc.org',
        code: '8867-4',
        display: 'Heart rate'
    )]
);

$value = new Quantity(
    value: 72,
    unit: 'beats/minute',
    system: 'http://unitsofmeasure.org',
    code: '/min'
);

$observation = (new PayloadBuilderObservation)
    ->setStatus('final')
    ->addCategory($category)
    ->setCode($code)
    ->setSubject($subject)
    ->setEncounter($encounterRef)
    ->setEffectiveDateTime(now()->toIso8601String())
    ->setValueQuantity($value)
    ->addReferenceRange(
        low: new Quantity(value: 60, unit: 'bpm', system: 'http://unitsofmeasure.org', code: '/min'),
        high: new Quantity(value: 100, unit: 'bpm', system: 'http://unitsofmeasure.org', code: '/min'),
        text: '60-100 bpm'
    )
    ->build();

$resp = $ss->post('Observation', $observation);

Old Way vs v4 Way

Before v4 (raw array)

use Satusehat\Integration\OAuth2Client;

$client = new OAuth2Client();

$patient = [
    'resourceType' => 'Patient',
    'identifier' => [['system' => '...', 'value' => '...']],
    'name' => [['family' => 'Doe', 'given' => ['John'], 'use' => 'official']],
    // ... manually build every nested structure
];

[$status, $resp] = $client->ss_post('Patient', $patient);

// Check response by inspecting raw array
if ($status >= 200 && $status < 300) {
    $id = $resp['id'] ?? null;
}

v4 (DataType + PayloadBuilder + SSResponse)

use Satusehat\Integration\SSRequest\SSRequest;
use Satusehat\Integration\OAuth2Client;
use Satusehat\Integration\DataType\Identifier;
use Satusehat\Integration\DataType\HumanName;
use Satusehat\Integration\Builder\PayloadBuilderPatient;

$ss = new SSRequest(new OAuth2Client());

$patient = (new PayloadBuilderPatient)
    ->addIdentifier(new Identifier(system: '...', value: '...'))
    ->addName(new HumanName(family: 'Doe', given: ['John'], use: 'official'))
    ->setGender('male')
    ->build();

$resp = $ss->post('Patient', $patient);

if ($resp->isSuccess()) {
    $id = $resp->getResourceId();
} else {
    foreach ($resp->getErrorMessages() as $msg) { /* log */ }
}

Key improvements in v4:

  • DataType classes guarantee valid FHIR structure
  • toArray() handles nested serialization recursively
  • SSResponse gives typed, structured access to responses
  • Automatic token refresh and retry on network failures
  • Fully fluent builder API

Supported FHIR Resources

The table lists the resources this README documents per HTTP verb. The package itself ships 141 PayloadBuilder* classes and 142 parsers — the measured, re-runnable list is in docs/PARITY.md, not in this table.

# Resource GET POST PUT PATCH Notes
1 Patient ✅ ✅ ✅ ✅ MPI
2 Practitioner ✅ ✅ ✅ ✅ SDMK
3 PractitionerRole ✅ ✅ ✅ ✅
4 Organization ✅ ✅ ✅ ✅ MSI
5 Location ✅ ✅ ✅ ✅
6 Encounter ✅ ✅ ✅ ✅
7 Condition ✅ ✅ ✅ ✅
8 Observation ✅ ✅ ✅ ✅
9 Procedure ✅ ✅ ✅ ✅
10 MedicationRequest ✅ ✅ ✅ ✅
11 Bundle — ✅ — — batch/transaction
12 CarePlan ✅ ✅ ✅ ✅
13 Composition ✅ ✅ ✅ ✅ RME
14 ClinicalImpression ✅ ✅ ✅ ✅
15 Goal ✅ ✅ ✅ ✅
16 NutritionOrder ✅ ✅ ✅ ✅
17 AllergyIntolerance ✅ ✅ ✅ ✅
18 Device ✅ ✅ ✅ ✅
19 DiagnosticReport ✅ ✅ ✅ ✅
20 DocumentReference ✅ ✅ ✅ ✅
21 EpisodeOfCare ✅ ✅ ✅ ✅
22 FamilyMemberHistory ✅ ✅ ✅ ✅
23 GenomicStudy ✅ ✅ ✅ ✅
24 Group ✅ ✅ ✅ ✅
25 Immunization ✅ ✅ ✅ ✅
26 Medication ✅ ✅ ✅ ✅
27 MedicationAdministration ✅ ✅ ✅ ✅
28 MedicationDispense ✅ ✅ ✅ ✅
29 MedicationStatement ✅ ✅ ✅ ✅
30 MolecularSequence ✅ ✅ ✅ ✅
31 QuestionnaireResponse ✅ ✅ ✅ ✅
32 RelatedPerson ✅ ✅ ✅ ✅
33 RiskAssessment ✅ ✅ ✅ ✅
34 ServiceRequest ✅ ✅ ✅ ✅
35 Specimen ✅ ✅ ✅ ✅
36 Substance ✅ ✅ ✅ ✅
37 Task ✅ ✅ ✅ ✅
38 Account ✅ ✅ ✅ ✅
39 ImagingStudy 💼 💼 💼 💼 non-core
40 Coverage 💼 💼 💼 💼 non-core
41 CoverageEligibilityRequest 💼 💼 💼 💼 non-core
42 CoverageEligibilityResponse 💼 💼 💼 💼 non-core
43 Claim 💼 💼 💼 💼 non-core
44 ClaimResponse 💼 💼 💼 💼 non-core
45 ChargeItem 💼 💼 💼 💼 non-core
46 ChargeItemDefinition 💼 💼 💼 💼 non-core
47 ChargeItemResponse 💼 💼 💼 💼 non-core
48 PaymentNotice 💼 💼 💼 💼 non-core
49 PaymentReconciliation 💼 💼 💼 💼 non-core
50 Invoice 💼 💼 💼 💼 non-core

HL7 v2 and MLLP

The package also speaks HL7 v2, because a hospital is rarely a single standard: analyzers and LIS speak v2 over MLLP, while SATUSEHAT speaks FHIR R4. Both live in the same install, with no extra dependency.

use Satusehat\Integration\HL7v2\Ack;
use Satusehat\Integration\HL7v2\Message;
use Satusehat\Integration\HL7v2\Mllp;

$msg = Message::parse($er7);          // CR, LF or CRLF line endings, any encoding characters
$msg->messageType();                  // "ADT"
$msg->triggerEvent();                 // "A01"
$msg->get('PID.5.1');                 // family name, escape sequences decoded
$msg->get('OBX.5');                   // first repetition
$msg->set('PID.8', 'F');              // re-escaped on write
echo $msg->toString();                // ER7, CR-terminated, byte-for-byte round trip

MLLP framing, including the case that breaks naive implementations — a frame split across TCP chunks:

$server = stream_socket_server('tcp://0.0.0.0:2575');
$conn   = stream_socket_accept($server, 30);
while (($er7 = Mllp::read($conn)) !== null) {
    $in  = Message::parse($er7);
    $ack = Ack::build($in, Ack::ACCEPT);   // AA / AE / AR, MSA-2 echoes MSH-10
    Mllp::write($conn, $ack->toString());
}

What is implemented: ER7 parsing and serialisation, field/component/subcomponent access, repetition access, the five HL7 escape sequences plus \Xdd..\ hex escapes, MSH-18 charset reporting, MLLP framing with a stream reader that tolerates arbitrary chunk boundaries, and ACK/NAK generation.

CDA R2 documents

HL7 CDA R2 is the other document format a hospital exchanges. This SDK reads and writes the part that is actually used — the header and the sections with narrative text — and leaves the rest alone.

use Satusehat\Integration\CDA\Document;

$doc = Document::parse($xml);              // refuses anything whose root is not ClinicalDocument
$doc->title();                             // "Resume Medis Rawat Inap"
$doc->patient()->identifier('2.16.840.1.113883.3.3157.1003.1');   // NIK
$doc->patient()->name();
$doc->authors();                           // ["Ivan HARSONO"]
$doc->section('10164-2')->title;           // section by LOINC, searched depth-first
$doc->sectionText('10164-2');              // narrative flattened to text, paragraphs kept
$doc->validate();                          // [] means exchangeable, not clinically correct
$doc = Document::build([
    'id' => 'DOC-1',
    'title' => 'Resume Medis',
    'custodian' => 'RS Contoh',
    'author' => 'Dokter Contoh',
    'patientId' => '3171234567890001',
    'patientName' => 'ANGGRAENI',
    'gender' => 'F',
    'birthTime' => '19850312',
    'sections' => [['loinc' => '10164-2', 'title' => 'Riwayat', 'text' => '<paragraph>Demam.</paragraph>']],
]);
echo $doc->toXml();

Two decisions worth stating:

  • Unknown structure survives a round trip. toXml() writes the same DOM that was parsed, so componentOf/encompassingEncounter, participant, legalAuthenticator and vendor extensions are preserved even though the SDK does not model them. A parser that rebuilds the document from its own model quietly deletes everything it did not understand.
  • Identifiers keep their root. A NIK without its assigning-authority root cannot be matched against anything, and dropping the root is how a local MRN silently becomes a national NIK.

The HL7 CDA R2 schemas are licensed; the classes implement the structural rules from the specification and do not redistribute the XSD.

Batches

A batch is not a message: its first segment is FHS, so Message::parse() would reject the whole file. Batch handles the envelope and hands back the messages inside it.

$messages = Batch::parse($fileEr7);            // FHS/BHS … BTS/FTS, or bare messages
Batch::declaredCount($fileEr7);                // 2, from BTS|2 — compare with count($messages)
$file = Batch::wrap($messages, 'SIMRS', 'LAB'); // builds the envelope and the trailers

Comparing declaredCount() with what was actually parsed is the cheapest integrity check in v2: a truncated file transfer produces fewer messages than the trailer promised.

Persistent connections

Analyzers expect one long-lived MLLP connection, not one per result. session() sends a list of messages over a single socket and returns one result per message, in order:

$results = (new Client('10.0.0.21:2575'))->session($messages);

It reconnects only when the link actually died, and keeps the bytes that arrived after the previous frame: one fread() on a persistent connection routinely returns two or three ACKs at once, and a stateless reader would hand back the first and discard the rest — then block forever waiting for an ACK it had already received.

Sending to an analyzer or LIS, with the two rules that keep a queue from melting:

$client = new Client('10.0.0.21:2575', timeout: 10.0, retries: 2);
$result = $client->send($msg);

$result->accepted();   // MSA-1 == AA
$result->attempts;     // transport retries used
$result->text;         // MSA-3 when the receiver explains its refusal
  • Transport failures retry; verdicts do not. A timeout or closed socket is retried with linear backoff. An AE/AR is returned to the caller — retrying an application rejection turns one bad message into a thousand.
  • MSA-2 must echo MSH-10. A reply carrying a different control id is a stale or misrouted ACK and raises instead of being counted as success.

Validation is data, not a class per message type:

$issues = Profiles::oruR01()->validate($msg);      // ADT_A01, ADT_A08, ORU_R01 built in
$issues = Profile::fromArray([
    'name' => 'ORU_R01_VENDOR_X',
    'message_type' => 'ORU',
    'required_segments' => ['MSH', 'PID', 'OBR', 'OBX'],
    'required_fields' => ['PID.3' => 'Patient identifier', 'OBX.5' => 'Observation value'],
    'allowed_values' => ['OBX.11' => ['F', 'P', 'C', 'X']],
])->validate($msg);

A new vendor is an array, not a port to five languages. Errors block, warnings do not: passes() is true when no error severity is produced.

The test corpus is ten messages a hospital actually sends and ten that must be refused (tests/HL7v2/fixtures), with the expectation for each recorded in manifest.json. The refusal cases carry the weight: a parser that accepts a message with no PID moves the failure into the database at 03:00, without the raw message to look at.

What is not implemented yet, and is not claimed: vendor-specific profiles beyond the three built in, HL7 v2 table validation, batch messages, and a persistent MLLP server daemon (the framing primitives and Mllp::read() are there; the supervisor loop is the operator's).

Strict R4 mode

SATUSEHAT_STRICT_R4=1 makes build() reject top-level elements that do not exist in R4, naming the resource and the offending elements. Off by default — see docs/STRICT_R4.md.

Documentation

Page Description
CHANGELOG Version history and release notes
Wiki Full documentation
Installation composer require, publish config, env setup
Usage OAuth, Patient, Encounter, Condition, Bundle, KFA
Features Full feature matrix
Onboarding SATUSEHAT developer account setup
docs/PARITY.md Measured cross-language parity
docs/history/ Archived plans and migration provenance

External Resources


Contributing

Contributions are welcome. See CONTRIBUTING.md for guidelines.


Support

Open an issue for bugs or feature requests.


License

MIT — see LICENSE.

Releases

Sponsor this project

Packages

Used by

Contributors

Languages