### Run the development environment Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/packages/esm-patient-task-list-app/README.md Commands to install project dependencies and start the local development server. ```sh yarn # to install dependencies yarn start # to run the dev server ``` -------------------------------- ### Start development server Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/README.md Launch a development server for specific microfrontends. ```bash yarn start --sources 'packages/esm-patient--app' ``` ```bash yarn start --sources 'packages/esm-patient-biometrics-app' --sources 'packages/esm-patient-vitals-app' ``` -------------------------------- ### Install dependencies Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/README.md Run this command to install all project dependencies. ```bash yarn ``` -------------------------------- ### Start Development Server for Testing Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/README.md Launch the dev server with specific source packages to test local changes. ```bash yarn start --sources packages/esm-patient-allergies-app ``` -------------------------------- ### Setup E2E Test Environment Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/README.md Install required Playwright browsers and initialize the environment configuration file. ```bash npx playwright install cp example.env .env ``` -------------------------------- ### Start development server Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/packages/esm-generic-patient-widgets-app/README.md Executes the development server for the generic patient widgets package from the project root. ```bash yarn run --sources 'packages/esm-generic-patient-widgets-app' ``` -------------------------------- ### Configure Order Types and Concept Sets Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/packages/esm-patient-orders-app/README.md Define custom order types, associate them with concept sets, and set display labels and icons. Example shows configuration for 'Medications'. ```typescript orderTypes: { _type: Type.Array, _elements: { orderTypeUuid: '131168f4-15f5-102d-96e4-000c29c2a5d7', // Drug Order UUID orderableConceptSets: ['drug-concepts-uuid'], // Concept set UUIDs label: 'Medications', // Display label icon: 'omrs-icon-medication' // OpenMRS icon name } } ``` -------------------------------- ### Implement CardHeader Component Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Use the CardHeader component to maintain consistent widget styling. Ensure required Carbon React dependencies are installed. ```typescript import { CardHeader } from '@openmrs/esm-patient-common-lib'; import { Button } from '@carbon/react'; import { Add } from '@carbon/react/icons'; function VitalsCard() { return (
{/* Vitals content */}
); } ``` -------------------------------- ### Run tests Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/README.md Commands for executing unit and integration tests across the monorepo. ```bash yarn turbo run test ``` ```bash yarn turbo run test:watch ``` ```bash yarn turbo run test --filter=@openmrs/esm-patient-conditions-app ``` ```bash yarn turbo run test -- visit-notes-form ``` ```bash yarn turbo run test:watch --ui tui -- visit-notes-form ``` ```bash yarn turbo run coverage ``` ```bash yarn turbo run test --force ``` -------------------------------- ### Launching Patient Chart Workspaces Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Provides utilities for launching patient chart workspaces. `launchPatientChartWithWorkspaceOpen` navigates to a specific workspace, while `useLaunchWorkspaceRequiringVisit` ensures a visit is active before launching. ```typescript import { launchPatientChartWithWorkspaceOpen, useLaunchWorkspaceRequiringVisit } from '@openmrs/esm-patient-common-lib'; // Launch patient chart with a specific workspace open function NavigateToPatientForm() { const handleNavigate = () => { launchPatientChartWithWorkspaceOpen({ patientUuid: 'patient-uuid-123', workspaceName: 'patient-vitals-biometrics-form-workspace', dashboardName: 'summary', additionalProps: { encounterUuid: 'encounter-uuid-456' } }); }; return ; } // Use hook to launch workspace with visit requirement function AddAllergyButton({ patientUuid }: { patientUuid: string }) { const launchAllergyWorkspace = useLaunchWorkspaceRequiringVisit<{ allergyUuid?: string }> patientUuid, 'patient-allergy-form-workspace' ); const handleAddAllergy = () => { // Automatically prompts for visit if none active launchAllergyWorkspace({ allergyUuid: undefined }); }; return ; } ``` -------------------------------- ### Configure Remote E2E Base URL Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/README.md Update the environment variable in .env to point to a remote instance. ```bash E2E_BASE_URL=https://dev3.openmrs.org/openmrs ``` -------------------------------- ### Execute E2E Tests Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/README.md Run the test suite in various modes including headless, headed, and interactive UI mode. ```bash yarn test-e2e ``` ```bash yarn test-e2e --headed ``` ```bash yarn test-e2e --ui ``` ```bash yarn test-e2e --headed --ui ``` ```bash yarn test-e2e ``` -------------------------------- ### Manage Visit Notes and Diagnoses Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Use `useVisitNotes` hook to fetch visit notes and `saveVisitNote` to add new ones. Requires patient UUID for fetching and specific IDs for encounter details. `fetchDiagnosisConceptsByName` can be used to search for diagnosis concepts. ```typescript import { useVisitNotes, saveVisitNote, updateVisitNote, savePatientDiagnosis, deletePatientDiagnosis, fetchDiagnosisConceptsByName } from '@openmrs/esm-patient-notes-app'; function VisitNotesWidget({ patientUuid }: { patientUuid: string }) { const { visitNotes, isLoading, mutateVisitNotes } = useVisitNotes(patientUuid); const handleSaveNote = async (noteData: { visitUuid: string; encounterTypeUuid: string; locationUuid: string; providerUuid: string; noteText: string; diagnosisConcepts: string[]; }) => { const abortController = new AbortController(); const payload = { visit: noteData.visitUuid, encounterType: noteData.encounterTypeUuid, location: noteData.locationUuid, encounterProviders: [{ provider: noteData.providerUuid, encounterRole: 'encounter-role-uuid', }], obs: [{ concept: 'visit-note-concept-uuid', value: noteData.noteText, }], }; await saveVisitNote(abortController, payload); mutateVisitNotes(); }; const handleSearchDiagnoses = async (searchTerm: string) => { const results = await fetchDiagnosisConceptsByName( searchTerm, 'diagnosis-concept-class-uuid' ); return results; }; return (

