Kulcare Docs
DeveloperHospital surgery center

Hospital and Surgery Center API Reference

Implemented Hospital routes, frontend adapter methods, security requirements, and pending integrations.

OT scheduling settings extend the existing theatre/configuration and day-response contracts. See OT Scheduling Settings for typed weekly/maintenance rules, configuration versions, lock order, and derived review_conflicts. Existing endpoints and permission owners are unchanged.

This page separates implemented routes from the broader API contract. The contract includes planned workflows that are not all available in the backend.

Private Clinical Document Foundation

U3 adds case-scoped metadata/list/upload/download/scan-retry APIs under /clinical/facilities/:facility_id/surgical_cases/:case_id/documents. The private-document contract defines exact routes, multipart fields, purpose-specific authority, error states, and the typed hospitalDocumentsApi. Uploads default off and need D2 approval; no selected scanner or approved retention/deletion implementation ships in this foundation. The API never emits public storage URLs or sets clinical readiness from a scan result. U4 now connects the Lab screen in the candidate. TPA remains unconnected until U5. Use the PDF-first Lab contract for queue, history, evidence commands, exact-key recovery, and effective mode. The new view_lab_readiness key grants queue access only. Private history and commands also need Lab management. Candidate tests do not establish deployment, manual QA, or D2/D3 acceptance.

The reusable stock source has its own Inventory ledger API contract and implementation plan. Inventory U1-U6 are implemented locally; final review and release gates are tracked in the Inventory developer guide. U10 now connects the live Hospital inventory screen to typed quantity/allocation commands and Clinical-owned links locally. See Hospital Case Stock for exact consumer routes, transactions, recovery, and release gates. Negative-stock overrides are not allowed; actual clinical care and unresolved stock confirmation remain separate.

Inventory Source And Hospital Handoff

The generic source routes use /api/inventory/facilities/:facility_id, not Hospital controller inheritance. They cover item/location setup, versioned conversions, paginated balances/history/holds/custody, and receipt/reserve/issue/consume/return/correction commands. The source contract lists exact routes, filter support, permissions, errors, and payloads. The pilot operations guide covers approved opening counts, read-only reconciliation, and the write stop. Stock setup and generic source commands do not require the Hospital module or a case.

Hospital U10 implementation status:

  • Typed decimal-string DTOs and an authenticated source adapter through @kulcare/api-client.
  • Scoped query keys, paginated stock selection, search, and refresh.
  • Clinical-owned case links without patient/case identifiers in Inventory input or audit. MAR links remain separate.
  • One caller transaction for coupled Clinical and Inventory effects; no internal HTTP hop.
  • Explicit actual-use obligations when stock confirmation fails. Pending use is not confirmed consumption or a charge.
  • Stable keys, protected lookup, current authority, version conflicts, and post-write invalidation.
  • Historical command results stay separate from fresh current quantities.
  • Issue, consume, unused return, quarantine, and recording-error correction paths.
  • Complete the scoped U10 review loop; one accepted finding fixed, follow-up clean.
  • Complete the U10 manual QA checklist and release gates.

Pharmacy readiness, MAR stock mapping, Billing charge-source integration, and inventory metrics remain separate units. Do not mark the /hsp/inventory route integrated because source API tests pass. U10 also has consumer HTTP and live-workbench tests. Staging acceptance remains separate.

The live hospitalStockApi.ts consumer provides these additional routes:

OperationRouteState
List case requirementsGET /clinical/facilities/:facility_id/case_stockLocal backend and UI integration; supports case, search and page filters.
Read quantities, holds, custody and historyGET /clinical/facilities/:facility_id/case_stock/:idLocal backend and UI integration with separate pagination.
Apply a case-stock commandPOST /clinical/facilities/:facility_id/surgical_cases/:case_id/stock_commandsNine typed actions with stable keys, versions, required audit and current authorization.
Read protected command history/resultGET /clinical/facilities/:facility_id/surgical_cases/:case_id/stock_commandsLookup by stable key; used for uncertain-result recovery.
Read source items, locations and balancesGET /inventory/facilities/:facility_id/{items,locations,balances}Reusable Inventory source; no case or patient data in source commands.

See Case Stock for permissions, envelopes and recovery rules.

Implemented HTTP adapter surface

The frontend adapter is frontend/apps/hospital/src/services/hospitalHttpApi.ts. The available methods are:

OperationMethodRouteState
Load app contextgetAppContext(facilityId)GET /clinical/facilities/:facility_id/hospital/contextBackend and adapter implemented.
Read configurationgetConfiguration(facilityId)GET /clinical/facilities/:facility_id/hospital/configurationBackend and adapter implemented.
Update configurationupdateConfiguration(facilityId, input)PATCH /clinical/facilities/:facility_id/hospital/configurationBackend and adapter implemented; Settings UI uses it.
List theatreslistOperatingTheatres()GET /clinical/facilities/:facility_id/hospital/theatresBackend and adapter implemented.
Create theatrecreateOperatingTheatre(input)POST /clinical/facilities/:facility_id/hospital/theatresSettings editor merged through PR 2642; U14 extends availability; release QA pending.
Update theatreupdateOperatingTheatre(id, input)PATCH /clinical/facilities/:facility_id/hospital/theatres/:idVersioned editor merged through PR 2642; U14 extends availability; release QA pending.
List surgical caseslistSurgicalCases(filters)GET /clinical/facilities/:facility_id/surgical_casesBackend and adapter implemented.
Read a casegetSurgicalCase(caseId)GET /clinical/facilities/:facility_id/surgical_cases/:idBackend and adapter implemented.
Read case readiness itemsIncluded in getSurgicalCase(caseId)Same case-detail routeVersioned policy, current evidence state, and permitted actions merged through PR 2642. Clinical approval and release QA remain open.
Record or review readinesscommandReadiness(input)POST /clinical/facilities/:facility_id/surgical_cases/:case_id/readiness/:item_id/commandsManual evidence, review, and approved bounded override merged through PR 2642.
Read command historyNo frontend history adapter yetGET on the same command routeProtected paginated history is implemented; case timeline records command references.
Create a casecreateSurgicalCase(input)POST /clinical/facilities/:facility_id/surgical_casesBackend and adapter implemented.
Transition a casetransitionSurgicalCaseStatus(input)POST /clinical/facilities/:facility_id/surgical_cases/:id/transitionBackend and adapter implemented.
Read OT schedulegetOTSchedule(date)GET /clinical/facilities/:facility_id/ot_scheduleBackend and adapter implemented.
Create OT bookingsaveOTBooking(input)POST /clinical/facilities/:facility_id/ot_bookingsBackend and adapter implemented.
Update OT bookingsaveOTBooking(input)PATCH /clinical/facilities/:facility_id/ot_bookings/:idBackend and adapter implemented.
Search facility patientssearchPatients(search)GET /clinical/patient_facilitiesExisting endpoint used by the adapter; facility selector is sent and must be validated by backend context.
Search facility proceduressearchProcedures(search)GET /clinical/facilities/:facility_id/facility_proceduresExisting endpoint used by the adapter.
List surgeonslistSurgeons()GET /identity/facilities/:facility_id/practitionersExisting endpoint used by the adapter.

Theatre routes use /hospital/theatres. Settings lists theatres for view_ot_schedule and exposes edits for manage_ot_schedule. These checks are separate from manage_hospital_configuration and case management. Backend policies still enforce each write. The editor uses name, code, status, turnaround, equipment tags, and availability rules. The room field remains API-only. Policy saves send only the version and changed policy.

Not yet implemented in the HTTP adapter

The following screens currently use mock workflows. The adapter rejects missing operations instead of falling back to mock data:

  • Recovery board and recovery observations.
  • Bed board and bed movement operations.
  • MAR orders and medication administration.
  • Selected-provider Lab scanning and D2/D3 release acceptance; pharmacy readiness source updates.
  • TPA / insurance capture and review, plus full ABDM/HCX exchange.
  • Billing workbench and charge posting.
  • Operational reports and exports.

The framework alone does not make a source workflow live. U4 adds the PDF-first Lab candidate; pharmacy and TPA integration remain pending. U10 separately connects case stock; it does not connect MAR, pharmacy review, charges, or inventory dashboard metrics.

The complete planned endpoint inventory and DTO proposals are in the API contract. A contract row is not an implemented route. Implement each resource group with backend authorization, RLS, audit, frontend adapter, UI integration, and manual QA before marking it complete.

Authentication, facility scope, and permissions

  • Use the platform @kulcare/api-client; it supplies authenticated request behavior.
  • Read active facility/profile state from shell identity context.
  • Keep tenant, facility, and selected-profile identity in React Query keys.
  • Do not send tenant_id from the client.
  • Treat a route facility ID as a selector. The backend must validate it against authenticated tenant and facility membership.
  • Enforce effective permissions in backend policies. UI checks only shape the interface.
  • Use tenant RLS for all protected tenant resources. New tenant tables require both ENABLE ROW LEVEL SECURITY and FORCE ROW LEVEL SECURITY, with USING and WITH CHECK policies.
  • Keep app flag management in Admin and RBAC management in shell.
  • Preserve audit coverage for case PHI reads, sensitive writes, OT booking outcomes, conflicts, and configuration changes.