Visit Notes

{visitNotes?.map(note => (

Date: {new Date(note.encounterDate).toLocaleDateString()}

Provider: {note.encounterProvider}

Diagnoses: {note.diagnoses}

Note: {note.encounterNote}

))}
); } ``` -------------------------------- ### Update Core Libraries Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/README.md Upgrade core dependencies and regenerate the lockfile to resolve version mismatches. ```bash # Upgrade core libraries yarn up openmrs@next @openmrs/esm-framework@next # Reset version specifiers to `next`. Don't commit actual version numbers. git checkout package.json # Run `yarn` to recreate the lockfile yarn ``` -------------------------------- ### Manage Patient Program Enrollments with TypeScript Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Use hooks and functions to manage patient program enrollments, including creating, updating, and deleting enrollments. Ensure correct payload structure for each operation. ```typescript import { usePrograms, useEnrollments, useAvailablePrograms, createProgramEnrollment, updateProgramEnrollment, deleteProgramEnrollment } from '@openmrs/esm-patient-programs-app'; function ProgramsWidget({ patientUuid }: { patientUuid: string }) { const { enrollments, activeEnrollments, eligiblePrograms, isLoading } = usePrograms(patientUuid); const handleEnrollInProgram = async (programUuid: string, locationUuid: string) => { const abortController = new AbortController(); const payload = { program: programUuid, patient: patientUuid, dateEnrolled: new Date().toISOString(), dateCompleted: null, location: locationUuid, states: [], }; try { await createProgramEnrollment(payload, abortController); console.log('Enrolled successfully'); } catch (error) { console.error('Enrollment failed:', error); } }; const handleCompleteEnrollment = async (enrollmentUuid: string) => { const abortController = new AbortController(); const payload = { dateEnrolled: '2024-01-01', dateCompleted: new Date().toISOString(), location: 'location-uuid', states: [], }; await updateProgramEnrollment(enrollmentUuid, payload, abortController); }; const handleDeleteEnrollment = async (enrollmentUuid: string) => { await deleteProgramEnrollment(enrollmentUuid); }; return (

Active Enrollments

{activeEnrollments?.map(enrollment => (
{enrollment.program.display} Enrolled: {enrollment.dateEnrolled}
))}

Available Programs

{eligiblePrograms?.map(program => ( ))}
); } ``` -------------------------------- ### Accessing Patient Chart Store Data Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Demonstrates how to use the `usePatientChartStore` hook to access patient and visit context. Ensure the patient UUID is correctly passed to the hook. ```typescript import { usePatientChartStore } from '@openmrs/esm-patient-common-lib'; function PatientVitalsWidget({ patientUuid }: { patientUuid: string }) { const { patient, visitContext, setVisitContext } = usePatientChartStore(patientUuid); // Access current patient information console.log('Patient name:', patient?.name?.[0]?.family); // Access current visit context if (visitContext) { console.log('Current visit:', visitContext.uuid); console.log('Visit type:', visitContext.visitType?.display); } // Update visit context when starting a new visit const handleVisitStarted = (newVisit: Visit, mutate: () => void) => { setVisitContext(newVisit, mutate); }; return (

Patient: {patient?.name?.[0]?.given?.join(' ')} {patient?.name?.[0]?.family}

{visitContext &&

Active Visit: {visitContext.visitType?.display}

}
); } ``` -------------------------------- ### Submit Orders with a New Encounter Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Use this function to create new orders and associate them with a newly created encounter. Requires patient, location, and provider UUIDs, and optionally visit information. ```typescript import { postOrdersOnNewEncounter, postOrders, postEncounter } from '@openmrs/esm-patient-common-lib'; // Create orders with a new encounter async function submitOrdersWithNewEncounter( patientUuid: string, currentVisit: Visit | null, locationUuid: string, providerUuid: string ) { const abortController = new AbortController(); try { const encounter = await postOrdersOnNewEncounter( patientUuid, 'order-encounter-type-uuid', currentVisit, locationUuid, providerUuid, abortController ); console.log('Orders submitted successfully:', encounter.uuid); return encounter; } catch (error) { console.error('Failed to submit orders:', error); throw error; } } ``` -------------------------------- ### Create Dashboard Link Utility Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Generates navigation links for patient chart dashboards, compatible with the extension-based architecture. Specify a title, path, and an optional Carbon icon name. ```typescript import { createDashboardLink } from '@openmrs/esm-patient-common-lib'; // Create a dashboard link for the allergies widget const allergiesDashboardLink = createDashboardLink({ title: 'Allergies', path: 'allergies', icon: 'warning', // Carbon icon name }); // Use in module exports for extension registration export const allergiesDashboardLinkExtension = { name: 'allergies-dashboard-link', slot: 'patient-chart-dashboard-slot', load: () => allergiesDashboardLink, }; ``` -------------------------------- ### Manage Vitals and Biometrics Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Use the useVitalsAndBiometrics hook to fetch paginated data and createOrUpdateVitalsAndBiometrics to persist new observations. ```typescript import { useVitalsAndBiometrics, useVitalsConceptMetadata, createOrUpdateVitalsAndBiometrics, invalidateCachedVitalsAndBiometrics } from '@openmrs/esm-patient-vitals-app'; function VitalsTable({ patientUuid }: { patientUuid: string }) { const { data: vitals, isLoading, error, hasMore, setPage, currentPage } = useVitalsAndBiometrics(patientUuid, 'both'); const { conceptRanges, conceptUnits } = useVitalsConceptMetadata(patientUuid); if (isLoading) return
Loading vitals...
; if (error) return
Error loading vitals: {error.message}
; return (
{vitals?.map(vital => ( ))}
Date Systolic/Diastolic Pulse Temperature SpO2 Weight BMI
{new Date(vital.date).toLocaleDateString()} {vital.systolic}/{vital.diastolic} {vital.pulse} {vital.temperature} {vital.spo2} {vital.weight} {vital.bmi}
{hasMore && ( )}
); } // Save vitals and biometrics async function saveVitals( patientUuid: string, encounterTypeUuid: string, locationUuid: string, vitalsData: { systolic: number; diastolic: number; pulse: number } ) { const abortController = new AbortController(); const observations = [ { concept: 'systolic-uuid', value: vitalsData.systolic }, { concept: 'diastolic-uuid', value: vitalsData.diastolic }, { concept: 'pulse-uuid', value: vitalsData.pulse }, ]; await createOrUpdateVitalsAndBiometrics( patientUuid, encounterTypeUuid, null, // encounterUuid - null creates new encounter locationUuid, observations, abortController ); // Invalidate cache to refresh all vitals hooks await invalidateCachedVitalsAndBiometrics(); } ``` -------------------------------- ### Manage Medication Orders Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Utilize hooks like `usePatientOrders`, `useActivePatientOrders`, and `usePastPatientOrders` to retrieve medication orders. Functions `buildMedicationOrder` and `prepMedicationOrderPostData` assist in preparing orders for renewal or discontinuation. ```typescript import { usePatientOrders, useActivePatientOrders, usePastPatientOrders, prepMedicationOrderPostData, buildMedicationOrder } from '@openmrs/esm-patient-medications-app'; function MedicationsWidget({ patientUuid }: { patientUuid: string }) { const { data: allOrders, isLoading, mutate } = usePatientOrders(patientUuid); const { data: activeOrders } = useActivePatientOrders(patientUuid); const { data: pastOrders } = usePastPatientOrders(patientUuid); // Convert an existing order to a basket item for renewal const handleRenewOrder = (order: Order) => { const basketItem = buildMedicationOrder(order, 'RENEW'); console.log('Renewal basket item:', basketItem); // Add to order basket... }; // Discontinue an active order const handleDiscontinueOrder = (order: Order) => { const basketItem = buildMedicationOrder(order, 'DISCONTINUE'); console.log('Discontinue basket item:', basketItem); // Add to order basket and submit... }; // Prepare order data for API submission const prepareOrderPayload = (basketItem: DrugOrderBasketItem) => { const payload = prepMedicationOrderPostData( basketItem, patientUuid, 'encounter-uuid', 'provider-uuid' ); return payload; }; return (