Readiness Commands

See Hospital Readiness Framework and its manual QA guide. Gap-closure U2 adds these operations locally. Clinical approval D3 and release acceptance remain open. Routes below use the Rails path. Browser requests use the existing /api prefix through @kulcare/api-client.

POST /clinical/facilities/:facility_id/surgical_cases/:case_id/readiness/:item_id/commands accepts:

{
  "command": {
    "operation_key": "stable-client-uuid",
    "action": "review",
    "version": 2,
    "source_revision": 1,
    "state": "ready",
    "reason": "Reviewed the current evidence"
  }
}

Actions are record_source, review, and override. Only manual evidence can use record_source; it accepts ready, warning, blocked, or unavailable and an optional source_reference. Review accepts ready or blocked against current fresh evidence. Override uses the approved policy state and lease, not a client-supplied expiry. All actions require a reason of at most 4,000 characters and current item/source versions. Unknown fields, including actor or tenant identity, are rejected.

Success is 201 for a new command and 200 for replay. data contains id, action, actor_user_id, reason, created_at, item, and replayed; meta contains request_id. The returned item is the immutable original result. Refetch current case detail after success. GET on the same route returns protected paginated command history with standard pagination metadata.

Version and source conflicts return 409 STALE_WRITE or SOURCE_REVISION_CONFLICT. A reused key with a different body returns 409 IDEMPOTENCY_CONFLICT. Authorization returns 403 FORBIDDEN; missing scoped resources or disabled cases return 404. Invalid evidence, missing reasons, locked cases, or unapproved override return 422 with a specific error code. Required audit failure returns 503 AUDIT_UNAVAILABLE and rolls back the command. Retry unknown outcomes with the original full command and key. Do not retry a known conflict with a new key automatically.

Case detail includes readiness_policy_version_id and readiness items with version, source_revision, review/override provenance, and allowed_actions. The adapter maps these to camel case. The editor pins evidence versions when opened. Case listing supports readiness_state in live mode and filters before pagination. OT start, ready-for-discharge, and completion return 409 READINESS_BLOCKED with current blocker details when required evidence is not ready. An absent policy fails closed. There is no default clinical checklist or policy-publishing HTTP endpoint.

Permissions are manage_hospital_readiness, manage_lab_readiness, manage_pharmacy_readiness, and override_hospital_readiness. They do not grant app view, facility assignment, category-module access, or clinical approval. Override also requires explicit member or role authority, even for an owner.

Request and response shape

The adapter expects a standard response envelope:

{
  "data": {},
  "meta": { "request_id": "request-id" }
}

Errors use a structured envelope with an error code, message, optional details, and request ID. OT conflict responses may include structured conflict entries. The adapter normalizes backend errors to HospitalApiError and maps snake-case records to camel-case DTOs.

Cache and write behavior

Use query-key helpers from services/hospitalQueryKeys.ts. Include the active tenant, facility, and profile scope. After a successful mutation, invalidate the changed resource and dependent projections. After a facility/profile switch, cancel and clear old scoped queries so a delayed response cannot populate the new view.

For versioned case and booking writes, send the current version. Do not retry a forbidden or stale mutation as though it were a transport failure. Render server conflict details and preserve user-entered values where the workflow permits.

Theatre PATCH also requires theatre.version, an opaque string returned on theatre reads and writes. Missing or stale versions return 409 STALE_WRITE. The timestamp-backed token needs no migration. The server locks the theatre during compare-and-save. Booking writes lock and reload the theatre before checking active status. This keeps eligibility and turnaround current. The settings editor preserves failed drafts and requires an explicit reload after a stale write. Successful edits invalidate theatres, OT schedules, case detail, and the dashboard in the active query scope. Existing booking rows and their turnaround snapshots do not change.

Adapter tests

HTTP contract tests live in frontend/apps/hospital/tests/hospital-http-api.test.ts. Add coverage for:

  • exact route and request body;
  • envelope and snake-case mapping;
  • filters and optional values;
  • error code, status, and request ID normalization;
  • conflicts and version fields;
  • facility scope and cache invalidation at the feature boundary.

These frontend tests do not replace backend authorization, audit, or enforced-role RLS tests.

On this page