Active Medications ({activeOrders?.length || 0})

{activeOrders?.map(order => (
{order.drug?.display} {order.dose} {order.doseUnits?.display} {order.frequency?.display} via {order.route?.display}
))}

Past Medications ({pastOrders?.length || 0})

{pastOrders?.map(order => (
{order.drug?.display} - Stopped: {order.dateStopped}
))}
); } ``` -------------------------------- ### Configure Immunization Parameters Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/packages/esm-patient-immunizations-app/README.md Defines the vaccine concept set and dose/booster schedules for the immunization module. Replace vaccineConceptUuid with actual UUIDs from your system. ```json { "immunizationConceptSet": "CIEL:984", "sequenceDefinitions": [ { "vaccineConceptUuid": "783AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "sequences": [ { "sequenceLabel": "Dose-1", "sequenceNumber": 1 }, { "sequenceLabel": "Dose-2", "sequenceNumber": 2 }, { "sequenceLabel": "Dose-3", "sequenceNumber": 3 }, { "sequenceLabel": "Dose-4", "sequenceNumber": 4 }, { "sequenceLabel": "Booster-1", "sequenceNumber": 11 }, { "sequenceLabel": "Booster-2", "sequenceNumber": 12 } ] } ] } ``` -------------------------------- ### Configure Print Button Visibility Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/packages/esm-patient-orders-app/README.md Control the visibility of the print button in order tables. Defaults to false. ```typescript showPrintButton: { _type: Type.Boolean, _description: 'Show print button in order tables', _default: false } ``` -------------------------------- ### Configure Order Encounter Type Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/packages/esm-patient-orders-app/README.md Set the encounter type for orders by providing its UUID. Defaults to '39da3525-afe4-45ff-8977-c53b7b359158'. ```typescript // config-schema.ts orderEncounterType: { _type: Type.UUID, _description: 'The encounter type for orders', _default: '39da3525-afe4-45ff-8977-c53b7b359158', // "Order" encounter type } ``` -------------------------------- ### Define Patient Chart Configuration Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Configure application behavior and tile definitions via the OpenMRS configuration system. UUIDs must match the specific OpenMRS backend dictionary. ```typescript // Example configuration in routes.json or config file const patientChartConfig = { "@openmrs/esm-patient-chart-app": { disableEmptyTabs: true, encounterEditableDuration: 1440, // 24 hours in minutes showRecommendedVisitTypeTab: true, showServiceQueueFields: false, visitAttributeTypes: [ { uuid: "visit-attribute-type-uuid", required: true, displayInThePatientBanner: true } ], tileDefinitions: [ { title: "Vitals Summary", columns: [ { title: "Blood Pressure", concept: "systolic-bp-uuid", encounterType: "vitals-encounter-uuid", hasSummary: true }, { title: "Weight", concept: "weight-uuid", encounterType: "vitals-encounter-uuid", hasSummary: true } ] } ] } }; ``` -------------------------------- ### Add Immunization Overview Widget to Patient Summary Dashboard Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/packages/esm-patient-immunizations-app/README.md Configure the `immunization-overview-widget` to be displayed on the patient summary dashboard by adding an entry to your `extensions.json` configuration file. This widget provides a summary card for immunization information. ```json { "name": "immunization-overview-widget", "slot": "patient-chart-summary-dashboard-slot", "order": 8 } ``` -------------------------------- ### Manage Patient Allergies with TypeScript Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Utilize hooks and functions to fetch allergens, reactions, and manage patient allergy records. Ensure proper error handling for save and update operations. ```typescript import { useAllergens, useAllergicReactions, useAllergenSearch, saveAllergy, updatePatientAllergy } from '@openmrs/esm-patient-allergies-app'; function AllergyForm({ patientUuid }: { patientUuid: string }) { const { allergens, isLoading: loadingAllergens } = useAllergens(); const { allergicReactions, isLoading: loadingReactions } = useAllergicReactions(); const [searchTerm, setSearchTerm] = useState(''); const { searchResults, isSearching } = useAllergenSearch(searchTerm); const handleSaveAllergy = async (formData: { allergenUuid: string; allergenType: string; severityUuid: string; reactionUuids: string[]; comment?: string; }) => { const abortController = new AbortController(); const payload = { allergen: { allergenType: formData.allergenType, // DRUG, FOOD, or ENVIRONMENT codedAllergen: { uuid: formData.allergenUuid }, }, severity: { uuid: formData.severityUuid }, comment: formData.comment, reactions: formData.reactionUuids.map(uuid => ({ reaction: { uuid } })), }; try { await saveAllergy(payload, patientUuid, abortController); console.log('Allergy saved successfully'); } catch (error) { console.error('Failed to save allergy:', error); } }; const handleUpdateAllergy = async (allergyUuid: string, payload: NewAllergy) => { const abortController = new AbortController(); await updatePatientAllergy(payload, patientUuid, allergyUuid, abortController); }; return (

Add Allergy

Reactions

{allergicReactions?.map(reaction => ( ))}
); } ``` -------------------------------- ### Empty State Component Usage Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Renders a consistent UI for empty data states in widgets. It displays a header, a message indicating no data, and a button to launch a form. Requires patient data fetching and a function to launch a workspace. ```typescript import { EmptyState } from '@openmrs/esm-patient-common-lib'; import { launchWorkspace2 } from '@openmrs/esm-framework'; function AllergiesOverview({ patientUuid }: { patientUuid: string }) { const { allergies, isLoading } = useAllergies(patientUuid); const launchAllergyForm = () => { launchWorkspace2('patient-allergy-form-workspace'); }; if (isLoading) return
Loading...
; if (!allergies || allergies.length === 0) { return ( ); } return (
{allergies.map(allergy => (
{allergy.display}
))}
); } ``` -------------------------------- ### Submit Orders to an Existing Encounter Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Use this function to add new orders to an already existing encounter. It returns details of successfully posted orders and any items that failed. ```typescript import { postOrdersOnNewEncounter, postOrders, postEncounter } from '@openmrs/esm-patient-common-lib'; // Submit orders to an existing encounter async function submitOrdersToExistingEncounter( patientUuid: string, encounterUuid: string, providerUuid: string ) { const abortController = new AbortController(); const { postedOrders, erroredItems } = await postOrders( patientUuid, encounterUuid, abortController, providerUuid ); if (erroredItems.length > 0) { console.error('Some orders failed:', erroredItems.map(item => ({ drug: item.display, error: item.extractedOrderError?.message }))); } return { postedOrders, erroredItems }; } ``` -------------------------------- ### Manage Patient Conditions Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Utilize hooks for searching and managing patient conditions, ensuring the cache is mutated after modifications. ```typescript import { useConditions, useConditionsSearch, createCondition, updateCondition, deleteCondition } from '@openmrs/esm-patient-conditions-app'; function ConditionsWidget({ patientUuid }: { patientUuid: string }) { const { conditions, isLoading, mutate } = useConditions(patientUuid); const [searchTerm, setSearchTerm] = useState(''); const { searchResults, isSearching } = useConditionsSearch(searchTerm); const handleAddCondition = async (condition: CodedCondition) => { const payload = { clinicalStatus: 'active', conceptId: condition.uuid, display: condition.display, onsetDateTime: new Date().toISOString(), abatementDateTime: '', patientId: patientUuid, userId: 'current-user-uuid', }; await createCondition(payload); mutate(); // Refresh conditions list }; const handleResolveCondition = async (conditionId: string) => { const payload = { clinicalStatus: 'inactive', conceptId: 'existing-concept-uuid', display: 'Existing condition', onsetDateTime: '2024-01-01', abatementDateTime: new Date().toISOString(), patientId: patientUuid, userId: 'current-user-uuid', }; await updateCondition(conditionId, payload); mutate(); }; const handleDeleteCondition = async (conditionId: string) => { await deleteCondition(conditionId); mutate(); }; return (
setSearchTerm(e.target.value)} /> {isSearching && Searching...}
    {searchResults.map(result => (
  • handleAddCondition(result)}> {result.display}
  • ))}

Active Conditions

{conditions?.filter(c => c.clinicalStatus === 'Active').map(condition => (
{condition.display} - Onset: {condition.onsetDateTime}
))}
); } ``` -------------------------------- ### Optimistic Visit Mutations Hook Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Use this hook for optimistic updates to visit data to improve perceived performance. It requires the patient's UUID and provides functions for adding, updating, and removing visits, as well as revalidating data. ```typescript import { useOptimisticVisitMutations } from '@openmrs/esm-patient-common-lib'; function VisitManager({ patientUuid }: { patientUuid: string }) { const { addVisitOptimistically, updateVisitOptimistically, removeVisitOptimistically, invalidateVisitRelatedData, revalidateCurrentVisit, revalidateAllVisitData, } = useOptimisticVisitMutations(patientUuid); const handleStartVisit = async (newVisit: Visit) => { // Optimistically add visit to cache addVisitOptimistically(newVisit); try { // Submit to server... await submitVisitToServer(newVisit); // Revalidate to confirm await revalidateCurrentVisit(); } catch (error) { // Rollback on error await revalidateAllVisitData(); } }; const handleEndVisit = async (visitUuid: string) => { // Optimistically update visit with stop time updateVisitOptimistically(visitUuid, { stopDatetime: new Date().toISOString() }); // Invalidate related data that depends on visit state await invalidateVisitRelatedData({ encounters: true, orders: true, }); }; const handleDeleteVisit = async (visitUuid: string) => { // Optimistically remove from cache removeVisitOptimistically(visitUuid); try { await deleteVisitFromServer(visitUuid); } catch (error) { await revalidateAllVisitData(); } }; return (
{/* Visit management UI */}
); } ``` -------------------------------- ### Manage Patient Orders with useOrderBasket Hook Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Use this hook to manage patient orders in a centralized basket. It supports grouping orders by type and prepares data for API submission. Requires patient context and order type. ```typescript import { useOrderBasket, type DrugOrderBasketItem } from '@openmrs/esm-patient-common-lib'; function MedicationOrderForm({ patient }: { patient: fhir.Patient }) { const { orders, setOrders, clearOrders } = useOrderBasket( patient, 'medications', prepareDrugOrderPostData // Function to transform basket item to API payload ); const addMedicationToBasket = (drug: Drug) => { const newOrder: DrugOrderBasketItem = { uuid: crypto.randomUUID(), display: drug.display, drug: drug, action: 'NEW', dosage: 500, unit: { value: 'mg', valueCoded: 'mg-uuid' }, frequency: { value: 'Once daily', valueCoded: 'freq-uuid', frequencyPerDay: 1 }, route: { value: 'Oral', valueCoded: 'route-uuid' }, asNeeded: false, startDate: new Date(), }; setOrders([...orders, newOrder]); }; const removeOrder = (orderUuid: string) => { setOrders(orders.filter(o => o.uuid !== orderUuid)); }; const handleClearAll = () => { clearOrders(); }; return (

Medication Orders ({orders.length})

{orders.map(order => (
{order.display} - {order.dosage} {order.unit?.value}
))}
); } ``` -------------------------------- ### Configure Reference Number Field Visibility Source: https://github.com/openmrs/openmrs-esm-patient-chart/blob/main/packages/esm-patient-orders-app/README.md Control the visibility of the reference number field in order forms. Defaults to true. ```typescript showReferenceNumberField: { _type: Type.Boolean, _description: 'Show reference number field in order forms', _default: true } ``` -------------------------------- ### Save Patient Immunization Function Source: https://context7.com/openmrs/openmrs-esm-patient-chart/llms.txt Saves or updates a patient's immunization record using FHIR resources. It requires patient details, vaccine information, administration date, and optionally an existing immunization UUID for updates. An AbortController can be used to cancel the request. ```typescript import { savePatientImmunization } from '@openmrs/esm-patient-immunizations-app'; async function recordImmunization( patientUuid: string, vaccineCode: string, vaccineName: string, administrationDate: Date, existingImmunizationUuid?: string ) { const abortController = new AbortController(); const immunizationResource = { resourceType: 'Immunization', status: 'completed', vaccineCode: { coding: [{ code: vaccineCode, display: vaccineName, }], }, patient: { reference: `Patient/${patientUuid}`, }, occurrenceDateTime: administrationDate.toISOString(), protocolApplied: [{ doseNumberPositiveInt: 1, }], }; try { const response = await savePatientImmunization( immunizationResource, existingImmunizationUuid, // null for new, uuid for update abortController ); console.log('Immunization saved:', response.data); return response.data; } catch (error) { console.error('Failed to save immunization:', error); throw error; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.