@eka-care/medical-records-ui 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/{OriginalRecordPanel-AUP6VLET.mjs → OriginalRecordPanel-4R3V6JTK.mjs} +2 -2
  2. package/dist/{OriginalRecordPanel-SFWXUBXU.js → OriginalRecordPanel-CVP7VB64.js} +3 -3
  3. package/dist/{OriginalRecordPanel-SFWXUBXU.js.map → OriginalRecordPanel-CVP7VB64.js.map} +1 -1
  4. package/dist/{VisitDayPanel-CHYCA3SZ.mjs → VisitDayPanel-H4S7MSB7.mjs} +5 -5
  5. package/dist/{VisitDayPanel-M5DMZSRU.js → VisitDayPanel-UUV4ZEMW.js} +6 -6
  6. package/dist/{VisitDayPanel-M5DMZSRU.js.map → VisitDayPanel-UUV4ZEMW.js.map} +1 -1
  7. package/dist/VisitOriginalPanel-QVVSBTAG.js +12 -0
  8. package/dist/{VisitOriginalPanel-F5RCWGHG.js.map → VisitOriginalPanel-QVVSBTAG.js.map} +1 -1
  9. package/dist/{VisitOriginalPanel-UQBFTG76.mjs → VisitOriginalPanel-SE6E5GE6.mjs} +3 -3
  10. package/dist/VisitRecordPanel-QXN52IHI.js +13 -0
  11. package/dist/{VisitRecordPanel-MLIDU4M5.js.map → VisitRecordPanel-QXN52IHI.js.map} +1 -1
  12. package/dist/{VisitRecordPanel-YVLIJOQV.mjs → VisitRecordPanel-WE7ALBUN.mjs} +4 -4
  13. package/dist/{VitalHistoryPanel-S6KUHCK4.js → VitalHistoryPanel-MXTECLVK.js} +4 -4
  14. package/dist/{VitalHistoryPanel-S6KUHCK4.js.map → VitalHistoryPanel-MXTECLVK.js.map} +1 -1
  15. package/dist/{VitalHistoryPanel-OQYGCHDW.mjs → VitalHistoryPanel-TKO7TFBB.mjs} +3 -3
  16. package/dist/{chunk-YMGWHNBK.js → chunk-4OSRKXYT.js} +3 -3
  17. package/dist/{chunk-YMGWHNBK.js.map → chunk-4OSRKXYT.js.map} +1 -1
  18. package/dist/{chunk-CQYOLK77.mjs → chunk-6HC4JPEG.mjs} +2 -2
  19. package/dist/{chunk-GAB2FVV2.mjs → chunk-B6QXGDQZ.mjs} +1 -1
  20. package/dist/{chunk-GAB2FVV2.mjs.map → chunk-B6QXGDQZ.mjs.map} +1 -1
  21. package/dist/{chunk-KIC2MTOE.mjs → chunk-BXHDMBMR.mjs} +2 -2
  22. package/dist/{chunk-BVOZVBTG.mjs → chunk-H3CRIWJR.mjs} +5 -5
  23. package/dist/chunk-H3CRIWJR.mjs.map +1 -0
  24. package/dist/{chunk-7TCJUFMK.js → chunk-KJMAPORM.js} +63 -28
  25. package/dist/chunk-KJMAPORM.js.map +1 -0
  26. package/dist/{chunk-PMB6SGPM.js → chunk-NQXDAXN5.js} +3 -3
  27. package/dist/{chunk-PMB6SGPM.js.map → chunk-NQXDAXN5.js.map} +1 -1
  28. package/dist/{chunk-L5BDCHZM.js → chunk-PA6BAC4L.js} +10 -10
  29. package/dist/chunk-PA6BAC4L.js.map +1 -0
  30. package/dist/{chunk-6APN3BLJ.mjs → chunk-S3TDB7TZ.mjs} +62 -27
  31. package/dist/chunk-S3TDB7TZ.mjs.map +1 -0
  32. package/dist/{chunk-KCEHGEHV.js → chunk-ZJMFXE5R.js} +1 -1
  33. package/dist/{chunk-KCEHGEHV.js.map → chunk-ZJMFXE5R.js.map} +1 -1
  34. package/dist/index.css +21 -0
  35. package/dist/index.css.map +1 -1
  36. package/dist/index.d.mts +2 -0
  37. package/dist/index.d.ts +2 -0
  38. package/dist/index.js +53 -58
  39. package/dist/index.js.map +1 -1
  40. package/dist/index.mjs +30 -35
  41. package/dist/index.mjs.map +1 -1
  42. package/dist/styles.css +21 -0
  43. package/dist/styles.css.map +1 -1
  44. package/package.json +1 -1
  45. package/dist/VisitOriginalPanel-F5RCWGHG.js +0 -12
  46. package/dist/VisitRecordPanel-MLIDU4M5.js +0 -13
  47. package/dist/chunk-6APN3BLJ.mjs.map +0 -1
  48. package/dist/chunk-7TCJUFMK.js.map +0 -1
  49. package/dist/chunk-BVOZVBTG.mjs.map +0 -1
  50. package/dist/chunk-L5BDCHZM.js.map +0 -1
  51. /package/dist/{OriginalRecordPanel-AUP6VLET.mjs.map → OriginalRecordPanel-4R3V6JTK.mjs.map} +0 -0
  52. /package/dist/{VisitDayPanel-CHYCA3SZ.mjs.map → VisitDayPanel-H4S7MSB7.mjs.map} +0 -0
  53. /package/dist/{VisitOriginalPanel-UQBFTG76.mjs.map → VisitOriginalPanel-SE6E5GE6.mjs.map} +0 -0
  54. /package/dist/{VisitRecordPanel-YVLIJOQV.mjs.map → VisitRecordPanel-WE7ALBUN.mjs.map} +0 -0
  55. /package/dist/{VitalHistoryPanel-OQYGCHDW.mjs.map → VitalHistoryPanel-TKO7TFBB.mjs.map} +0 -0
  56. /package/dist/{chunk-CQYOLK77.mjs.map → chunk-6HC4JPEG.mjs.map} +0 -0
  57. /package/dist/{chunk-KIC2MTOE.mjs.map → chunk-BXHDMBMR.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/medical-records-ui/medical-records-ui/dist/chunk-PMB6SGPM.js","../src/visits/components/VisitOriginalPanel.tsx","../src/visits/connection/usePrescription.ts","../src/visits/prescription/fhir-utils.ts","../src/visits/prescription/classify.ts","../src/visits/prescription/header.ts","../src/visits/prescription/mappers/observations.ts","../src/visits/prescription/mappers/care-plans.ts","../src/visits/prescription/config.ts","../src/visits/prescription/mappers/conditions.ts","../src/visits/prescription/mappers/history-extras.ts","../src/visits/prescription/mappers/service-requests.ts","../src/visits/prescription/mappers/medications.ts","../src/visits/prescription/mappers/follow-up.ts","../src/visits/prescription/convert-prescription.ts","../src/visits/hooks/usePdfHref.ts"],"names":[],"mappings":"AAAA,+8BAAY;AACZ;AACE;AACF,sDAA4B;AAC5B;AACE;AACA;AACA;AACA;AACA;AACF,sDAA4B;AAC5B;AACA;ACVA,8BAAwC;AACxC,2CA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E,QAAA;AAIJ,MAAA;AACA,sBAAA;AAKF,IAAA;AAEA,oBAAA;AACc,MAAA;AAKA,MAAA;AAER,wBAAA;AAGA,wBAAA;AAGF,MAAA;AAEU,MAAA;AAKA,MAAA;AAOd,IAAA;AACF,EAAA;AAEJ;ADqxBiB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/medical-records-ui/medical-records-ui/dist/chunk-PMB6SGPM.js","sourcesContent":[null,"\"use client\";\n\nimport { lazy, Suspense, useMemo } from \"react\";\nimport { ChevronLeft, ExternalLink, LoaderCircle } from \"lucide-react\";\nimport { useStore } from \"zustand\";\nimport { useSdk } from \"../../connection/useSdk\";\nimport type { PreviewFile } from \"../../connection/useRecordPreview\";\nimport { useSmartRecordsActions } from \"../../views/context/SmartRecordsActionsContext\";\nimport { IconButton, Typography } from \"widgets\";\nimport { usePrescription } from \"../connection/usePrescription\";\nimport { usePdfHref } from \"../hooks/usePdfHref\";\nimport { isoToDisplayDate } from \"../prescription/fhir-utils\";\n\nconst DocumentViewer = lazy(() =>\n import(\"../../views/RecordPreview/DocumentViewer\").then((m) => ({ default: m.DocumentViewer })),\n);\n\ninterface VisitOriginalPanelProps {\n appointmentId: string;\n onBack?: () => void;\n}\n\nexport function VisitOriginalPanel({ appointmentId, onBack }: VisitOriginalPanelProps) {\n const { store } = useSdk();\n const { hideOpenInNewTab } = useSmartRecordsActions();\n const visit = useStore(store, (s) => s.visits.byId[appointmentId]);\n const { status, retry, conversion } = usePrescription(visit?.prescriptionId ?? null);\n const header = conversion?.header ?? null;\n const pdfHref = usePdfHref(header?.pdfUrl ?? null, header?.pdfBase64 ?? null);\n const hasPdf = !!(header?.pdfUrl || header?.pdfBase64);\n\n const files = useMemo<PreviewFile[]>(() => (pdfHref ? [{ url: pdfHref, kind: \"pdf\" }] : []), [pdfHref]);\n const date = isoToDisplayDate(header?.date ?? null);\n\n const openInNewTab = () => {\n if (pdfHref) window.open(pdfHref, \"_blank\", \"noopener,noreferrer\");\n };\n\n return (\n <div className=\"mr-sv__panel\">\n <div className=\"mr-sv__panel-header mr-orig__panel-header\">\n {onBack && (\n <button type=\"button\" className=\"mr-sv__back-btn\" onClick={onBack}>\n <ChevronLeft size={16} aria-hidden />\n Back\n </button>\n )}\n <div className=\"mr-sv__panel-info\">\n <Typography variant=\"label\" as=\"span\" className=\"mr-sv__panel-name\">\n Prescription\n </Typography>\n {date && (\n <Typography variant=\"hint\" as=\"span\" className=\"mr-sv__panel-meta-text\">\n {date}\n </Typography>\n )}\n </div>\n <div className=\"mr-orig__header-actions\">\n {pdfHref && !hideOpenInNewTab && (\n <IconButton icon={<ExternalLink size={16} aria-hidden />} label=\"Open in new tab\" variant=\"ghost\" size=\"sm\" onClick={openInNewTab} />\n )}\n </div>\n </div>\n\n <div className=\"mr-sv__panel-body mr-rx-original\">\n {status === \"loading\" && (\n <div className=\"mr-rx-original__center\">\n <LoaderCircle size={44} className=\"mr-sv__loading-spinner\" aria-hidden />\n </div>\n )}\n {status === \"error\" && (\n <div className=\"mr-rx-original__center\">\n <Typography variant=\"muted\" className=\"mr-sv__panel-empty\">\n Couldn&apos;t load the prescription\n </Typography>\n <button type=\"button\" className=\"mr-sv__ghost-link-btn\" onClick={retry}>\n Retry\n </button>\n </div>\n )}\n {status === \"loaded\" && !hasPdf && (\n <Typography variant=\"muted\" className=\"mr-sv__panel-empty\">\n No original document for this prescription.\n </Typography>\n )}\n {status === \"loaded\" && files.length > 0 && (\n <div className=\"mr-record-preview__body mr-rx-original__viewer\">\n <Suspense fallback={null}>\n <DocumentViewer files={files} title=\"Prescription\" />\n </Suspense>\n </div>\n )}\n </div>\n </div>\n );\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport type { FhirBundle } from '@eka-care/medical-records-ts-sdk';\nimport { getCore, isWorkerReady } from '../../connection/sdkClient';\nimport { convertPrescriptionBundle } from '../prescription/convert-prescription';\nimport type { PrescriptionConversion } from '../prescription/types';\n\nexport type PrescriptionStatus = 'idle' | 'loading' | 'loaded' | 'error';\n\nexport interface PrescriptionState {\n status: PrescriptionStatus;\n bundle: FhirBundle | null;\n conversion: PrescriptionConversion | null;\n error: string | null;\n retry: () => Promise<void>;\n}\n\ntype Entry = { bundle: FhirBundle; conversion: PrescriptionConversion };\ntype Snapshot = Omit<PrescriptionState, 'retry'>;\n\nconst cache = new Map<string, Entry>();\nconst inflight = new Map<string, Promise<Entry>>();\n\nexport function clearPrescriptionCache(): void {\n cache.clear();\n inflight.clear();\n}\n\nfunction fetchEntry(prescriptionId: string): Promise<Entry> {\n const hit = cache.get(prescriptionId);\n if (hit) return Promise.resolve(hit);\n const pending = inflight.get(prescriptionId);\n if (pending) return pending;\n const request = getCore()\n .getPrescriptionBundle({ prescriptionId })\n .then((bundle) => {\n const conversion = convertPrescriptionBundle(bundle);\n const entry = { bundle, conversion };\n if (conversion.diagnostics.length) console.table(conversion.diagnostics);\n cache.set(prescriptionId, entry);\n return entry;\n })\n .finally(() => inflight.delete(prescriptionId));\n inflight.set(prescriptionId, request);\n return request;\n}\n\nexport async function prefetchPrescription(prescriptionId: string | null | undefined): Promise<void> {\n if (!prescriptionId || !isWorkerReady()) return;\n try {\n await fetchEntry(prescriptionId);\n } catch {\n // the record panel reports the error when it is actually opened\n }\n}\n\nconst IDLE: Snapshot = { status: 'idle', bundle: null, conversion: null, error: null };\n\nconst loaded = (entry: Entry): Snapshot => ({ status: 'loaded', bundle: entry.bundle, conversion: entry.conversion, error: null });\n\nasync function resolve(prescriptionId: string | null, isCurrent: () => boolean, set: (s: Snapshot) => void): Promise<void> {\n if (!prescriptionId || !isWorkerReady()) {\n set(IDLE);\n return;\n }\n const hit = cache.get(prescriptionId);\n if (hit) {\n set(loaded(hit));\n return;\n }\n set({ status: 'loading', bundle: null, conversion: null, error: null });\n try {\n const entry = await fetchEntry(prescriptionId);\n if (isCurrent()) set(loaded(entry));\n } catch (e) {\n if (isCurrent()) set({ status: 'error', bundle: null, conversion: null, error: e instanceof Error ? e.message : 'Failed to load prescription' });\n }\n}\n\nexport function usePrescription(prescriptionId: string | null): PrescriptionState {\n const [state, setState] = useState<Snapshot>(() => {\n const hit = prescriptionId ? cache.get(prescriptionId) : undefined;\n return hit ? loaded(hit) : IDLE;\n });\n const requestRef = useRef(0);\n\n const start = useCallback(() => {\n const request = ++requestRef.current;\n return resolve(prescriptionId, () => requestRef.current === request, setState);\n }, [prescriptionId]);\n\n useEffect(() => {\n void start();\n }, [start]);\n\n return { ...state, retry: start };\n}\n","import type { FhirResource, fhir4 } from '@eka-care/medical-records-ts-sdk';\n\n\nconst EKA_SYSTEM = /eka\\.care/i;\nconst SNOMED_SYSTEM = /snomed/i;\n\nexport function codings(cc: fhir4.CodeableConcept | undefined | null): fhir4.Coding[] {\n return Array.isArray(cc?.coding) ? cc!.coding.filter((c): c is fhir4.Coding => !!c && typeof c === 'object') : [];\n}\n\n// All codings across a resource's category list\nexport function categoryCodings(categories: fhir4.CodeableConcept[] | undefined | null): fhir4.Coding[] {\n return Array.isArray(categories) ? categories.flatMap(codings) : [];\n}\n\n// Category free-text labels, e.g. \"custom_section\"\nexport function categoryTexts(categories: fhir4.CodeableConcept[] | undefined | null): string[] {\n return Array.isArray(categories) ? categories.map((c) => c?.text).filter((t): t is string => typeof t === 'string') : [];\n}\n\nexport function hasCode(list: fhir4.Coding[], code: string): boolean {\n return list.some((c) => c.code === code);\n}\n\nexport function hasDisplay(list: fhir4.Coding[], display: string): boolean {\n const want = display.toLowerCase();\n return list.some((c) => (c.display ?? '').toLowerCase() === want);\n}\n\n// Display name of a concept, preferring Eka's own wording, then SNOMED, then anything, then the text\nexport function conceptDisplay(cc: fhir4.CodeableConcept | undefined | null): string | null {\n const list = codings(cc);\n const pick =\n list.find((c) => EKA_SYSTEM.test(c.system ?? '') && c.display) ??\n list.find((c) => SNOMED_SYSTEM.test(c.system ?? '') && c.display) ??\n list.find((c) => c.display);\n return pick?.display?.trim() || cc?.text?.trim() || null;\n}\n\nconst MDB_SYSTEM = /eka\\.care\\/(mdb|medication|service)|mdb\\.eka\\.care/i;\n\n// The eka master-database id (d-…, b-…, lp-…); local codes from parchi do not count\nexport function ekaCode(cc: fhir4.CodeableConcept | undefined | null): string | null {\n return codings(cc).find((c) => MDB_SYSTEM.test(c.system ?? '') && c.code)?.code ?? null;\n}\n\nexport function snomedCode(cc: fhir4.CodeableConcept | undefined | null): string | null {\n return codings(cc).find((c) => SNOMED_SYSTEM.test(c.system ?? '') && c.code)?.code ?? null;\n}\n\nexport function entityCodes(cc: fhir4.CodeableConcept | undefined | null): { eka_code: string; snomed_code: string } {\n return { eka_code: ekaCode(cc) ?? '', snomed_code: snomedCode(cc) ?? '' };\n}\n\n// \"102 C\" from a Quantity; null when there is no numeric value\nexport function quantityText(q: fhir4.Quantity | undefined | null): string | null {\n if (!q || typeof q.value !== 'number' || Number.isNaN(q.value)) return null;\n const unit = (q.unit ?? q.code ?? '').trim();\n return unit ? `${q.value} ${unit}` : String(q.value);\n}\n\nexport function quantityValue(q: fhir4.Quantity | undefined | null): string | null {\n return q && typeof q.value === 'number' && !Number.isNaN(q.value) ? String(q.value) : null;\n}\n\nexport function quantityUnit(q: fhir4.Quantity | undefined | null): string | null {\n const unit = (q?.unit ?? q?.code ?? '').trim();\n return unit || null;\n}\n\nexport function noteText(notes: fhir4.Annotation[] | undefined | null): string | null {\n if (!Array.isArray(notes)) return null;\n const text = notes.map((n) => n?.text?.trim()).filter(Boolean).join('\\n');\n return text || null;\n}\n\n// Extension value by url, e.g. the eka care-context id\nexport function extensionString(ext: fhir4.Extension[] | undefined | null, url: string): string | null {\n return Array.isArray(ext) ? ext.find((e) => e?.url === url)?.valueString ?? null : null;\n}\n\nexport function isoToDisplayDate(iso: string | undefined | null): string | null {\n if (!iso) return null;\n const dayOnly = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(iso.trim());\n const d = dayOnly ? new Date(Number(dayOnly[1]), Number(dayOnly[2]) - 1, Number(dayOnly[3])) : new Date(Date.parse(iso));\n if (Number.isNaN(d.getTime())) return null;\n return `${String(d.getDate()).padStart(2, '0')} ${d.toLocaleString('en', { month: 'short' })} ${d.getFullYear()}`;\n}\n\n\nexport function compositionSectionMap(resources: FhirResource[]): Map<string, string> {\n const map = new Map<string, string>();\n const composition = resources.find((r) => r?.resourceType === 'Composition') as fhir4.Composition | undefined;\n for (const section of composition?.section ?? []) {\n const code = codings(section?.code).find((c) => c.code)?.code;\n if (!code) continue;\n for (const entry of section.entry ?? []) {\n if (entry?.reference) map.set(entry.reference, code);\n }\n }\n return map;\n}\n","import type { FhirResource, fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport { categoryCodings, categoryTexts, codings, hasCode, hasDisplay } from './fhir-utils';\n\n/** The piles a bundle card can land in. Anything else is deliberately ignored. */\nexport type Pile =\n | 'header'\n | 'symptoms'\n | 'vitals'\n | 'labResults'\n | 'examination'\n | 'diagnosis'\n | 'history'\n | 'medications'\n | 'labInvestigations'\n | 'procedures'\n | 'advice'\n | 'clinicalNote'\n | 'notes'\n | 'customSection'\n | 'followUp'\n | 'referral'\n | 'ipAdmission';\n\nconst HEADER_TYPES = new Set(['Composition', 'Encounter', 'Patient', 'Practitioner', 'Organization', 'DocumentReference']);\nconst HISTORY_TYPES = new Set(['FamilyMemberHistory', 'Procedure', 'AllergyIntolerance']);\n\n// Codes the Eka FHIR spec allows for a symptom's category, besides the plain \"symptom\"\nconst SYMPTOM_CODES = ['symptom', '418799008', 's-8068301606'];\nconst SNOMED_MEDICAL_ADVICE = '386464006';\nconst SNOMED_CLINICAL_NOTE = '371530004';\nconst SNOMED_PATIENT_REFERRAL = '3457005';\n\nconst SECTION_PILES: Record<string, Pile> = {\n '422843007': 'symptoms', // Chief Complaints\n '371529009': 'history', // Medical History\n '722446000': 'history', // Allergies\n '282291009': 'diagnosis', // Diagnosis\n};\n\nfunction classifyObservation(r: fhir4.Observation): Pile | null {\n const cats = categoryCodings(r.category);\n if (hasCode(cats, 'vital-signs')) return 'vitals';\n if (hasCode(cats, 'exam')) return 'examination';\n if (hasCode(cats, 'social-history')) return 'history';\n if (hasCode(cats, 'laboratory')) return 'labResults';\n if (hasCode(cats, 'survey')) return 'notes';\n if (SYMPTOM_CODES.some((code) => hasCode(cats, code))) return 'symptoms';\n return null;\n}\n\n// A Condition's category cannot tell a symptom from a history item; the Composition section can\nfunction classifyCondition(r: fhir4.Condition, sectionCode?: string): Pile | null {\n const bySection = sectionCode ? SECTION_PILES[sectionCode] : undefined;\n if (bySection) return bySection;\n const cats = categoryCodings(r.category);\n if (hasCode(cats, 'encounter-diagnosis')) return 'diagnosis';\n if (hasCode(cats, 'problem-list-item')) return 'history';\n return null;\n}\n\nfunction classifyServiceRequest(r: fhir4.ServiceRequest): Pile | null {\n const cats = categoryCodings(r.category);\n if (hasDisplay(cats, 'Laboratory procedure') || hasCode(cats, '108252007')) return 'labInvestigations';\n if (hasDisplay(cats, 'Surgical procedure') || hasCode(cats, '387713003')) return 'procedures';\n if (hasDisplay(cats, 'Patient referral') || hasCode(cats, SNOMED_PATIENT_REFERRAL)) {\n return /hospital admission/i.test(r.code?.text ?? '') ? 'ipAdmission' : 'referral';\n }\n return null;\n}\n\n// Category first; the spec's intent values (plan = advice, proposal = note) are the fallback\nfunction classifyCarePlan(r: fhir4.CarePlan): Pile | null {\n if (categoryTexts(r.category).includes('custom_section')) return 'customSection';\n const cats = categoryCodings(r.category);\n if (hasCode(cats, SNOMED_MEDICAL_ADVICE) || hasDisplay(cats, 'Medical advice')) return 'advice';\n if (hasCode(cats, SNOMED_CLINICAL_NOTE) || hasDisplay(cats, 'Clinical note')) return 'clinicalNote';\n if (r.intent === 'plan') return 'advice';\n if (r.intent === 'proposal') return 'clinicalNote';\n return null;\n}\n\nfunction classifyAppointment(r: fhir4.Appointment): Pile | null {\n const types = codings(r.appointmentType);\n if (!types.length) return 'followUp';\n return hasCode(types, 'FOLLOWUP') || hasCode(types, 'FU') ? 'followUp' : null;\n}\n\n/** Decides which pile a bundle card belongs to; null means \"ignore on purpose\". Never throws. */\nexport function classifyResource(resource: FhirResource | null | undefined, sectionCode?: string): Pile | null {\n if (!resource || typeof resource !== 'object' || typeof resource.resourceType !== 'string') return null;\n const type = resource.resourceType;\n if (HEADER_TYPES.has(type)) return 'header';\n if (HISTORY_TYPES.has(type)) return 'history';\n switch (type) {\n case 'Observation':\n return classifyObservation(resource as fhir4.Observation);\n case 'Condition':\n return classifyCondition(resource as fhir4.Condition, sectionCode);\n case 'ServiceRequest':\n return classifyServiceRequest(resource as fhir4.ServiceRequest);\n case 'CarePlan':\n return classifyCarePlan(resource as fhir4.CarePlan);\n case 'MedicationRequest':\n return 'medications';\n case 'Appointment':\n return classifyAppointment(resource as fhir4.Appointment);\n default:\n return null;\n }\n}\n","import type { FhirResource, fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport type { PrescriptionHeader } from './types';\nimport { extensionString } from './fhir-utils';\n\nconst CARE_CONTEXT_EXTENSION = 'https://eka.care/care_context_id';\n\nconst byType = <T extends FhirResource>(resources: FhirResource[], type: T['resourceType']): T | undefined =>\n resources.find((r) => r?.resourceType === type) as T | undefined;\n\n// Who, when and the original document: read from the Composition, Patient, Practitioner and DocumentReference cards\nexport function buildHeader(resources: FhirResource[]): PrescriptionHeader {\n const composition = byType<fhir4.Composition>(resources, 'Composition');\n const encounter = byType<fhir4.Encounter>(resources, 'Encounter');\n const patient = byType<fhir4.Patient>(resources, 'Patient');\n const practitioner = byType<fhir4.Practitioner>(resources, 'Practitioner');\n const document = byType<fhir4.DocumentReference>(resources, 'DocumentReference');\n const attachment = document?.content?.[0]?.attachment;\n const author = composition?.author?.[0];\n return {\n prescriptionId: composition?.identifier?.value ?? null,\n date: composition?.date ?? encounter?.period?.start ?? null,\n doctorName: author?.display ?? practitioner?.name?.[0]?.text ?? null,\n doctorId: practitioner?.id ?? author?.reference?.split('/').pop() ?? null,\n patientName: patient?.name?.[0]?.text ?? composition?.subject?.display ?? null,\n patientId: patient?.id ?? composition?.subject?.reference?.split('/').pop() ?? null,\n careContextId: extensionString(composition?.extension, CARE_CONTEXT_EXTENSION) ?? extensionString(encounter?.extension, CARE_CONTEXT_EXTENSION),\n pdfUrl: attachment?.url ?? null,\n pdfBase64: attachment?.data ?? null,\n };\n}\n","import type { fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport { conceptDisplay, entityCodes, noteText, quantityUnit, quantityValue } from '../fhir-utils';\nimport type { EntityCodes } from '../types';\n\nexport function symptomItem(r: fhir4.Observation | fhir4.Condition): { item: string; codes: EntityCodes } | null {\n const item = conceptDisplay(r.code);\n return item ? { item, codes: entityCodes(r.code) } : null;\n}\n\n\nexport function vitalRow(obs: fhir4.Observation): Record<string, string> | null {\n const name = conceptDisplay(obs.code);\n if (!name) return null;\n const components = Array.isArray(obs.component) ? obs.component : [];\n const quantities = components.length\n ? components.map((c) => c?.valueQuantity).filter((q): q is fhir4.Quantity => !!q)\n : obs.valueQuantity\n ? [obs.valueQuantity]\n : [];\n const values = quantities.map(quantityValue).filter((v): v is string => v !== null);\n const value = values.length ? values.join('/') : (obs.valueString?.trim() ?? conceptDisplay(obs.valueCodeableConcept) ?? '');\n return {\n vital_name: name,\n value,\n unit: quantityUnit(quantities[0]) ?? '',\n normal_range: '',\n notes: noteText(obs.note) ?? '',\n ...entityCodes(obs.code),\n };\n}\n\nconst EXAM_STATUS: Record<string, string> = { POS: 'present', NEG: 'absent', A: 'abnormal', N: 'normal' };\n\nexport function examinationRow(obs: fhir4.Observation): Record<string, string> | null {\n const finding = conceptDisplay(obs.code);\n if (!finding) return null;\n const interpretation = Array.isArray(obs.interpretation) ? obs.interpretation[0]?.coding?.[0]?.code ?? '' : '';\n const status = EXAM_STATUS[interpretation] ?? obs.valueString?.trim().toLowerCase() ?? '';\n return { finding, status, detail: noteText(obs.note) ?? '', ...entityCodes(obs.code) };\n}\n\nexport function socialHistoryRow(obs: fhir4.Observation): Record<string, string> | null {\n const condition = conceptDisplay(obs.code);\n if (!condition) return null;\n return {\n condition,\n category: 'lifestyle_habit',\n status: obs.valueString?.trim() ?? conceptDisplay(obs.valueCodeableConcept) ?? '',\n since: '',\n note: noteText(obs.note) ?? '',\n ...entityCodes(obs.code),\n };\n}\n\nconst INTERPRETATION: Record<string, string> = { H: 'High', HH: 'High', L: 'Low', LL: 'Low', A: 'Abnormal', AA: 'Abnormal', N: 'Normal' };\n\nfunction referenceRangeText(obs: fhir4.Observation): string {\n const range = Array.isArray(obs.referenceRange) ? obs.referenceRange[0] : undefined;\n if (!range) return '';\n const low = quantityValue(range.low);\n const high = quantityValue(range.high);\n if (low && high) return `${low} - ${high}`;\n return range.text?.trim() ?? (low ? `> ${low}` : high ? `< ${high}` : '');\n}\n\nexport function labResultRow(obs: fhir4.Observation): Record<string, string> | null {\n const test_name = conceptDisplay(obs.code);\n const value = quantityValue(obs.valueQuantity) ?? obs.valueString?.trim() ?? conceptDisplay(obs.valueCodeableConcept);\n if (!test_name || !value) return null;\n const interpretation = Array.isArray(obs.interpretation) ? obs.interpretation[0] : undefined;\n const code = interpretation?.coding?.[0]?.code ?? '';\n return {\n test_name,\n value,\n unit: quantityUnit(obs.valueQuantity) ?? '',\n reference_range: referenceRangeText(obs),\n out_of_range: INTERPRETATION[code] ?? conceptDisplay(interpretation) ?? '',\n ...entityCodes(obs.code),\n };\n}\n","import type { fhir4 } from '@eka-care/medical-records-ts-sdk';\n\n// Narrative of an advice or clinical-note CarePlan, HTML stripped\nexport function carePlanText(cp: fhir4.CarePlan): string | null {\n const text = (cp.description ?? cp.title ?? '').replace(/<[^>]+>/g, '').trim();\n return text || null;\n}\n\n// Custom-section notes arrive as a Python dict dump: {'id':'…','name':'Dolo','value':'Wrd','value_html':null}\n// Python switches to double quotes when the string holds an apostrophe, so both quote styles are accepted\nconst PY_STRING = `'((?:[^'\\\\\\\\]|\\\\\\\\.)*)'|\"((?:[^\"\\\\\\\\]|\\\\\\\\.)*)\"`;\nconst NAME_RE = new RegExp(`['\"]name['\"]\\\\s*:\\\\s*(?:${PY_STRING})`);\nconst VALUE_RE = new RegExp(`['\"]value['\"]\\\\s*:\\\\s*(?:${PY_STRING}|None|null)`);\n\nfunction unescape(text: string): string {\n return text.replace(/\\\\'/g, \"'\").replace(/\\\\\"/g, '\"').replace(/\\\\n/g, '\\n').trim();\n}\n\n// The matched string from either quote style\nfunction matched(m: RegExpExecArray | null): string | null {\n if (!m) return null;\n return m[1] ?? m[2] ?? '';\n}\n\n// One name/value pair from a note; null when the note holds no such pair\nexport function parseCustomPair(text: string | undefined | null): { key: string; value: string } | null {\n if (!text) return null;\n try {\n const parsed = JSON.parse(text) as { name?: unknown; value?: unknown };\n if (parsed && typeof parsed === 'object' && typeof parsed.name === 'string') {\n return { key: parsed.name.trim(), value: typeof parsed.value === 'string' ? parsed.value.trim() : '' };\n }\n } catch {\n // not JSON; fall through to the Python-style form\n }\n const name = matched(NAME_RE.exec(text));\n if (name === null) return null;\n const value = matched(VALUE_RE.exec(text));\n return { key: unescape(name), value: value ? unescape(value) : '' };\n}\n\n// Every note as a pair; a note that cannot be parsed is kept verbatim as the key so nothing is silently lost\nexport function customSectionItems(cp: fhir4.CarePlan): { key: string; value: string }[] {\n const notes = Array.isArray(cp.note) ? cp.note : [];\n return notes\n .map((n) => parseCustomPair(n?.text) ?? { key: (n?.text ?? '').trim(), value: '' })\n .filter((pair) => pair.key !== '' || pair.value !== '');\n}\n\nexport function customSectionTitle(cp: fhir4.CarePlan): string {\n return (cp.title ?? cp.description ?? 'Custom section').replace(/<[^>]+>/g, '').trim() || 'Custom section';\n}\n","export const SHOW_CUSTOM_SECTIONS = true;\n","import type { fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport { codings, conceptDisplay, ekaCode, entityCodes, isoToDisplayDate, noteText, snomedCode } from '../fhir-utils';\n\nconst SEVERITY_BY_SNOMED: Record<string, string> = { '24484000': 'Severe', '6736007': 'Moderate', '255604002': 'Mild' };\n\nfunction firstCode(cc: fhir4.CodeableConcept | undefined): string {\n return (codings(cc)[0]?.code ?? '').toLowerCase();\n}\n\nexport function diagnosisStatus(cond: fhir4.Condition): 'Confirmed' | 'Suspected' | 'Resolved' | 'Ruled out' {\n const clinical = firstCode(cond.clinicalStatus);\n const verification = firstCode(cond.verificationStatus);\n if (verification === 'refuted' || clinical === 'inactive') return 'Ruled out';\n if (['resolved', 'remission'].includes(clinical)) return 'Resolved';\n if (['provisional', 'unconfirmed', 'differential'].includes(verification) || clinical === 'unknown') return 'Suspected';\n return 'Confirmed';\n}\n\nexport function presenceToken(clinical: string, verification: string): string {\n if (verification === 'refuted') return 'no';\n if (clinical === 'active' || clinical === 'recurrence' || clinical === 'relapse' || verification === 'confirmed') return 'yes';\n return '';\n}\n\n// Onset may be a date, a period, an age or free text\nexport function onsetText(cond: fhir4.Condition): string {\n if (cond.onsetDateTime) return isoToDisplayDate(cond.onsetDateTime) ?? cond.onsetDateTime;\n if (cond.onsetPeriod?.start) return isoToDisplayDate(cond.onsetPeriod.start) ?? cond.onsetPeriod.start;\n if (cond.onsetAge && typeof cond.onsetAge.value === 'number') return `${cond.onsetAge.value} ${cond.onsetAge.unit ?? cond.onsetAge.code ?? ''}`.trim();\n if (typeof cond.onsetString === 'string') return cond.onsetString.trim();\n return '';\n}\n\nexport function severityText(cond: fhir4.Condition): string {\n const code = snomedCode(cond.severity);\n return (code && SEVERITY_BY_SNOMED[code]) || conceptDisplay(cond.severity) || '';\n}\n\n// A diagnosis of this visit, in the editor's DIAGNOSIS row shape\nexport function diagnosisRow(cond: fhir4.Condition): Record<string, string> | null {\n const name = conceptDisplay(cond.code);\n if (!name) return null;\n const row: Record<string, string> = {\n diagnosis: name,\n diagnosis_id: ekaCode(cond.code) ?? '',\n eka_code: ekaCode(cond.code) ?? '',\n icd10_code: '',\n icd10_name: '',\n snomed_code: snomedCode(cond.code) ?? '',\n status: diagnosisStatus(cond),\n };\n const since = onsetText(cond);\n const severity = severityText(cond);\n const notes = noteText(cond.note);\n if (since) row.since = since;\n if (severity) row.severity = severity;\n if (notes) row.notes = notes;\n return row;\n}\n\n// A known condition the patient carries, in the editor's PATIENT_MEDICAL_HISTORY row shape\nexport function historyRowFromCondition(cond: fhir4.Condition): Record<string, string> | null {\n const condition = conceptDisplay(cond.code);\n if (!condition) return null;\n return {\n condition,\n category: 'condition',\n status: presenceToken(firstCode(cond.clinicalStatus), firstCode(cond.verificationStatus)),\n since: onsetText(cond),\n note: noteText(cond.note) ?? '',\n ...entityCodes(cond.code),\n };\n}\n","import type { fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport { codings, conceptDisplay, entityCodes, isoToDisplayDate, noteText } from '../fhir-utils';\nimport { presenceToken } from './conditions';\n\nexport function familyHistoryRows(fmh: fhir4.FamilyMemberHistory): Record<string, string>[] {\n const relation = conceptDisplay(fmh.relationship) ?? '';\n const notes = noteText(fmh.note) ?? '';\n const note = [relation, notes].filter(Boolean).join('. ');\n const conditions = Array.isArray(fmh.condition) ? fmh.condition : [];\n return conditions\n .filter((c) => !!conceptDisplay(c?.code))\n .map((c) => ({ condition: conceptDisplay(c.code)!, category: 'family_history', status: '', since: '', note, ...entityCodes(c.code) }));\n}\n\nexport function pastProcedureRow(proc: fhir4.Procedure): Record<string, string> | null {\n const condition = conceptDisplay(proc.code);\n if (!condition) return null;\n const performed = proc.performedDateTime ?? proc.performedPeriod?.start ?? null;\n return {\n condition,\n category: 'past_procedure',\n status: '',\n since: (performed && isoToDisplayDate(performed)) ?? '',\n note: noteText(proc.note) ?? '',\n ...entityCodes(proc.code),\n };\n}\n\nexport function allergyRow(allergy: fhir4.AllergyIntolerance): Record<string, string> | null {\n const condition = conceptDisplay(allergy.code);\n if (!condition) return null;\n const kinds = Array.isArray(allergy.category) ? allergy.category : [];\n return {\n condition,\n category: kinds.includes('medication') ? 'drug_allergy' : 'other_allergy',\n status: presenceToken(codings(allergy.clinicalStatus)[0]?.code ?? '', codings(allergy.verificationStatus)[0]?.code ?? ''),\n since: allergy.onsetDateTime ? (isoToDisplayDate(allergy.onsetDateTime) ?? '') : '',\n note: noteText(allergy.note) ?? '',\n ...entityCodes(allergy.code),\n };\n}\n","import type { fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport { conceptDisplay, entityCodes, noteText } from '../fhir-utils';\n\nexport function labInvestigationRow(sr: fhir4.ServiceRequest): Record<string, string> | null {\n const investigation = conceptDisplay(sr.code);\n if (!investigation) return null;\n const codes = entityCodes(sr.code);\n return { investigation, investigationId: codes.eka_code, ekaId: codes.eka_code, ...codes, test_on: '', repeat_on: '', remarks: noteText(sr.note) ?? '' };\n}\n\nexport function procedureRow(sr: fhir4.ServiceRequest): Record<string, string> | null {\n const procedure_name = conceptDisplay(sr.code);\n if (!procedure_name) return null;\n return { procedure_name, timing: '', note: noteText(sr.note) ?? '', ...entityCodes(sr.code) };\n}\n\nexport function referralRow(sr: fhir4.ServiceRequest): Record<string, string> | null {\n const referred_to = sr.code?.text?.trim() || conceptDisplay(sr.code);\n if (!referred_to) return null;\n return { referred_to, specialty: '', phone: '', hospital: '', notes: noteText(sr.note) ?? '', ...entityCodes(sr.code) };\n}\n\nexport function admissionNotes(sr: fhir4.ServiceRequest): string {\n return noteText(sr.note) ?? '';\n}\n","import type { fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport { codings, conceptDisplay, ekaCode, entityCodes, noteText, quantityText } from '../fhir-utils';\n\nconst UNIT_WORDS: Record<string, [string, string]> = {\n s: ['second', 'seconds'], min: ['minute', 'minutes'], h: ['hour', 'hours'], d: ['day', 'days'],\n wk: ['week', 'weeks'], mo: ['month', 'months'], a: ['year', 'years'],\n};\n\nfunction durationText(repeat: fhir4.TimingRepeat | undefined): string {\n if (!repeat || typeof repeat.duration !== 'number') return '';\n const unit = repeat.durationUnit ? UNIT_WORDS[repeat.durationUnit] : undefined;\n const word = unit ? (repeat.duration === 1 ? unit[0] : unit[1]) : (repeat.durationUnit ?? '');\n return `${repeat.duration} ${word}`.trim();\n}\n\n// \"1-1-0\" when the doctor wrote one; otherwise derived from the repeat count\nfunction frequencyText(dosage: fhir4.Dosage): string {\n const written = Array.isArray(dosage.additionalInstruction) ? conceptDisplay(dosage.additionalInstruction[0]) : null;\n if (written) return written;\n const f = dosage.timing?.repeat?.frequency;\n return typeof f === 'number' ? `${f} time${f === 1 ? '' : 's'} a day` : '';\n}\n\n// One prescribed medicine, in the editor's MEDICATION_TABLE row shape\nexport function medicationRow(mr: fhir4.MedicationRequest): Record<string, string> | null {\n const drug_name = conceptDisplay(mr.medicationCodeableConcept);\n if (!drug_name) return null;\n const dosage: fhir4.Dosage = Array.isArray(mr.dosageInstruction) ? (mr.dosageInstruction[0] ?? {}) : {};\n const doseQuantity = Array.isArray(dosage.doseAndRate) ? dosage.doseAndRate[0]?.doseQuantity : undefined;\n return {\n drug_name,\n medication_id: ekaCode(mr.medicationCodeableConcept) ?? codings(mr.medicationCodeableConcept)[0]?.code ?? '',\n ...entityCodes(mr.medicationCodeableConcept),\n dosage: quantityText(doseQuantity) ?? '',\n frequency: frequencyText(dosage),\n timing: conceptDisplay(dosage.timing?.code) ?? '',\n duration: durationText(dosage.timing?.repeat),\n route: conceptDisplay(dosage.route) ?? '',\n quantity: quantityText(mr.dispenseRequest?.quantity) ?? '',\n notes: (dosage.text ?? dosage.patientInstruction ?? noteText(mr.note) ?? '').trim(),\n };\n}\n","import type { fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport type { FollowUpPayload } from '../types';\n\nconst DAY_MS = 86_400_000;\n\nexport function followUpPayload(appt: fhir4.Appointment, visitDate: string | null): FollowUpPayload | null {\n const date = (appt.start ?? appt.requestedPeriod?.[0]?.start ?? '').trim();\n if (!date) return null;\n const written = (appt.description ?? '').trim();\n let interval = written && written !== date ? written : '';\n if (!interval) {\n const startMs = Date.parse(date);\n const visitMs = visitDate ? Date.parse(visitDate) : NaN;\n if (!Number.isNaN(startMs) && !Number.isNaN(visitMs)) {\n const days = Math.round((startMs - visitMs) / DAY_MS);\n if (days > 0) interval = `${days} day${days === 1 ? '' : 's'}`;\n }\n }\n return { date, interval, notes: (appt.comment ?? '').trim() };\n}\n","import type { FhirBundle, FhirResource, fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport type { Diagnostic, EntityCodes, IpAdmissionPayload, PrescriptionConversion, PrescriptionSection, TableColumn } from './types';\nimport { classifyResource } from './classify';\nimport { buildHeader } from './header';\nimport { categoryCodings, categoryTexts, codings, compositionSectionMap, conceptDisplay } from './fhir-utils';\nimport { examinationRow, labResultRow, socialHistoryRow, symptomItem, vitalRow } from './mappers/observations';\nimport { carePlanText, customSectionItems, customSectionTitle } from './mappers/care-plans';\nimport { SHOW_CUSTOM_SECTIONS } from './config';\nimport { diagnosisRow, historyRowFromCondition } from './mappers/conditions';\nimport { allergyRow, familyHistoryRows, pastProcedureRow } from './mappers/history-extras';\nimport { admissionNotes, labInvestigationRow, procedureRow, referralRow } from './mappers/service-requests';\nimport { medicationRow } from './mappers/medications';\nimport { followUpPayload } from './mappers/follow-up';\n\ntype Row = Record<string, string>;\n\nconst col = (key: string, label: string, type: TableColumn['type'] = 'text'): TableColumn => ({ key, label, type });\n\nconst VITAL_HEADERS = [col('vital_name', 'Vital Sign'), col('value', 'Value'), col('unit', 'Unit'), col('normal_range', 'Normal Range'), col('notes', 'Notes', 'markdown')];\nconst EXAM_HEADERS = [col('finding', 'Finding'), col('status', 'Status'), col('detail', 'Detail')];\nconst HISTORY_HEADERS = [col('condition', 'Condition'), col('category', 'Category'), col('status', 'Status'), col('since', 'Since'), col('note', 'Note')];\nconst MEDICATION_HEADERS = [col('drug_name', 'Medicine'), col('dosage', 'Dosage'), col('frequency', 'Frequency'), col('timing', 'Timing'), col('duration', 'Duration'), col('route', 'Route'), col('quantity', 'Quantity'), col('notes', 'Instructions')];\nconst LAB_HEADERS = [col('investigation', 'Investigation'), col('test_on', 'Test On'), col('repeat_on', 'Repeat On'), col('remarks', 'Remarks')];\nconst LAB_RESULT_HEADERS = [col('test_name', 'Test Name'), col('value', 'Value'), col('unit', 'Unit'), col('reference_range', 'Reference Range'), col('out_of_range', 'Status')];\nconst PROCEDURE_HEADERS = [col('procedure_name', 'Procedure'), col('timing', 'Timing'), col('note', 'Note')];\nconst REFERRAL_HEADERS = [col('referred_to', 'Doctor name'), col('specialty', 'Speciality'), col('phone', 'Phone number'), col('hospital', 'Hospital'), col('notes', 'Notes')];\nconst DIAGNOSIS_OPTIONAL = [col('since', 'Since'), col('severity', 'Severity'), col('notes', 'Notes')];\n\n// Section key = slug of the display name, the same rule the editor's standard sections follow\nfunction slug(title: string): string {\n return title.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'section';\n}\n\nfunction uniqueKey(base: string, taken: Set<string>): string {\n let key = base;\n for (let n = 2; taken.has(key); n++) key = `${base}_${n}`;\n taken.add(key);\n return key;\n}\n\ntype FoldTarget = 'symptoms' | 'advice' | 'medications' | 'diagnosis' | 'procedures' | 'labInvestigations' | 'labResults' | 'examination' | 'history' | 'vitals' | 'referrals';\nconst FOLD_TARGETS: Record<string, FoldTarget> = {\n 'chief complaint': 'symptoms', 'chief complaints': 'symptoms', symptom: 'symptoms', symptoms: 'symptoms',\n advice: 'advice', advices: 'advice',\n medication: 'medications', medications: 'medications', medicine: 'medications', medicines: 'medications',\n diagnosis: 'diagnosis', diagnoses: 'diagnosis',\n procedure: 'procedures', procedures: 'procedures',\n 'lab investigation': 'labInvestigations', 'lab investigations': 'labInvestigations', investigation: 'labInvestigations', investigations: 'labInvestigations',\n 'lab result': 'labResults', 'lab results': 'labResults',\n 'examination finding': 'examination', 'examination findings': 'examination', examination: 'examination',\n 'patient medical history': 'history', 'medical history': 'history', history: 'history',\n vital: 'vitals', vitals: 'vitals', 'vital sign': 'vitals', 'vital signs': 'vitals',\n referral: 'referrals', referrals: 'referrals',\n};\nfunction foldTargetOf(title: string): FoldTarget | null {\n return FOLD_TARGETS[title.toLowerCase().replace(/[^a-z ]+/g, ' ').replace(/\\s+/g, ' ').trim()] ?? null;\n}\n\nfunction foldedRow(target: FoldTarget, key: string, value: string): Row {\n switch (target) {\n case 'medications': return { drug_name: key, dosage: '', frequency: '', timing: '', duration: '', route: '', quantity: '', notes: value };\n case 'diagnosis': return { diagnosis: key, status: '', notes: value };\n case 'procedures': return { procedure_name: key, timing: '', note: value };\n case 'labInvestigations': return { investigation: key, test_on: '', repeat_on: '', remarks: value };\n case 'labResults': return { test_name: key, value, unit: '', reference_range: '', out_of_range: '' };\n case 'examination': return { finding: key, status: '', detail: value };\n case 'history': return { condition: key, category: 'condition', status: '', since: '', note: value };\n case 'vitals': return { vital_name: key, value, unit: '', normal_range: '', notes: '' };\n default: return { referred_to: key, specialty: '', phone: '', hospital: '', notes: value };\n }\n}\n\nfunction diagnosisHeaders(rows: Row[]): TableColumn[] {\n return [col('diagnosis', 'Diagnosis'), col('status', 'Status'), ...DIAGNOSIS_OPTIONAL.filter((c) => rows.some((r) => r[c.key]))];\n}\n\nfunction unmappedReason(r: FhirResource): string {\n switch (r.resourceType) {\n case 'Observation': {\n const codes = categoryCodings((r as fhir4.Observation).category).map((c) => c.code).filter(Boolean);\n return codes.length ? `Observation category \"${codes.join(', ')}\" is not mapped` : 'Observation has no category';\n }\n case 'Condition':\n return 'Condition has no recognised category';\n case 'ServiceRequest': {\n const labels = categoryCodings((r as fhir4.ServiceRequest).category).map((c) => c.display ?? c.code).filter(Boolean);\n return labels.length ? `ServiceRequest category \"${labels.join(', ')}\" is not mapped` : 'ServiceRequest has no category';\n }\n case 'CarePlan':\n return `CarePlan has no recognised category or intent (${categoryTexts((r as fhir4.CarePlan).category).join(', ') || 'none'})`;\n case 'Appointment': {\n const type = codings((r as fhir4.Appointment).appointmentType)[0]?.code ?? 'none';\n return `Appointment type \"${type}\" is not a follow-up`;\n }\n default:\n return `resource type \"${r.resourceType}\" is not mapped`;\n }\n}\n\nexport interface ConvertOptions {\n showCustomSections?: boolean;\n}\n\nexport function convertPrescriptionBundle(bundle: FhirBundle | null | undefined, options: ConvertOptions = {}): PrescriptionConversion {\n const showCustomSections = options.showCustomSections ?? SHOW_CUSTOM_SECTIONS;\n const entries = Array.isArray(bundle?.entry) ? bundle!.entry : [];\n const resources = entries\n .map((e) => e?.resource)\n .filter((r): r is FhirResource => !!r && typeof r === 'object' && typeof r.resourceType === 'string');\n\n const header = buildHeader(resources);\n const sectionOf = compositionSectionMap(resources);\n const diagnostics: Diagnostic[] = [];\n const report = (r: FhirResource, reason: string) => diagnostics.push({ resourceType: r.resourceType, id: r.id ?? null, reason });\n\n const symptoms: { item: string; codes: EntityCodes }[] = [];\n const vitals: Row[] = [];\n const labResults: Row[] = [];\n const examination: Row[] = [];\n const diagnosis: Row[] = [];\n const history: Row[] = [];\n const medications: Row[] = [];\n const labInvestigations: Row[] = [];\n const procedures: Row[] = [];\n const advice: string[] = [];\n const clinicalNotes: string[] = [];\n const referrals: Row[] = [];\n const admissionNoteLines: string[] = [];\n const customSections: { title: string; items: { key: string; value: string }[] }[] = [];\n let followUp: PrescriptionSection['payload'] | null = null;\n\n const pushRow = (target: Row[], row: Row | null, r: FhirResource) => {\n if (row) target.push(row);\n else report(r, `${r.resourceType} has no display name`);\n };\n\n for (const r of resources) {\n try {\n const pile = classifyResource(r, sectionOf.get(`${r.resourceType}/${r.id ?? ''}`));\n switch (pile) {\n case 'header':\n break;\n case 'symptoms': {\n const symptom = symptomItem(r as fhir4.Observation | fhir4.Condition);\n if (symptom) symptoms.push(symptom);\n else report(r, 'Observation has no display name');\n break;\n }\n case 'vitals':\n pushRow(vitals, vitalRow(r as fhir4.Observation), r);\n break;\n case 'labResults': {\n const row = labResultRow(r as fhir4.Observation);\n if (row) labResults.push(row);\n else report(r, 'Observation \"laboratory\" has no value to show as a lab result');\n break;\n }\n case 'examination':\n pushRow(examination, examinationRow(r as fhir4.Observation), r);\n break;\n case 'diagnosis':\n pushRow(diagnosis, diagnosisRow(r as fhir4.Condition), r);\n break;\n case 'history':\n if (r.resourceType === 'Condition') pushRow(history, historyRowFromCondition(r as fhir4.Condition), r);\n else if (r.resourceType === 'Observation') pushRow(history, socialHistoryRow(r as fhir4.Observation), r);\n else if (r.resourceType === 'FamilyMemberHistory') {\n const rows = familyHistoryRows(r as fhir4.FamilyMemberHistory);\n if (rows.length) history.push(...rows);\n else report(r, 'FamilyMemberHistory has no condition');\n } else if (r.resourceType === 'Procedure') pushRow(history, pastProcedureRow(r as fhir4.Procedure), r);\n else if (r.resourceType === 'AllergyIntolerance') pushRow(history, allergyRow(r as fhir4.AllergyIntolerance), r);\n break;\n case 'medications':\n pushRow(medications, medicationRow(r as fhir4.MedicationRequest), r);\n break;\n case 'labInvestigations':\n pushRow(labInvestigations, labInvestigationRow(r as fhir4.ServiceRequest), r);\n break;\n case 'procedures':\n pushRow(procedures, procedureRow(r as fhir4.ServiceRequest), r);\n break;\n case 'advice': {\n const item = carePlanText(r as fhir4.CarePlan);\n if (item) advice.push(item);\n else report(r, 'CarePlan advice has no text');\n break;\n }\n case 'clinicalNote': {\n const note = carePlanText(r as fhir4.CarePlan);\n if (note) clinicalNotes.push(note);\n else report(r, 'CarePlan clinical note has no text');\n break;\n }\n case 'notes':\n report(r, `free-text note \"${conceptDisplay((r as fhir4.Observation).code) ?? 'Note'}\"; narrative sections are not shown`);\n break;\n case 'referral':\n pushRow(referrals, referralRow(r as fhir4.ServiceRequest), r);\n break;\n case 'ipAdmission':\n admissionNoteLines.push(admissionNotes(r as fhir4.ServiceRequest));\n break;\n case 'customSection': {\n const cp = r as fhir4.CarePlan;\n if (!showCustomSections) report(r, `custom section \"${customSectionTitle(cp)}\" is a doctor-tool section; not shown`);\n else if (!customSectionItems(cp).length) report(r, `custom section \"${customSectionTitle(cp)}\" has no notes`);\n else customSections.push({ title: customSectionTitle(cp), items: customSectionItems(cp) });\n break;\n }\n case 'followUp': {\n const payload = followUpPayload(r as fhir4.Appointment, header.date);\n if (payload) followUp = payload;\n else report(r, 'Appointment has no start date');\n break;\n }\n default:\n report(r, unmappedReason(r));\n }\n } catch (e) {\n report(r, `could not be read: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n\n // A custom section titled like a standard section folds into it after the real entries; the rest stay free-form cards\n const freeFormSections: typeof customSections = [];\n const piles: Record<FoldTarget, Row[] | null> = { symptoms: null, advice: null, medications, diagnosis, procedures, labInvestigations, labResults, examination, history, vitals, referrals };\n for (const custom of customSections) {\n const target = foldTargetOf(custom.title);\n if (!target) { freeFormSections.push(custom); continue; }\n for (const { key, value } of custom.items) {\n const line = value ? `${key}: ${value}` : key;\n if (target === 'symptoms') symptoms.push({ item: line, codes: { eka_code: '', snomed_code: '' } });\n else if (target === 'advice') advice.push(line);\n else piles[target]!.push(foldedRow(target, key, value));\n }\n }\n\n const sections: PrescriptionSection[] = [];\n let order = 0;\n const add = (key: string, display_name: string, kind: PrescriptionSection['kind'], payload: PrescriptionSection['payload']) =>\n sections.push({ key, display_name, kind, payload, order: ++order });\n\n if (symptoms.length) add('symptoms', 'Symptoms', 'LIST', { items: symptoms.map((x) => x.item), codes: symptoms.map((x) => x.codes) }); else order++;\n if (vitals.length) add('vitals', 'Vitals', 'VITAL_TABLE', { headers: VITAL_HEADERS, rows: vitals }); else order++;\n if (examination.length) add('examination_findings', 'Examination Findings', 'EXAMINATION_FINDINGS', { headers: EXAM_HEADERS, rows: examination }); else order++;\n if (diagnosis.length) add('diagnosis', 'Diagnosis', 'DIAGNOSIS', { headers: diagnosisHeaders(diagnosis), rows: diagnosis }); else order++;\n if (history.length) add('medical_history', 'Medical History', 'PATIENT_MEDICAL_HISTORY', { headers: HISTORY_HEADERS, rows: history }); else order++;\n if (medications.length) add('medications', 'Medications', 'MEDICATION_TABLE', { headers: MEDICATION_HEADERS, rows: medications }); else order++;\n if (labInvestigations.length) add('lab_investigations', 'Lab Investigations', 'LAB_INVESTIGATIONS', { headers: LAB_HEADERS, rows: labInvestigations }); else order++;\n if (labResults.length) add('lab_results', 'Lab Results', 'LAB_RESULTS', { headers: LAB_RESULT_HEADERS, rows: labResults }); else order++;\n if (procedures.length) add('procedures', 'Procedures', 'PROCEDURES', { headers: PROCEDURE_HEADERS, rows: procedures }); else order++;\n if (advice.length) add('advice', 'Advice', 'LIST', { items: advice }); else order++;\n if (clinicalNotes.length) add('clinical_notes', 'Clinical Notes', 'LIST', { items: clinicalNotes }); else order++;\n if (followUp) add('follow_up', 'Follow-up', 'FOLLOW_UP', followUp); else order++;\n if (referrals.length) add('referral', 'Referral', 'REFERRAL', { headers: REFERRAL_HEADERS, rows: referrals }); else order++;\n const admission: IpAdmissionPayload = { recommended: true, procedures: [], notes: admissionNoteLines.filter(Boolean).join('\\n') };\n if (admissionNoteLines.length) add('ip_admission', 'IP Admission', 'IP_ADMISSION', admission); else order++;\n const taken = new Set(sections.map((s) => s.key));\n for (const custom of freeFormSections) add(uniqueKey(slug(custom.title), taken), custom.title, 'KEY_VALUE', { items: custom.items });\n\n return { header, sections, diagnostics };\n}\n","import { useEffect, useState } from \"react\";\n\nexport function usePdfHref(url: string | null, base64: string | null): string | null {\n const [href, setHref] = useState<string | null>(url);\n useEffect(() => {\n if (url) {\n setHref(url);\n return;\n }\n if (!base64) {\n setHref(null);\n return;\n }\n try {\n const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));\n const objectUrl = URL.createObjectURL(new Blob([bytes], { type: \"application/pdf\" }));\n setHref(objectUrl);\n return () => URL.revokeObjectURL(objectUrl);\n } catch {\n setHref(`data:application/pdf;base64,${base64}`);\n return;\n }\n }, [url, base64]);\n return href;\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/medical-records-ui/medical-records-ui/dist/chunk-NQXDAXN5.js","../src/visits/components/VisitOriginalPanel.tsx","../src/visits/connection/usePrescription.ts","../src/visits/prescription/fhir-utils.ts","../src/visits/prescription/classify.ts","../src/visits/prescription/header.ts","../src/visits/prescription/mappers/observations.ts","../src/visits/prescription/mappers/care-plans.ts","../src/visits/prescription/config.ts","../src/visits/prescription/mappers/conditions.ts","../src/visits/prescription/mappers/history-extras.ts","../src/visits/prescription/mappers/service-requests.ts","../src/visits/prescription/mappers/medications.ts","../src/visits/prescription/mappers/follow-up.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AAA;AACT,EAAA;AACS,EAAA;AAED,EAAA;AACD,EAAA;AAEP,EAAA;AACS,IAAA;AACf,EAAA;AAGE,EAAA;AACE,oBAAA;AAEI,MAAA;AACE,wBAAA;AAAqC,QAAA;AAEvC,MAAA;AAEF,sBAAA;AACE,wBAAA;AAIE,QAAA;AAIJ,MAAA;AACA,sBAAA;AAKF,IAAA;AAEA,oBAAA;AACc,MAAA;AAKA,MAAA;AAER,wBAAA;AAGA,wBAAA;AAGF,MAAA;AAEU,MAAA;AAKA,MAAA;AAOd,IAAA;AACF,EAAA;AAEJ;ADqxBiB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/medical-records-ui/medical-records-ui/dist/chunk-NQXDAXN5.js","sourcesContent":[null,"\"use client\";\n\nimport { lazy, Suspense, useMemo } from \"react\";\nimport { ChevronLeft, ExternalLink, LoaderCircle } from \"lucide-react\";\nimport { useStore } from \"zustand\";\nimport { useSdk } from \"../../connection/useSdk\";\nimport type { PreviewFile } from \"../../connection/useRecordPreview\";\nimport { useSmartRecordsActions } from \"../../views/context/SmartRecordsActionsContext\";\nimport { IconButton, Typography } from \"widgets\";\nimport { usePrescription } from \"../connection/usePrescription\";\nimport { usePdfHref } from \"../hooks/usePdfHref\";\nimport { isoToDisplayDate } from \"../prescription/fhir-utils\";\n\nconst DocumentViewer = lazy(() =>\n import(\"../../views/RecordPreview/DocumentViewer\").then((m) => ({ default: m.DocumentViewer })),\n);\n\ninterface VisitOriginalPanelProps {\n appointmentId: string;\n onBack?: () => void;\n}\n\nexport function VisitOriginalPanel({ appointmentId, onBack }: VisitOriginalPanelProps) {\n const { store } = useSdk();\n const { hideOpenInNewTab } = useSmartRecordsActions();\n const visit = useStore(store, (s) => s.visits.byId[appointmentId]);\n const { status, retry, conversion } = usePrescription(visit?.prescriptionId ?? null);\n const header = conversion?.header ?? null;\n const pdfHref = usePdfHref(header?.pdfUrl ?? null, header?.pdfBase64 ?? null);\n const hasPdf = !!(header?.pdfUrl || header?.pdfBase64);\n\n const files = useMemo<PreviewFile[]>(() => (pdfHref ? [{ url: pdfHref, kind: \"pdf\" }] : []), [pdfHref]);\n const date = isoToDisplayDate(header?.date ?? null);\n\n const openInNewTab = () => {\n if (pdfHref) window.open(pdfHref, \"_blank\", \"noopener,noreferrer\");\n };\n\n return (\n <div className=\"mr-sv__panel\">\n <div className=\"mr-sv__panel-header mr-orig__panel-header\">\n {onBack && (\n <button type=\"button\" className=\"mr-sv__back-btn\" onClick={onBack}>\n <ChevronLeft size={16} aria-hidden />\n Back\n </button>\n )}\n <div className=\"mr-sv__panel-info\">\n <Typography variant=\"label\" as=\"span\" className=\"mr-sv__panel-name\">\n Prescription\n </Typography>\n {date && (\n <Typography variant=\"hint\" as=\"span\" className=\"mr-sv__panel-meta-text\">\n {date}\n </Typography>\n )}\n </div>\n <div className=\"mr-orig__header-actions\">\n {pdfHref && !hideOpenInNewTab && (\n <IconButton icon={<ExternalLink size={16} aria-hidden />} label=\"Open in new tab\" variant=\"ghost\" size=\"sm\" onClick={openInNewTab} />\n )}\n </div>\n </div>\n\n <div className=\"mr-sv__panel-body mr-rx-original\">\n {status === \"loading\" && (\n <div className=\"mr-rx-original__center\">\n <LoaderCircle size={44} className=\"mr-sv__loading-spinner\" aria-hidden />\n </div>\n )}\n {status === \"error\" && (\n <div className=\"mr-rx-original__center\">\n <Typography variant=\"muted\" className=\"mr-sv__panel-empty\">\n Couldn&apos;t load the prescription\n </Typography>\n <button type=\"button\" className=\"mr-sv__ghost-link-btn\" onClick={retry}>\n Retry\n </button>\n </div>\n )}\n {status === \"loaded\" && !hasPdf && (\n <Typography variant=\"muted\" className=\"mr-sv__panel-empty\">\n No original document for this prescription.\n </Typography>\n )}\n {status === \"loaded\" && files.length > 0 && (\n <div className=\"mr-record-preview__body mr-rx-original__viewer\">\n <Suspense fallback={null}>\n <DocumentViewer files={files} title=\"Prescription\" />\n </Suspense>\n </div>\n )}\n </div>\n </div>\n );\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport type { FhirBundle } from '@eka-care/medical-records-ts-sdk';\nimport { getCore, isWorkerReady } from '../../connection/sdkClient';\nimport { convertPrescriptionBundle } from '../prescription/convert-prescription';\nimport type { PrescriptionConversion } from '../prescription/types';\n\nexport type PrescriptionStatus = 'idle' | 'loading' | 'loaded' | 'error';\n\nexport interface PrescriptionState {\n status: PrescriptionStatus;\n bundle: FhirBundle | null;\n conversion: PrescriptionConversion | null;\n error: string | null;\n retry: () => Promise<void>;\n}\n\ntype Entry = { bundle: FhirBundle; conversion: PrescriptionConversion };\ntype Snapshot = Omit<PrescriptionState, 'retry'>;\n\nconst cache = new Map<string, Entry>();\nconst inflight = new Map<string, Promise<Entry>>();\n\nexport function clearPrescriptionCache(): void {\n cache.clear();\n inflight.clear();\n}\n\nfunction fetchEntry(prescriptionId: string): Promise<Entry> {\n const hit = cache.get(prescriptionId);\n if (hit) return Promise.resolve(hit);\n const pending = inflight.get(prescriptionId);\n if (pending) return pending;\n const request = getCore()\n .getPrescriptionBundle({ prescriptionId })\n .then((bundle) => {\n const conversion = convertPrescriptionBundle(bundle);\n const entry = { bundle, conversion };\n if (conversion.diagnostics.length) console.table(conversion.diagnostics);\n cache.set(prescriptionId, entry);\n return entry;\n })\n .finally(() => inflight.delete(prescriptionId));\n inflight.set(prescriptionId, request);\n return request;\n}\n\nexport async function prefetchPrescription(prescriptionId: string | null | undefined): Promise<void> {\n if (!prescriptionId || !isWorkerReady()) return;\n try {\n await fetchEntry(prescriptionId);\n } catch {\n // the record panel reports the error when it is actually opened\n }\n}\n\nconst IDLE: Snapshot = { status: 'idle', bundle: null, conversion: null, error: null };\n\nconst loaded = (entry: Entry): Snapshot => ({ status: 'loaded', bundle: entry.bundle, conversion: entry.conversion, error: null });\n\nasync function resolve(prescriptionId: string | null, isCurrent: () => boolean, set: (s: Snapshot) => void): Promise<void> {\n if (!prescriptionId || !isWorkerReady()) {\n set(IDLE);\n return;\n }\n const hit = cache.get(prescriptionId);\n if (hit) {\n set(loaded(hit));\n return;\n }\n set({ status: 'loading', bundle: null, conversion: null, error: null });\n try {\n const entry = await fetchEntry(prescriptionId);\n if (isCurrent()) set(loaded(entry));\n } catch (e) {\n if (isCurrent()) set({ status: 'error', bundle: null, conversion: null, error: e instanceof Error ? e.message : 'Failed to load prescription' });\n }\n}\n\nexport function usePrescription(prescriptionId: string | null): PrescriptionState {\n const [state, setState] = useState<Snapshot>(() => {\n const hit = prescriptionId ? cache.get(prescriptionId) : undefined;\n return hit ? loaded(hit) : IDLE;\n });\n const requestRef = useRef(0);\n\n const start = useCallback(() => {\n const request = ++requestRef.current;\n return resolve(prescriptionId, () => requestRef.current === request, setState);\n }, [prescriptionId]);\n\n useEffect(() => {\n void start();\n }, [start]);\n\n return { ...state, retry: start };\n}\n","import type { FhirResource, fhir4 } from '@eka-care/medical-records-ts-sdk';\n\n\nconst EKA_SYSTEM = /eka\\.care/i;\nconst SNOMED_SYSTEM = /snomed/i;\n\nexport function codings(cc: fhir4.CodeableConcept | undefined | null): fhir4.Coding[] {\n return Array.isArray(cc?.coding) ? cc!.coding.filter((c): c is fhir4.Coding => !!c && typeof c === 'object') : [];\n}\n\n// All codings across a resource's category list\nexport function categoryCodings(categories: fhir4.CodeableConcept[] | undefined | null): fhir4.Coding[] {\n return Array.isArray(categories) ? categories.flatMap(codings) : [];\n}\n\n// Category free-text labels, e.g. \"custom_section\"\nexport function categoryTexts(categories: fhir4.CodeableConcept[] | undefined | null): string[] {\n return Array.isArray(categories) ? categories.map((c) => c?.text).filter((t): t is string => typeof t === 'string') : [];\n}\n\nexport function hasCode(list: fhir4.Coding[], code: string): boolean {\n return list.some((c) => c.code === code);\n}\n\nexport function hasDisplay(list: fhir4.Coding[], display: string): boolean {\n const want = display.toLowerCase();\n return list.some((c) => (c.display ?? '').toLowerCase() === want);\n}\n\n// Display name of a concept, preferring Eka's own wording, then SNOMED, then anything, then the text\nexport function conceptDisplay(cc: fhir4.CodeableConcept | undefined | null): string | null {\n const list = codings(cc);\n const pick =\n list.find((c) => EKA_SYSTEM.test(c.system ?? '') && c.display) ??\n list.find((c) => SNOMED_SYSTEM.test(c.system ?? '') && c.display) ??\n list.find((c) => c.display);\n return pick?.display?.trim() || cc?.text?.trim() || null;\n}\n\nconst MDB_SYSTEM = /eka\\.care\\/(mdb|medication|service)|mdb\\.eka\\.care/i;\n\n// The eka master-database id (d-…, b-…, lp-…); local codes from parchi do not count\nexport function ekaCode(cc: fhir4.CodeableConcept | undefined | null): string | null {\n return codings(cc).find((c) => MDB_SYSTEM.test(c.system ?? '') && c.code)?.code ?? null;\n}\n\nexport function snomedCode(cc: fhir4.CodeableConcept | undefined | null): string | null {\n return codings(cc).find((c) => SNOMED_SYSTEM.test(c.system ?? '') && c.code)?.code ?? null;\n}\n\nexport function entityCodes(cc: fhir4.CodeableConcept | undefined | null): { eka_code: string; snomed_code: string } {\n return { eka_code: ekaCode(cc) ?? '', snomed_code: snomedCode(cc) ?? '' };\n}\n\n// \"102 C\" from a Quantity; null when there is no numeric value\nexport function quantityText(q: fhir4.Quantity | undefined | null): string | null {\n if (!q || typeof q.value !== 'number' || Number.isNaN(q.value)) return null;\n const unit = (q.unit ?? q.code ?? '').trim();\n return unit ? `${q.value} ${unit}` : String(q.value);\n}\n\nexport function quantityValue(q: fhir4.Quantity | undefined | null): string | null {\n return q && typeof q.value === 'number' && !Number.isNaN(q.value) ? String(q.value) : null;\n}\n\nexport function quantityUnit(q: fhir4.Quantity | undefined | null): string | null {\n const unit = (q?.unit ?? q?.code ?? '').trim();\n return unit || null;\n}\n\nexport function noteText(notes: fhir4.Annotation[] | undefined | null): string | null {\n if (!Array.isArray(notes)) return null;\n const text = notes.map((n) => n?.text?.trim()).filter(Boolean).join('\\n');\n return text || null;\n}\n\n// Extension value by url, e.g. the eka care-context id\nexport function extensionString(ext: fhir4.Extension[] | undefined | null, url: string): string | null {\n return Array.isArray(ext) ? ext.find((e) => e?.url === url)?.valueString ?? null : null;\n}\n\nexport function isoToDisplayDate(iso: string | undefined | null): string | null {\n if (!iso) return null;\n const dayOnly = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(iso.trim());\n const d = dayOnly ? new Date(Number(dayOnly[1]), Number(dayOnly[2]) - 1, Number(dayOnly[3])) : new Date(Date.parse(iso));\n if (Number.isNaN(d.getTime())) return null;\n return `${String(d.getDate()).padStart(2, '0')} ${d.toLocaleString('en', { month: 'short' })} ${d.getFullYear()}`;\n}\n\n\nexport function compositionSectionMap(resources: FhirResource[]): Map<string, string> {\n const map = new Map<string, string>();\n const composition = resources.find((r) => r?.resourceType === 'Composition') as fhir4.Composition | undefined;\n for (const section of composition?.section ?? []) {\n const code = codings(section?.code).find((c) => c.code)?.code;\n if (!code) continue;\n for (const entry of section.entry ?? []) {\n if (entry?.reference) map.set(entry.reference, code);\n }\n }\n return map;\n}\n","import type { FhirResource, fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport { categoryCodings, categoryTexts, codings, hasCode, hasDisplay } from './fhir-utils';\n\n/** The piles a bundle card can land in. Anything else is deliberately ignored. */\nexport type Pile =\n | 'header'\n | 'symptoms'\n | 'vitals'\n | 'labResults'\n | 'examination'\n | 'diagnosis'\n | 'history'\n | 'medications'\n | 'labInvestigations'\n | 'procedures'\n | 'advice'\n | 'clinicalNote'\n | 'notes'\n | 'customSection'\n | 'followUp'\n | 'referral'\n | 'ipAdmission';\n\nconst HEADER_TYPES = new Set(['Composition', 'Encounter', 'Patient', 'Practitioner', 'Organization', 'DocumentReference']);\nconst HISTORY_TYPES = new Set(['FamilyMemberHistory', 'Procedure', 'AllergyIntolerance']);\n\n// Codes the Eka FHIR spec allows for a symptom's category, besides the plain \"symptom\"\nconst SYMPTOM_CODES = ['symptom', '418799008', 's-8068301606'];\nconst SNOMED_MEDICAL_ADVICE = '386464006';\nconst SNOMED_CLINICAL_NOTE = '371530004';\nconst SNOMED_PATIENT_REFERRAL = '3457005';\n\nconst SECTION_PILES: Record<string, Pile> = {\n '422843007': 'symptoms', // Chief Complaints\n '371529009': 'history', // Medical History\n '722446000': 'history', // Allergies\n '282291009': 'diagnosis', // Diagnosis\n};\n\nfunction classifyObservation(r: fhir4.Observation): Pile | null {\n const cats = categoryCodings(r.category);\n if (hasCode(cats, 'vital-signs')) return 'vitals';\n if (hasCode(cats, 'exam')) return 'examination';\n if (hasCode(cats, 'social-history')) return 'history';\n if (hasCode(cats, 'laboratory')) return 'labResults';\n if (hasCode(cats, 'survey')) return 'notes';\n if (SYMPTOM_CODES.some((code) => hasCode(cats, code))) return 'symptoms';\n return null;\n}\n\n// A Condition's category cannot tell a symptom from a history item; the Composition section can\nfunction classifyCondition(r: fhir4.Condition, sectionCode?: string): Pile | null {\n const bySection = sectionCode ? SECTION_PILES[sectionCode] : undefined;\n if (bySection) return bySection;\n const cats = categoryCodings(r.category);\n if (hasCode(cats, 'encounter-diagnosis')) return 'diagnosis';\n if (hasCode(cats, 'problem-list-item')) return 'history';\n return null;\n}\n\nfunction classifyServiceRequest(r: fhir4.ServiceRequest): Pile | null {\n const cats = categoryCodings(r.category);\n if (hasDisplay(cats, 'Laboratory procedure') || hasCode(cats, '108252007')) return 'labInvestigations';\n if (hasDisplay(cats, 'Surgical procedure') || hasCode(cats, '387713003')) return 'procedures';\n if (hasDisplay(cats, 'Patient referral') || hasCode(cats, SNOMED_PATIENT_REFERRAL)) {\n return /hospital admission/i.test(r.code?.text ?? '') ? 'ipAdmission' : 'referral';\n }\n return null;\n}\n\n// Category first; the spec's intent values (plan = advice, proposal = note) are the fallback\nfunction classifyCarePlan(r: fhir4.CarePlan): Pile | null {\n if (categoryTexts(r.category).includes('custom_section')) return 'customSection';\n const cats = categoryCodings(r.category);\n if (hasCode(cats, SNOMED_MEDICAL_ADVICE) || hasDisplay(cats, 'Medical advice')) return 'advice';\n if (hasCode(cats, SNOMED_CLINICAL_NOTE) || hasDisplay(cats, 'Clinical note')) return 'clinicalNote';\n if (r.intent === 'plan') return 'advice';\n if (r.intent === 'proposal') return 'clinicalNote';\n return null;\n}\n\nfunction classifyAppointment(r: fhir4.Appointment): Pile | null {\n const types = codings(r.appointmentType);\n if (!types.length) return 'followUp';\n return hasCode(types, 'FOLLOWUP') || hasCode(types, 'FU') ? 'followUp' : null;\n}\n\n/** Decides which pile a bundle card belongs to; null means \"ignore on purpose\". Never throws. */\nexport function classifyResource(resource: FhirResource | null | undefined, sectionCode?: string): Pile | null {\n if (!resource || typeof resource !== 'object' || typeof resource.resourceType !== 'string') return null;\n const type = resource.resourceType;\n if (HEADER_TYPES.has(type)) return 'header';\n if (HISTORY_TYPES.has(type)) return 'history';\n switch (type) {\n case 'Observation':\n return classifyObservation(resource as fhir4.Observation);\n case 'Condition':\n return classifyCondition(resource as fhir4.Condition, sectionCode);\n case 'ServiceRequest':\n return classifyServiceRequest(resource as fhir4.ServiceRequest);\n case 'CarePlan':\n return classifyCarePlan(resource as fhir4.CarePlan);\n case 'MedicationRequest':\n return 'medications';\n case 'Appointment':\n return classifyAppointment(resource as fhir4.Appointment);\n default:\n return null;\n }\n}\n","import type { FhirResource, fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport type { PrescriptionHeader } from './types';\nimport { extensionString } from './fhir-utils';\n\nconst CARE_CONTEXT_EXTENSION = 'https://eka.care/care_context_id';\n\nconst byType = <T extends FhirResource>(resources: FhirResource[], type: T['resourceType']): T | undefined =>\n resources.find((r) => r?.resourceType === type) as T | undefined;\n\n// Who, when and the original document: read from the Composition, Patient, Practitioner and DocumentReference cards\nexport function buildHeader(resources: FhirResource[]): PrescriptionHeader {\n const composition = byType<fhir4.Composition>(resources, 'Composition');\n const encounter = byType<fhir4.Encounter>(resources, 'Encounter');\n const patient = byType<fhir4.Patient>(resources, 'Patient');\n const practitioner = byType<fhir4.Practitioner>(resources, 'Practitioner');\n const document = byType<fhir4.DocumentReference>(resources, 'DocumentReference');\n const attachment = document?.content?.[0]?.attachment;\n const author = composition?.author?.[0];\n return {\n prescriptionId: composition?.identifier?.value ?? null,\n date: composition?.date ?? encounter?.period?.start ?? null,\n doctorName: author?.display ?? practitioner?.name?.[0]?.text ?? null,\n doctorId: practitioner?.id ?? author?.reference?.split('/').pop() ?? null,\n patientName: patient?.name?.[0]?.text ?? composition?.subject?.display ?? null,\n patientId: patient?.id ?? composition?.subject?.reference?.split('/').pop() ?? null,\n careContextId: extensionString(composition?.extension, CARE_CONTEXT_EXTENSION) ?? extensionString(encounter?.extension, CARE_CONTEXT_EXTENSION),\n pdfUrl: attachment?.url ?? null,\n pdfBase64: attachment?.data ?? null,\n };\n}\n","import type { fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport { conceptDisplay, entityCodes, noteText, quantityUnit, quantityValue } from '../fhir-utils';\nimport type { EntityCodes } from '../types';\n\nexport function symptomItem(r: fhir4.Observation | fhir4.Condition): { item: string; codes: EntityCodes } | null {\n const item = conceptDisplay(r.code);\n return item ? { item, codes: entityCodes(r.code) } : null;\n}\n\n\nexport function vitalRow(obs: fhir4.Observation): Record<string, string> | null {\n const name = conceptDisplay(obs.code);\n if (!name) return null;\n const components = Array.isArray(obs.component) ? obs.component : [];\n const quantities = components.length\n ? components.map((c) => c?.valueQuantity).filter((q): q is fhir4.Quantity => !!q)\n : obs.valueQuantity\n ? [obs.valueQuantity]\n : [];\n const values = quantities.map(quantityValue).filter((v): v is string => v !== null);\n const value = values.length ? values.join('/') : (obs.valueString?.trim() ?? conceptDisplay(obs.valueCodeableConcept) ?? '');\n return {\n vital_name: name,\n value,\n unit: quantityUnit(quantities[0]) ?? '',\n normal_range: '',\n notes: noteText(obs.note) ?? '',\n ...entityCodes(obs.code),\n };\n}\n\nconst EXAM_STATUS: Record<string, string> = { POS: 'present', NEG: 'absent', A: 'abnormal', N: 'normal' };\n\nexport function examinationRow(obs: fhir4.Observation): Record<string, string> | null {\n const finding = conceptDisplay(obs.code);\n if (!finding) return null;\n const interpretation = Array.isArray(obs.interpretation) ? obs.interpretation[0]?.coding?.[0]?.code ?? '' : '';\n const status = EXAM_STATUS[interpretation] ?? obs.valueString?.trim().toLowerCase() ?? '';\n return { finding, status, detail: noteText(obs.note) ?? '', ...entityCodes(obs.code) };\n}\n\nexport function socialHistoryRow(obs: fhir4.Observation): Record<string, string> | null {\n const condition = conceptDisplay(obs.code);\n if (!condition) return null;\n return {\n condition,\n category: 'lifestyle_habit',\n status: obs.valueString?.trim() ?? conceptDisplay(obs.valueCodeableConcept) ?? '',\n since: '',\n note: noteText(obs.note) ?? '',\n ...entityCodes(obs.code),\n };\n}\n\nconst INTERPRETATION: Record<string, string> = { H: 'High', HH: 'High', L: 'Low', LL: 'Low', A: 'Abnormal', AA: 'Abnormal', N: 'Normal' };\n\nfunction referenceRangeText(obs: fhir4.Observation): string {\n const range = Array.isArray(obs.referenceRange) ? obs.referenceRange[0] : undefined;\n if (!range) return '';\n const low = quantityValue(range.low);\n const high = quantityValue(range.high);\n if (low && high) return `${low} - ${high}`;\n return range.text?.trim() ?? (low ? `> ${low}` : high ? `< ${high}` : '');\n}\n\nexport function labResultRow(obs: fhir4.Observation): Record<string, string> | null {\n const test_name = conceptDisplay(obs.code);\n const value = quantityValue(obs.valueQuantity) ?? obs.valueString?.trim() ?? conceptDisplay(obs.valueCodeableConcept);\n if (!test_name || !value) return null;\n const interpretation = Array.isArray(obs.interpretation) ? obs.interpretation[0] : undefined;\n const code = interpretation?.coding?.[0]?.code ?? '';\n return {\n test_name,\n value,\n unit: quantityUnit(obs.valueQuantity) ?? '',\n reference_range: referenceRangeText(obs),\n out_of_range: INTERPRETATION[code] ?? conceptDisplay(interpretation) ?? '',\n ...entityCodes(obs.code),\n };\n}\n","import type { fhir4 } from '@eka-care/medical-records-ts-sdk';\n\n// Narrative of an advice or clinical-note CarePlan, HTML stripped\nexport function carePlanText(cp: fhir4.CarePlan): string | null {\n const text = (cp.description ?? cp.title ?? '').replace(/<[^>]+>/g, '').trim();\n return text || null;\n}\n\n// Custom-section notes arrive as a Python dict dump: {'id':'…','name':'Dolo','value':'Wrd','value_html':null}\n// Python switches to double quotes when the string holds an apostrophe, so both quote styles are accepted\nconst PY_STRING = `'((?:[^'\\\\\\\\]|\\\\\\\\.)*)'|\"((?:[^\"\\\\\\\\]|\\\\\\\\.)*)\"`;\nconst NAME_RE = new RegExp(`['\"]name['\"]\\\\s*:\\\\s*(?:${PY_STRING})`);\nconst VALUE_RE = new RegExp(`['\"]value['\"]\\\\s*:\\\\s*(?:${PY_STRING}|None|null)`);\n\nfunction unescape(text: string): string {\n return text.replace(/\\\\'/g, \"'\").replace(/\\\\\"/g, '\"').replace(/\\\\n/g, '\\n').trim();\n}\n\n// The matched string from either quote style\nfunction matched(m: RegExpExecArray | null): string | null {\n if (!m) return null;\n return m[1] ?? m[2] ?? '';\n}\n\n// One name/value pair from a note; null when the note holds no such pair\nexport function parseCustomPair(text: string | undefined | null): { key: string; value: string } | null {\n if (!text) return null;\n try {\n const parsed = JSON.parse(text) as { name?: unknown; value?: unknown };\n if (parsed && typeof parsed === 'object' && typeof parsed.name === 'string') {\n return { key: parsed.name.trim(), value: typeof parsed.value === 'string' ? parsed.value.trim() : '' };\n }\n } catch {\n // not JSON; fall through to the Python-style form\n }\n const name = matched(NAME_RE.exec(text));\n if (name === null) return null;\n const value = matched(VALUE_RE.exec(text));\n return { key: unescape(name), value: value ? unescape(value) : '' };\n}\n\n// Every note as a pair; a note that cannot be parsed is kept verbatim as the key so nothing is silently lost\nexport function customSectionItems(cp: fhir4.CarePlan): { key: string; value: string }[] {\n const notes = Array.isArray(cp.note) ? cp.note : [];\n return notes\n .map((n) => parseCustomPair(n?.text) ?? { key: (n?.text ?? '').trim(), value: '' })\n .filter((pair) => pair.key !== '' || pair.value !== '');\n}\n\nexport function customSectionTitle(cp: fhir4.CarePlan): string {\n return (cp.title ?? cp.description ?? 'Custom section').replace(/<[^>]+>/g, '').trim() || 'Custom section';\n}\n","export const SHOW_CUSTOM_SECTIONS = true;\n","import type { fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport { codings, conceptDisplay, ekaCode, entityCodes, isoToDisplayDate, noteText, snomedCode } from '../fhir-utils';\n\nconst SEVERITY_BY_SNOMED: Record<string, string> = { '24484000': 'Severe', '6736007': 'Moderate', '255604002': 'Mild' };\n\nfunction firstCode(cc: fhir4.CodeableConcept | undefined): string {\n return (codings(cc)[0]?.code ?? '').toLowerCase();\n}\n\nexport function diagnosisStatus(cond: fhir4.Condition): 'Confirmed' | 'Suspected' | 'Resolved' | 'Ruled out' {\n const clinical = firstCode(cond.clinicalStatus);\n const verification = firstCode(cond.verificationStatus);\n if (verification === 'refuted' || clinical === 'inactive') return 'Ruled out';\n if (['resolved', 'remission'].includes(clinical)) return 'Resolved';\n if (['provisional', 'unconfirmed', 'differential'].includes(verification) || clinical === 'unknown') return 'Suspected';\n return 'Confirmed';\n}\n\nexport function presenceToken(clinical: string, verification: string): string {\n if (verification === 'refuted') return 'no';\n if (clinical === 'active' || clinical === 'recurrence' || clinical === 'relapse' || verification === 'confirmed') return 'yes';\n return '';\n}\n\n// Onset may be a date, a period, an age or free text\nexport function onsetText(cond: fhir4.Condition): string {\n if (cond.onsetDateTime) return isoToDisplayDate(cond.onsetDateTime) ?? cond.onsetDateTime;\n if (cond.onsetPeriod?.start) return isoToDisplayDate(cond.onsetPeriod.start) ?? cond.onsetPeriod.start;\n if (cond.onsetAge && typeof cond.onsetAge.value === 'number') return `${cond.onsetAge.value} ${cond.onsetAge.unit ?? cond.onsetAge.code ?? ''}`.trim();\n if (typeof cond.onsetString === 'string') return cond.onsetString.trim();\n return '';\n}\n\nexport function severityText(cond: fhir4.Condition): string {\n const code = snomedCode(cond.severity);\n return (code && SEVERITY_BY_SNOMED[code]) || conceptDisplay(cond.severity) || '';\n}\n\n// A diagnosis of this visit, in the editor's DIAGNOSIS row shape\nexport function diagnosisRow(cond: fhir4.Condition): Record<string, string> | null {\n const name = conceptDisplay(cond.code);\n if (!name) return null;\n const row: Record<string, string> = {\n diagnosis: name,\n diagnosis_id: ekaCode(cond.code) ?? '',\n eka_code: ekaCode(cond.code) ?? '',\n icd10_code: '',\n icd10_name: '',\n snomed_code: snomedCode(cond.code) ?? '',\n status: diagnosisStatus(cond),\n };\n const since = onsetText(cond);\n const severity = severityText(cond);\n const notes = noteText(cond.note);\n if (since) row.since = since;\n if (severity) row.severity = severity;\n if (notes) row.notes = notes;\n return row;\n}\n\n// A known condition the patient carries, in the editor's PATIENT_MEDICAL_HISTORY row shape\nexport function historyRowFromCondition(cond: fhir4.Condition): Record<string, string> | null {\n const condition = conceptDisplay(cond.code);\n if (!condition) return null;\n return {\n condition,\n category: 'condition',\n status: presenceToken(firstCode(cond.clinicalStatus), firstCode(cond.verificationStatus)),\n since: onsetText(cond),\n note: noteText(cond.note) ?? '',\n ...entityCodes(cond.code),\n };\n}\n","import type { fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport { codings, conceptDisplay, entityCodes, isoToDisplayDate, noteText } from '../fhir-utils';\nimport { presenceToken } from './conditions';\n\nexport function familyHistoryRows(fmh: fhir4.FamilyMemberHistory): Record<string, string>[] {\n const relation = conceptDisplay(fmh.relationship) ?? '';\n const notes = noteText(fmh.note) ?? '';\n const note = [relation, notes].filter(Boolean).join('. ');\n const conditions = Array.isArray(fmh.condition) ? fmh.condition : [];\n return conditions\n .filter((c) => !!conceptDisplay(c?.code))\n .map((c) => ({ condition: conceptDisplay(c.code)!, category: 'family_history', status: '', since: '', note, ...entityCodes(c.code) }));\n}\n\nexport function pastProcedureRow(proc: fhir4.Procedure): Record<string, string> | null {\n const condition = conceptDisplay(proc.code);\n if (!condition) return null;\n const performed = proc.performedDateTime ?? proc.performedPeriod?.start ?? null;\n return {\n condition,\n category: 'past_procedure',\n status: '',\n since: (performed && isoToDisplayDate(performed)) ?? '',\n note: noteText(proc.note) ?? '',\n ...entityCodes(proc.code),\n };\n}\n\nexport function allergyRow(allergy: fhir4.AllergyIntolerance): Record<string, string> | null {\n const condition = conceptDisplay(allergy.code);\n if (!condition) return null;\n const kinds = Array.isArray(allergy.category) ? allergy.category : [];\n return {\n condition,\n category: kinds.includes('medication') ? 'drug_allergy' : 'other_allergy',\n status: presenceToken(codings(allergy.clinicalStatus)[0]?.code ?? '', codings(allergy.verificationStatus)[0]?.code ?? ''),\n since: allergy.onsetDateTime ? (isoToDisplayDate(allergy.onsetDateTime) ?? '') : '',\n note: noteText(allergy.note) ?? '',\n ...entityCodes(allergy.code),\n };\n}\n","import type { fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport { conceptDisplay, entityCodes, noteText } from '../fhir-utils';\n\nexport function labInvestigationRow(sr: fhir4.ServiceRequest): Record<string, string> | null {\n const investigation = conceptDisplay(sr.code);\n if (!investigation) return null;\n const codes = entityCodes(sr.code);\n return { investigation, investigationId: codes.eka_code, ekaId: codes.eka_code, ...codes, test_on: '', repeat_on: '', remarks: noteText(sr.note) ?? '' };\n}\n\nexport function procedureRow(sr: fhir4.ServiceRequest): Record<string, string> | null {\n const procedure_name = conceptDisplay(sr.code);\n if (!procedure_name) return null;\n return { procedure_name, timing: '', note: noteText(sr.note) ?? '', ...entityCodes(sr.code) };\n}\n\nexport function referralRow(sr: fhir4.ServiceRequest): Record<string, string> | null {\n const referred_to = sr.code?.text?.trim() || conceptDisplay(sr.code);\n if (!referred_to) return null;\n return { referred_to, specialty: '', phone: '', hospital: '', notes: noteText(sr.note) ?? '', ...entityCodes(sr.code) };\n}\n\nexport function admissionNotes(sr: fhir4.ServiceRequest): string {\n return noteText(sr.note) ?? '';\n}\n","import type { fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport { codings, conceptDisplay, ekaCode, entityCodes, noteText, quantityText } from '../fhir-utils';\n\nconst UNIT_WORDS: Record<string, [string, string]> = {\n s: ['second', 'seconds'], min: ['minute', 'minutes'], h: ['hour', 'hours'], d: ['day', 'days'],\n wk: ['week', 'weeks'], mo: ['month', 'months'], a: ['year', 'years'],\n};\n\nfunction durationText(repeat: fhir4.TimingRepeat | undefined): string {\n if (!repeat || typeof repeat.duration !== 'number') return '';\n const unit = repeat.durationUnit ? UNIT_WORDS[repeat.durationUnit] : undefined;\n const word = unit ? (repeat.duration === 1 ? unit[0] : unit[1]) : (repeat.durationUnit ?? '');\n return `${repeat.duration} ${word}`.trim();\n}\n\n// \"1-1-0\" when the doctor wrote one; otherwise derived from the repeat count\nfunction frequencyText(dosage: fhir4.Dosage): string {\n const written = Array.isArray(dosage.additionalInstruction) ? conceptDisplay(dosage.additionalInstruction[0]) : null;\n if (written) return written;\n const f = dosage.timing?.repeat?.frequency;\n return typeof f === 'number' ? `${f} time${f === 1 ? '' : 's'} a day` : '';\n}\n\n// One prescribed medicine, in the editor's MEDICATION_TABLE row shape\nexport function medicationRow(mr: fhir4.MedicationRequest): Record<string, string> | null {\n const drug_name = conceptDisplay(mr.medicationCodeableConcept);\n if (!drug_name) return null;\n const dosage: fhir4.Dosage = Array.isArray(mr.dosageInstruction) ? (mr.dosageInstruction[0] ?? {}) : {};\n const doseQuantity = Array.isArray(dosage.doseAndRate) ? dosage.doseAndRate[0]?.doseQuantity : undefined;\n return {\n drug_name,\n medication_id: ekaCode(mr.medicationCodeableConcept) ?? codings(mr.medicationCodeableConcept)[0]?.code ?? '',\n ...entityCodes(mr.medicationCodeableConcept),\n dosage: quantityText(doseQuantity) ?? '',\n frequency: frequencyText(dosage),\n timing: conceptDisplay(dosage.timing?.code) ?? '',\n duration: durationText(dosage.timing?.repeat),\n route: conceptDisplay(dosage.route) ?? '',\n quantity: quantityText(mr.dispenseRequest?.quantity) ?? '',\n notes: (dosage.text ?? dosage.patientInstruction ?? noteText(mr.note) ?? '').trim(),\n };\n}\n","import type { fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport type { FollowUpPayload } from '../types';\n\nconst DAY_MS = 86_400_000;\n\nexport function followUpPayload(appt: fhir4.Appointment, visitDate: string | null): FollowUpPayload | null {\n const date = (appt.start ?? appt.requestedPeriod?.[0]?.start ?? '').trim();\n if (!date) return null;\n const written = (appt.description ?? '').trim();\n let interval = written && written !== date ? written : '';\n if (!interval) {\n const startMs = Date.parse(date);\n const visitMs = visitDate ? Date.parse(visitDate) : NaN;\n if (!Number.isNaN(startMs) && !Number.isNaN(visitMs)) {\n const days = Math.round((startMs - visitMs) / DAY_MS);\n if (days > 0) interval = `${days} day${days === 1 ? '' : 's'}`;\n }\n }\n return { date, interval, notes: (appt.comment ?? '').trim() };\n}\n","import type { FhirBundle, FhirResource, fhir4 } from '@eka-care/medical-records-ts-sdk';\nimport type { Diagnostic, EntityCodes, IpAdmissionPayload, PrescriptionConversion, PrescriptionSection, TableColumn } from './types';\nimport { classifyResource } from './classify';\nimport { buildHeader } from './header';\nimport { categoryCodings, categoryTexts, codings, compositionSectionMap, conceptDisplay } from './fhir-utils';\nimport { examinationRow, labResultRow, socialHistoryRow, symptomItem, vitalRow } from './mappers/observations';\nimport { carePlanText, customSectionItems, customSectionTitle } from './mappers/care-plans';\nimport { SHOW_CUSTOM_SECTIONS } from './config';\nimport { diagnosisRow, historyRowFromCondition } from './mappers/conditions';\nimport { allergyRow, familyHistoryRows, pastProcedureRow } from './mappers/history-extras';\nimport { admissionNotes, labInvestigationRow, procedureRow, referralRow } from './mappers/service-requests';\nimport { medicationRow } from './mappers/medications';\nimport { followUpPayload } from './mappers/follow-up';\n\ntype Row = Record<string, string>;\n\nconst col = (key: string, label: string, type: TableColumn['type'] = 'text'): TableColumn => ({ key, label, type });\n\nconst VITAL_HEADERS = [col('vital_name', 'Vital Sign'), col('value', 'Value'), col('unit', 'Unit'), col('normal_range', 'Normal Range'), col('notes', 'Notes', 'markdown')];\nconst EXAM_HEADERS = [col('finding', 'Finding'), col('status', 'Status'), col('detail', 'Detail')];\nconst HISTORY_HEADERS = [col('condition', 'Condition'), col('category', 'Category'), col('status', 'Status'), col('since', 'Since'), col('note', 'Note')];\nconst MEDICATION_HEADERS = [col('drug_name', 'Medicine'), col('dosage', 'Dosage'), col('frequency', 'Frequency'), col('timing', 'Timing'), col('duration', 'Duration'), col('route', 'Route'), col('quantity', 'Quantity'), col('notes', 'Instructions')];\nconst LAB_HEADERS = [col('investigation', 'Investigation'), col('test_on', 'Test On'), col('repeat_on', 'Repeat On'), col('remarks', 'Remarks')];\nconst LAB_RESULT_HEADERS = [col('test_name', 'Test Name'), col('value', 'Value'), col('unit', 'Unit'), col('reference_range', 'Reference Range'), col('out_of_range', 'Status')];\nconst PROCEDURE_HEADERS = [col('procedure_name', 'Procedure'), col('timing', 'Timing'), col('note', 'Note')];\nconst REFERRAL_HEADERS = [col('referred_to', 'Doctor name'), col('specialty', 'Speciality'), col('phone', 'Phone number'), col('hospital', 'Hospital'), col('notes', 'Notes')];\nconst DIAGNOSIS_OPTIONAL = [col('since', 'Since'), col('severity', 'Severity'), col('notes', 'Notes')];\n\n// Section key = slug of the display name, the same rule the editor's standard sections follow\nfunction slug(title: string): string {\n return title.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'section';\n}\n\nfunction uniqueKey(base: string, taken: Set<string>): string {\n let key = base;\n for (let n = 2; taken.has(key); n++) key = `${base}_${n}`;\n taken.add(key);\n return key;\n}\n\ntype FoldTarget = 'symptoms' | 'advice' | 'medications' | 'diagnosis' | 'procedures' | 'labInvestigations' | 'labResults' | 'examination' | 'history' | 'vitals' | 'referrals';\nconst FOLD_TARGETS: Record<string, FoldTarget> = {\n 'chief complaint': 'symptoms', 'chief complaints': 'symptoms', symptom: 'symptoms', symptoms: 'symptoms',\n advice: 'advice', advices: 'advice',\n medication: 'medications', medications: 'medications', medicine: 'medications', medicines: 'medications',\n diagnosis: 'diagnosis', diagnoses: 'diagnosis',\n procedure: 'procedures', procedures: 'procedures',\n 'lab investigation': 'labInvestigations', 'lab investigations': 'labInvestigations', investigation: 'labInvestigations', investigations: 'labInvestigations',\n 'lab result': 'labResults', 'lab results': 'labResults',\n 'examination finding': 'examination', 'examination findings': 'examination', examination: 'examination',\n 'patient medical history': 'history', 'medical history': 'history', history: 'history',\n vital: 'vitals', vitals: 'vitals', 'vital sign': 'vitals', 'vital signs': 'vitals',\n referral: 'referrals', referrals: 'referrals',\n};\nfunction foldTargetOf(title: string): FoldTarget | null {\n return FOLD_TARGETS[title.toLowerCase().replace(/[^a-z ]+/g, ' ').replace(/\\s+/g, ' ').trim()] ?? null;\n}\n\nfunction foldedRow(target: FoldTarget, key: string, value: string): Row {\n switch (target) {\n case 'medications': return { drug_name: key, dosage: '', frequency: '', timing: '', duration: '', route: '', quantity: '', notes: value };\n case 'diagnosis': return { diagnosis: key, status: '', notes: value };\n case 'procedures': return { procedure_name: key, timing: '', note: value };\n case 'labInvestigations': return { investigation: key, test_on: '', repeat_on: '', remarks: value };\n case 'labResults': return { test_name: key, value, unit: '', reference_range: '', out_of_range: '' };\n case 'examination': return { finding: key, status: '', detail: value };\n case 'history': return { condition: key, category: 'condition', status: '', since: '', note: value };\n case 'vitals': return { vital_name: key, value, unit: '', normal_range: '', notes: '' };\n default: return { referred_to: key, specialty: '', phone: '', hospital: '', notes: value };\n }\n}\n\nfunction diagnosisHeaders(rows: Row[]): TableColumn[] {\n return [col('diagnosis', 'Diagnosis'), col('status', 'Status'), ...DIAGNOSIS_OPTIONAL.filter((c) => rows.some((r) => r[c.key]))];\n}\n\nfunction unmappedReason(r: FhirResource): string {\n switch (r.resourceType) {\n case 'Observation': {\n const codes = categoryCodings((r as fhir4.Observation).category).map((c) => c.code).filter(Boolean);\n return codes.length ? `Observation category \"${codes.join(', ')}\" is not mapped` : 'Observation has no category';\n }\n case 'Condition':\n return 'Condition has no recognised category';\n case 'ServiceRequest': {\n const labels = categoryCodings((r as fhir4.ServiceRequest).category).map((c) => c.display ?? c.code).filter(Boolean);\n return labels.length ? `ServiceRequest category \"${labels.join(', ')}\" is not mapped` : 'ServiceRequest has no category';\n }\n case 'CarePlan':\n return `CarePlan has no recognised category or intent (${categoryTexts((r as fhir4.CarePlan).category).join(', ') || 'none'})`;\n case 'Appointment': {\n const type = codings((r as fhir4.Appointment).appointmentType)[0]?.code ?? 'none';\n return `Appointment type \"${type}\" is not a follow-up`;\n }\n default:\n return `resource type \"${r.resourceType}\" is not mapped`;\n }\n}\n\nexport interface ConvertOptions {\n showCustomSections?: boolean;\n}\n\nexport function convertPrescriptionBundle(bundle: FhirBundle | null | undefined, options: ConvertOptions = {}): PrescriptionConversion {\n const showCustomSections = options.showCustomSections ?? SHOW_CUSTOM_SECTIONS;\n const entries = Array.isArray(bundle?.entry) ? bundle!.entry : [];\n const resources = entries\n .map((e) => e?.resource)\n .filter((r): r is FhirResource => !!r && typeof r === 'object' && typeof r.resourceType === 'string');\n\n const header = buildHeader(resources);\n const sectionOf = compositionSectionMap(resources);\n const diagnostics: Diagnostic[] = [];\n const report = (r: FhirResource, reason: string) => diagnostics.push({ resourceType: r.resourceType, id: r.id ?? null, reason });\n\n const symptoms: { item: string; codes: EntityCodes }[] = [];\n const vitals: Row[] = [];\n const labResults: Row[] = [];\n const examination: Row[] = [];\n const diagnosis: Row[] = [];\n const history: Row[] = [];\n const medications: Row[] = [];\n const labInvestigations: Row[] = [];\n const procedures: Row[] = [];\n const advice: string[] = [];\n const clinicalNotes: string[] = [];\n const referrals: Row[] = [];\n const admissionNoteLines: string[] = [];\n const customSections: { title: string; items: { key: string; value: string }[] }[] = [];\n let followUp: PrescriptionSection['payload'] | null = null;\n\n const pushRow = (target: Row[], row: Row | null, r: FhirResource) => {\n if (row) target.push(row);\n else report(r, `${r.resourceType} has no display name`);\n };\n\n for (const r of resources) {\n try {\n const pile = classifyResource(r, sectionOf.get(`${r.resourceType}/${r.id ?? ''}`));\n switch (pile) {\n case 'header':\n break;\n case 'symptoms': {\n const symptom = symptomItem(r as fhir4.Observation | fhir4.Condition);\n if (symptom) symptoms.push(symptom);\n else report(r, 'Observation has no display name');\n break;\n }\n case 'vitals':\n pushRow(vitals, vitalRow(r as fhir4.Observation), r);\n break;\n case 'labResults': {\n const row = labResultRow(r as fhir4.Observation);\n if (row) labResults.push(row);\n else report(r, 'Observation \"laboratory\" has no value to show as a lab result');\n break;\n }\n case 'examination':\n pushRow(examination, examinationRow(r as fhir4.Observation), r);\n break;\n case 'diagnosis':\n pushRow(diagnosis, diagnosisRow(r as fhir4.Condition), r);\n break;\n case 'history':\n if (r.resourceType === 'Condition') pushRow(history, historyRowFromCondition(r as fhir4.Condition), r);\n else if (r.resourceType === 'Observation') pushRow(history, socialHistoryRow(r as fhir4.Observation), r);\n else if (r.resourceType === 'FamilyMemberHistory') {\n const rows = familyHistoryRows(r as fhir4.FamilyMemberHistory);\n if (rows.length) history.push(...rows);\n else report(r, 'FamilyMemberHistory has no condition');\n } else if (r.resourceType === 'Procedure') pushRow(history, pastProcedureRow(r as fhir4.Procedure), r);\n else if (r.resourceType === 'AllergyIntolerance') pushRow(history, allergyRow(r as fhir4.AllergyIntolerance), r);\n break;\n case 'medications':\n pushRow(medications, medicationRow(r as fhir4.MedicationRequest), r);\n break;\n case 'labInvestigations':\n pushRow(labInvestigations, labInvestigationRow(r as fhir4.ServiceRequest), r);\n break;\n case 'procedures':\n pushRow(procedures, procedureRow(r as fhir4.ServiceRequest), r);\n break;\n case 'advice': {\n const item = carePlanText(r as fhir4.CarePlan);\n if (item) advice.push(item);\n else report(r, 'CarePlan advice has no text');\n break;\n }\n case 'clinicalNote': {\n const note = carePlanText(r as fhir4.CarePlan);\n if (note) clinicalNotes.push(note);\n else report(r, 'CarePlan clinical note has no text');\n break;\n }\n case 'notes':\n report(r, `free-text note \"${conceptDisplay((r as fhir4.Observation).code) ?? 'Note'}\"; narrative sections are not shown`);\n break;\n case 'referral':\n pushRow(referrals, referralRow(r as fhir4.ServiceRequest), r);\n break;\n case 'ipAdmission':\n admissionNoteLines.push(admissionNotes(r as fhir4.ServiceRequest));\n break;\n case 'customSection': {\n const cp = r as fhir4.CarePlan;\n if (!showCustomSections) report(r, `custom section \"${customSectionTitle(cp)}\" is a doctor-tool section; not shown`);\n else if (!customSectionItems(cp).length) report(r, `custom section \"${customSectionTitle(cp)}\" has no notes`);\n else customSections.push({ title: customSectionTitle(cp), items: customSectionItems(cp) });\n break;\n }\n case 'followUp': {\n const payload = followUpPayload(r as fhir4.Appointment, header.date);\n if (payload) followUp = payload;\n else report(r, 'Appointment has no start date');\n break;\n }\n default:\n report(r, unmappedReason(r));\n }\n } catch (e) {\n report(r, `could not be read: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n\n // A custom section titled like a standard section folds into it after the real entries; the rest stay free-form cards\n const freeFormSections: typeof customSections = [];\n const piles: Record<FoldTarget, Row[] | null> = { symptoms: null, advice: null, medications, diagnosis, procedures, labInvestigations, labResults, examination, history, vitals, referrals };\n for (const custom of customSections) {\n const target = foldTargetOf(custom.title);\n if (!target) { freeFormSections.push(custom); continue; }\n for (const { key, value } of custom.items) {\n const line = value ? `${key}: ${value}` : key;\n if (target === 'symptoms') symptoms.push({ item: line, codes: { eka_code: '', snomed_code: '' } });\n else if (target === 'advice') advice.push(line);\n else piles[target]!.push(foldedRow(target, key, value));\n }\n }\n\n const sections: PrescriptionSection[] = [];\n let order = 0;\n const add = (key: string, display_name: string, kind: PrescriptionSection['kind'], payload: PrescriptionSection['payload']) =>\n sections.push({ key, display_name, kind, payload, order: ++order });\n\n if (symptoms.length) add('symptoms', 'Symptoms', 'LIST', { items: symptoms.map((x) => x.item), codes: symptoms.map((x) => x.codes) }); else order++;\n if (vitals.length) add('vitals', 'Vitals', 'VITAL_TABLE', { headers: VITAL_HEADERS, rows: vitals }); else order++;\n if (examination.length) add('examination_findings', 'Examination Findings', 'EXAMINATION_FINDINGS', { headers: EXAM_HEADERS, rows: examination }); else order++;\n if (diagnosis.length) add('diagnosis', 'Diagnosis', 'DIAGNOSIS', { headers: diagnosisHeaders(diagnosis), rows: diagnosis }); else order++;\n if (history.length) add('medical_history', 'Medical History', 'PATIENT_MEDICAL_HISTORY', { headers: HISTORY_HEADERS, rows: history }); else order++;\n if (medications.length) add('medications', 'Medications', 'MEDICATION_TABLE', { headers: MEDICATION_HEADERS, rows: medications }); else order++;\n if (labInvestigations.length) add('lab_investigations', 'Lab Investigations', 'LAB_INVESTIGATIONS', { headers: LAB_HEADERS, rows: labInvestigations }); else order++;\n if (labResults.length) add('lab_results', 'Lab Results', 'LAB_RESULTS', { headers: LAB_RESULT_HEADERS, rows: labResults }); else order++;\n if (procedures.length) add('procedures', 'Procedures', 'PROCEDURES', { headers: PROCEDURE_HEADERS, rows: procedures }); else order++;\n if (advice.length) add('advice', 'Advice', 'LIST', { items: advice }); else order++;\n if (clinicalNotes.length) add('clinical_notes', 'Clinical Notes', 'LIST', { items: clinicalNotes }); else order++;\n if (followUp) add('follow_up', 'Follow-up', 'FOLLOW_UP', followUp); else order++;\n if (referrals.length) add('referral', 'Referral', 'REFERRAL', { headers: REFERRAL_HEADERS, rows: referrals }); else order++;\n const admission: IpAdmissionPayload = { recommended: true, procedures: [], notes: admissionNoteLines.filter(Boolean).join('\\n') };\n if (admissionNoteLines.length) add('ip_admission', 'IP Admission', 'IP_ADMISSION', admission); else order++;\n const taken = new Set(sections.map((s) => s.key));\n for (const custom of freeFormSections) add(uniqueKey(slug(custom.title), taken), custom.title, 'KEY_VALUE', { items: custom.items });\n\n return { header, sections, diagnostics };\n}\n","import { useEffect, useState } from \"react\";\n\nexport function usePdfHref(url: string | null, base64: string | null): string | null {\n const [href, setHref] = useState<string | null>(url);\n useEffect(() => {\n if (url) {\n setHref(url);\n return;\n }\n if (!base64) {\n setHref(null);\n return;\n }\n try {\n const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));\n const objectUrl = URL.createObjectURL(new Blob([bytes], { type: \"application/pdf\" }));\n setHref(objectUrl);\n return () => URL.revokeObjectURL(objectUrl);\n } catch {\n setHref(`data:application/pdf;base64,${base64}`);\n return;\n }\n }, [url, base64]);\n return href;\n}\n"]}
@@ -3,10 +3,10 @@
3
3
 
4
4
 
5
5
 
6
- var _chunkPMB6SGPMjs = require('./chunk-PMB6SGPM.js');
6
+ var _chunkNQXDAXN5js = require('./chunk-NQXDAXN5.js');
7
7
 
8
8
 
9
- var _chunkKCEHGEHVjs = require('./chunk-KCEHGEHV.js');
9
+ var _chunkZJMFXE5Rjs = require('./chunk-ZJMFXE5R.js');
10
10
 
11
11
 
12
12
 
@@ -105,7 +105,7 @@ function PrescriptionSectionBody({ section }) {
105
105
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, FieldRows, { fields: p.items.map((item) => ({ label: item.key, value: item.value || "\u2014" })) });
106
106
  case "FOLLOW_UP": {
107
107
  const f = p;
108
- const date = _chunkPMB6SGPMjs.isoToDisplayDate.call(void 0, f.date);
108
+ const date = _chunkNQXDAXN5js.isoToDisplayDate.call(void 0, f.date);
109
109
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
110
110
  FieldRows,
111
111
  {
@@ -146,7 +146,7 @@ var PrescriptionSectionCard = _react.memo.call(void 0, function PrescriptionSect
146
146
  // src/visits/components/PrescriptionPanel.tsx
147
147
 
148
148
  function PrescriptionPanel({ conversion, dayKey, appointmentId, onBack }) {
149
- const { openVisitOriginal, attachToContext } = _chunkKCEHGEHVjs.useSmartRecordsActions.call(void 0, );
149
+ const { openVisitOriginal, attachToContext } = _chunkZJMFXE5Rjs.useSmartRecordsActions.call(void 0, );
150
150
  const { header, sections } = conversion;
151
151
  const { prescriptionId } = header;
152
152
  _react.useEffect.call(void 0, () => {
@@ -154,12 +154,12 @@ function PrescriptionPanel({ conversion, dayKey, appointmentId, onBack }) {
154
154
  }, [header, sections]);
155
155
  const hasPdf = !!(header.pdfUrl || header.pdfBase64);
156
156
  const handleViewOriginal = _react.useCallback.call(void 0, () => openVisitOriginal(dayKey, appointmentId), [openVisitOriginal, dayKey, appointmentId]);
157
- const date = _chunkPMB6SGPMjs.isoToDisplayDate.call(void 0, header.date);
157
+ const date = _chunkNQXDAXN5js.isoToDisplayDate.call(void 0, header.date);
158
158
  const isEmpty = sections.length === 0;
159
159
  const handleAddToContext = _react.useCallback.call(void 0, () => {
160
160
  if (!prescriptionId) return;
161
- void _optionalChain([attachToContext, 'optionalCall', _6 => _6(prescriptionId, date ? `Prescription \xB7 ${date}` : "Prescription")]);
162
- }, [attachToContext, prescriptionId, date]);
161
+ void _optionalChain([attachToContext, 'optionalCall', _6 => _6(prescriptionId, date ? `Prescription \xB7 ${date}` : "Prescription", appointmentId)]);
162
+ }, [attachToContext, prescriptionId, date, appointmentId]);
163
163
  const showAddToContext = !!attachToContext && !!prescriptionId && !isEmpty;
164
164
  const sectionCount = isEmpty ? "No sections" : `${sections.length} section${sections.length !== 1 ? "s" : ""}`;
165
165
  const meta = [date, sectionCount].filter(Boolean).join(" \xB7 ");
@@ -194,7 +194,7 @@ function PrescriptionPanel({ conversion, dayKey, appointmentId, onBack }) {
194
194
  function VisitRecordPanel({ appointmentId, onBack }) {
195
195
  const { store } = _chunkTAUICEVAjs.useSdk.call(void 0, );
196
196
  const visit = _zustand.useStore.call(void 0, store, (s) => s.visits.byId[appointmentId]);
197
- const { status, retry, conversion } = _chunkPMB6SGPMjs.usePrescription.call(void 0, _nullishCoalesce(_optionalChain([visit, 'optionalAccess', _7 => _7.prescriptionId]), () => ( null)));
197
+ const { status, retry, conversion } = _chunkNQXDAXN5js.usePrescription.call(void 0, _nullishCoalesce(_optionalChain([visit, 'optionalAccess', _7 => _7.prescriptionId]), () => ( null)));
198
198
  const isLoading = !!_optionalChain([visit, 'optionalAccess', _8 => _8.prescriptionId]) && status === "loading";
199
199
  let heading = "Visit details";
200
200
  let text = "Details for this visit will appear here.";
@@ -208,7 +208,7 @@ function VisitRecordPanel({ appointmentId, onBack }) {
208
208
  if (_optionalChain([visit, 'optionalAccess', _9 => _9.prescriptionId]) && status === "loaded" && conversion) {
209
209
  const hasPdf = !!(conversion.header.pdfUrl || conversion.header.pdfBase64);
210
210
  if (conversion.sections.length === 0 && hasPdf) {
211
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkPMB6SGPMjs.VisitOriginalPanel, { appointmentId, onBack });
211
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkNQXDAXN5js.VisitOriginalPanel, { appointmentId, onBack });
212
212
  }
213
213
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, PrescriptionPanel, { conversion, dayKey: visit.dayKey, appointmentId, onBack });
214
214
  }
@@ -244,4 +244,4 @@ function VisitRecordPanel({ appointmentId, onBack }) {
244
244
 
245
245
 
246
246
  exports.VisitPanelHeader = VisitPanelHeader; exports.weekdayOf = weekdayOf; exports.PrescriptionPanel = PrescriptionPanel; exports.VisitRecordPanel = VisitRecordPanel;
247
- //# sourceMappingURL=chunk-L5BDCHZM.js.map
247
+ //# sourceMappingURL=chunk-PA6BAC4L.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/medical-records-ui/medical-records-ui/dist/chunk-PA6BAC4L.js","../src/visits/components/VisitRecordPanel.tsx","../src/visits/components/VisitPanelHeader.tsx","../src/visits/components/PrescriptionPanel.tsx","../src/visits/components/PrescriptionSectionCard.tsx","../src/visits/components/PrescriptionSectionBody.tsx"],"names":["jsx","jsxs","PrescriptionSectionCard"],"mappings":"AAAA,6rBAAY;AACZ;AACE;AACA;AACA;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACE;AACA;AACA;AACA;AACF,sDAA4B;AAC5B;AACA;ACdA,kCAAyB;AACzB,2CAA6B;ADgB7B;AACA;AEpBA;AAYI,+CAAA;AAFG,SAAS,gBAAA,CAAiB,EAAE,QAAA,EAAU,QAAA,EAAU,OAAO,CAAA,EAA0B;AACtF,EAAA,uBACE,8BAAA,oBAAA,EAAA,EACG,QAAA,EAAA;AAAA,IAAA,OAAA,mBACC,6BAAA,KAAC,EAAA,EAAI,SAAA,EAAU,iBAAA,EACb,QAAA,kBAAA,8BAAA,QAAC,EAAA,EAAO,IAAA,EAAK,QAAA,EAAS,SAAA,EAAU,iBAAA,EAAkB,OAAA,EAAS,MAAA,EACzD,QAAA,EAAA;AAAA,sBAAA,6BAAA,wBAAC,EAAA,EAAY,IAAA,EAAM,EAAA,EAAI,aAAA,EAAW,KAAA,CAAC,CAAA;AAAA,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A;AACqC,sBAAA;AAAE,MAAA;AAGzC,IAAA;AAGA,oBAAA;AACE,sBAAA;AAEI,wBAAA;AAIkC,wBAAA;AAExC,MAAA;AAEwB,MAAA;AAA+D,QAAA;AAE/C,wBAAA;AACtC,MAAA;AAEJ,IAAA;AAEe,oBAAA;AAGU,sBAAA;AAEjB,sBAAA;AAA8B,wBAAA;AACF,wBAAA;AAC9B,MAAA;AAIA,IAAA;AAUW,IAAA;AAMnB,EAAA;AAEJ;AH0F4E;AACA;AC1J/D;AApBsE;AACxD,EAAA;AACwC,EAAA;AACJ,EAAA;AAEL,EAAA;AAE1C,EAAA;AACH,EAAA;AACyB,EAAA;AACxB,IAAA;AACH,IAAA;AACsB,EAAA;AACnB,IAAA;AACH,IAAA;AACT,EAAA;AAEgE,EAAA;AACE,IAAA;AAChB,IAAA;AACW,MAAA;AAC3D,IAAA;AAC0D,IAAA;AAC5D,EAAA;AAGiB,EAAA;AAEXA,IAAAA;AAAC,MAAA;AAAA,MAAA;AACiB,QAAA;AACoB,QAAA;AACpC,QAAA;AAAA,MAAA;AACF,IAAA;AAGC,oBAAA;AAEqC,sBAAA;AAEhC,sBAAA;AAA8B,wBAAA;AACF,wBAAA;AAC9B,MAAA;AAIA,IAAA;AAAmB,sBAAA;AAEjB,sBAAA;AAA+B,wBAAA;AACF,wBAAA;AAEd,QAAA;AAIjB,MAAA;AAGN,IAAA;AACF,EAAA;AAEJ;ADkK4E;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/medical-records-ui/medical-records-ui/dist/chunk-PA6BAC4L.js","sourcesContent":[null,"\"use client\";\n\nimport { useStore } from \"zustand\";\nimport { LoaderCircle } from \"lucide-react\";\nimport { useSdk } from \"../../connection/useSdk\";\nimport { usePrescription } from \"../connection/usePrescription\";\nimport { Typography } from \"widgets\";\nimport EmptyIllustration from \"illustrations/empty-state\";\nimport { VisitPanelHeader, weekdayOf } from \"./VisitPanelHeader\";\nimport { PrescriptionPanel } from \"./PrescriptionPanel\";\nimport { VisitOriginalPanel } from \"./VisitOriginalPanel\";\n\ninterface VisitRecordPanelProps {\n appointmentId: string;\n onBack?: () => void;\n}\n\nexport function VisitRecordPanel({ appointmentId, onBack }: VisitRecordPanelProps) {\n const { store } = useSdk();\n const visit = useStore(store, (s) => s.visits.byId[appointmentId]);\n const { status, retry, conversion } = usePrescription(visit?.prescriptionId ?? null);\n\n const isLoading = !!visit?.prescriptionId && status === \"loading\";\n\n let heading = \"Visit details\";\n let text = \"Details for this visit will appear here.\";\n if (visit && !visit.prescriptionId) {\n heading = \"No prescription\";\n text = \"No prescription was issued for this appointment.\";\n } else if (status === \"error\") {\n heading = \"Couldn't load the prescription\";\n text = \"Please retry, or contact support if the problem persists.\";\n }\n\n if (visit?.prescriptionId && status === \"loaded\" && conversion) {\n const hasPdf = !!(conversion.header.pdfUrl || conversion.header.pdfBase64);\n if (conversion.sections.length === 0 && hasPdf) {\n return <VisitOriginalPanel appointmentId={appointmentId} onBack={onBack} />;\n }\n return <PrescriptionPanel conversion={conversion} dayKey={visit.dayKey} appointmentId={appointmentId} onBack={onBack} />;\n }\n\n return (\n <div className=\"mr-sv__panel mr-sv__care-context-panel\">\n {visit && (\n <VisitPanelHeader\n dayEpoch={visit.startEpoch}\n subtitle={weekdayOf(visit.startEpoch)}\n onBack={onBack}\n />\n )}\n <div className=\"mr-sv__panel-body\">\n {isLoading ? (\n <div className=\"mr-sv__loading-panel\">\n <LoaderCircle size={44} className=\"mr-sv__loading-spinner\" aria-hidden />\n <div className=\"mr-sv__empty-text\">\n <Typography variant=\"heading\">Loading prescription...</Typography>\n <Typography variant=\"muted\">Fetching the prescription for this visit</Typography>\n </div>\n </div>\n ) : (\n <div className=\"mr-sv__empty\">\n <EmptyIllustration />\n <div className=\"mr-sv__empty-text\">\n <Typography variant=\"heading\">{heading}</Typography>\n <Typography variant=\"muted\">{text}</Typography>\n {status === \"error\" && (\n <button type=\"button\" className=\"mr-sv__ghost-link-btn\" onClick={retry}>\n Retry\n </button>\n )}\n </div>\n </div>\n )}\n </div>\n </div>\n );\n}\n","import { ChevronLeft } from \"lucide-react\";\nimport { epochToDisplay } from \"../../helpers/formatters\";\nimport { Typography } from \"widgets\";\n\ninterface VisitPanelHeaderProps {\n dayEpoch: number;\n subtitle: string;\n onBack?: () => void;\n}\n\nexport function VisitPanelHeader({ dayEpoch, subtitle, onBack }: VisitPanelHeaderProps) {\n return (\n <>\n {onBack && (\n <div className=\"mr-sv__back-row\">\n <button type=\"button\" className=\"mr-sv__back-btn\" onClick={onBack}>\n <ChevronLeft size={16} aria-hidden />\n Back\n </button>\n </div>\n )}\n <div className=\"mr-cc-panel__header\">\n <div className=\"mr-cc-panel__header-left\">\n <div className=\"mr-cc-panel__info\">\n <div className=\"mr-cc-panel__name-row\">\n <Typography variant=\"label\" as=\"span\" className=\"mr-cc-panel__name\">\n {epochToDisplay(dayEpoch)}\n </Typography>\n </div>\n <span className=\"mr-cc-panel__sub\">{subtitle}</span>\n </div>\n </div>\n </div>\n </>\n );\n}\n\nexport function weekdayOf(epochMs: number): string {\n return new Date(epochMs).toLocaleString(\"en\", { weekday: \"short\" });\n}\n","\"use client\";\n\nimport { useCallback, useEffect } from \"react\";\nimport { ChevronLeft, ChevronRight } from \"lucide-react\";\nimport { Typography } from \"widgets\";\nimport EmptyIllustration from \"illustrations/empty-state\";\nimport { useSmartRecordsActions } from \"../../views/context/SmartRecordsActionsContext\";\nimport type { PrescriptionConversion } from \"../prescription/types\";\nimport { isoToDisplayDate } from \"../prescription/fhir-utils\";\nimport { PrescriptionSectionCard } from \"./PrescriptionSectionCard\";\n\ninterface PrescriptionPanelProps {\n conversion: PrescriptionConversion;\n dayKey: string;\n appointmentId: string;\n onBack?: () => void;\n}\n\nexport function PrescriptionPanel({ conversion, dayKey, appointmentId, onBack }: PrescriptionPanelProps) {\n const { openVisitOriginal, attachToContext } = useSmartRecordsActions();\n const { header, sections } = conversion;\n const { prescriptionId } = header;\n\n // TEMP log\n useEffect(() => {\n console.log(\"[visits] prescription panel\", { prescriptionId: header.prescriptionId, header, sections });\n }, [header, sections]);\n\n const hasPdf = !!(header.pdfUrl || header.pdfBase64);\n const handleViewOriginal = useCallback(() => openVisitOriginal(dayKey, appointmentId), [openVisitOriginal, dayKey, appointmentId]);\n const date = isoToDisplayDate(header.date);\n const isEmpty = sections.length === 0;\n\n const handleAddToContext = useCallback(() => {\n if (!prescriptionId) return;\n void attachToContext?.(prescriptionId, date ? `Prescription · ${date}` : \"Prescription\", appointmentId);\n }, [attachToContext, prescriptionId, date, appointmentId]);\n \n const showAddToContext = !!attachToContext && !!prescriptionId && !isEmpty;\n const sectionCount = isEmpty ? \"No sections\" : `${sections.length} section${sections.length !== 1 ? \"s\" : \"\"}`;\n const meta = [date, sectionCount].filter(Boolean).join(\" · \");\n\n return (\n <div className=\"mr-sv__panel\">\n {onBack && (\n <div className=\"mr-sv__back-row\">\n <button type=\"button\" className=\"mr-sv__back-btn\" onClick={onBack}>\n <ChevronLeft size={16} aria-hidden />\n Back\n </button>\n </div>\n )}\n <div className=\"mr-cc-panel__header\">\n <div className=\"mr-cc-panel__header-left\">\n <div className=\"mr-cc-panel__info\">\n <div className=\"mr-cc-panel__name-row\">\n <Typography variant=\"label\" as=\"span\" className=\"mr-cc-panel__name\">\n Prescription\n </Typography>\n </div>\n <span className=\"mr-cc-panel__sub\">{meta}</span>\n </div>\n </div>\n {hasPdf && (\n <button type=\"button\" className=\"mr-sv__ghost-link-btn\" onClick={handleViewOriginal}>\n View original\n <ChevronRight size={16} aria-hidden />\n </button>\n )}\n </div>\n\n <div className=\"mr-sv__panel-body mr-rx-body\">\n {isEmpty ? (\n <div className=\"mr-sv__empty\">\n <EmptyIllustration />\n <div className=\"mr-sv__empty-text\">\n <Typography variant=\"heading\">No structured data</Typography>\n <Typography variant=\"muted\">This prescription has no sections to show here.</Typography>\n </div>\n </div>\n ) : (\n <div className=\"mr-rx-scroll\">\n <div className=\"mr-rx-cards\">\n {sections.map((section) => (\n <PrescriptionSectionCard key={section.key} section={section} />\n ))}\n </div>\n </div>\n )}\n </div>\n\n {showAddToContext && (\n <div className=\"mr-cc-table__footer mr-rx-footer\">\n <button type=\"button\" className=\"mr-cc-table__copy-note-btn\" onClick={handleAddToContext}>\n Attach to session\n </button>\n </div>\n )}\n </div>\n );\n}\n","import { memo } from \"react\";\nimport type { PrescriptionSection } from \"../prescription/types\";\nimport { PrescriptionSectionBody } from \"./PrescriptionSectionBody\";\n\ninterface PrescriptionSectionCardProps {\n section: PrescriptionSection;\n}\n\nexport const PrescriptionSectionCard = memo(function PrescriptionSectionCard({ section }: PrescriptionSectionCardProps) {\n return (\n <div className=\"mr-rx-card\">\n <div className=\"mr-rx-card__head\">\n <span className=\"mr-rx-card__title\">{section.display_name}</span>\n </div>\n <PrescriptionSectionBody section={section} />\n </div>\n );\n});\n","import type { FollowUpPayload, IpAdmissionPayload, KeyValuePayload, ListPayload, PrescriptionSection, TableColumn, TablePayload } from \"../prescription/types\";\nimport { isoToDisplayDate } from \"../prescription/fhir-utils\";\n\ninterface PrescriptionSectionBodyProps {\n section: PrescriptionSection;\n}\n\ntype Row = Record<string, string>;\n\nconst HIDDEN_COLUMNS = new Set([\"diagnosis_id\", \"icd10_code\", \"icd10_name\", \"eka_code\", \"snomed_code\", \"medication_id\", \"investigationId\", \"ekaId\"]);\n\nconst HISTORY_CATEGORY: Record<string, string> = {\n condition: \"Condition\",\n lifestyle_habit: \"Lifestyle habit\",\n drug_allergy: \"Drug allergy\",\n other_allergy: \"Other allergy\",\n family_history: \"Family history\",\n past_procedure: \"Past procedure\",\n};\n\nconst capitalize = (text: string) => (text ? text[0].toUpperCase() + text.slice(1) : text);\n\nfunction cellText(kind: PrescriptionSection[\"kind\"], key: string, value: string): string {\n if (kind === \"PATIENT_MEDICAL_HISTORY\" && key === \"category\") return HISTORY_CATEGORY[value] ?? value;\n if (kind === \"PATIENT_MEDICAL_HISTORY\" && key === \"status\") return value === \"yes\" ? \"Yes\" : value === \"no\" ? \"No\" : value;\n if (kind === \"EXAMINATION_FINDINGS\" && key === \"status\") return capitalize(value);\n return value;\n}\n\nfunction visibleColumns(headers: TableColumn[], rows: Row[]): TableColumn[] {\n return headers.filter((h, i) => !HIDDEN_COLUMNS.has(h.key) && (i === 0 || rows.some((r) => r[h.key]?.trim())));\n}\n\nconst WIDE_COLUMNS = new Set([\"notes\", \"note\", \"remarks\", \"detail\", \"instructions\"]);\n\nfunction gridTemplate(columns: TableColumn[]): string {\n return columns.map((c, i) => (i === 0 ? \"minmax(0, 1.7fr)\" : WIDE_COLUMNS.has(c.key) ? \"minmax(0, 1.4fr)\" : \"minmax(0, 1fr)\")).join(\" \");\n}\n\nfunction SectionTable({ kind, payload }: { kind: PrescriptionSection[\"kind\"]; payload: TablePayload }) {\n const columns = visibleColumns(payload.headers, payload.rows);\n const nameKey = columns[0]?.key ?? \"\";\n if (columns.length <= 1) {\n return (\n <ol className=\"mr-rx-list\">\n {payload.rows.map((r, i) => (\n <li key={i}>{r[nameKey] ?? \"\"}</li>\n ))}\n </ol>\n );\n }\n const style = { gridTemplateColumns: gridTemplate(columns) };\n return (\n <div className=\"mr-rx-tbl\">\n <div className=\"mr-rx-tblh\" style={style}>\n {columns.map((c) => (\n <span key={c.key}>{c.label}</span>\n ))}\n </div>\n {payload.rows.map((r, i) => (\n <div className=\"mr-rx-tblr\" style={style} key={i}>\n {columns.map((c, ci) => {\n const value = cellText(kind, c.key, r[c.key] ?? \"\").trim();\n return (\n <span key={c.key} className={ci === 0 ? \"mr-rx-mn\" : undefined}>\n {value || \"—\"}\n </span>\n );\n })}\n </div>\n ))}\n </div>\n );\n}\n\nfunction FieldRows({ fields }: { fields: { label: string; value: string; hint?: string }[] }) {\n return (\n <dl className=\"mr-rx-kv\">\n {fields\n .filter((f) => f.value)\n .map((f) => (\n <div key={f.label}>\n <dt>{f.label}</dt>\n <dd>\n {f.value}\n {f.hint && <span className=\"mr-rx-u\"> {f.hint}</span>}\n </dd>\n </div>\n ))}\n </dl>\n );\n}\n\nexport function PrescriptionSectionBody({ section }: PrescriptionSectionBodyProps) {\n const p = section.payload;\n switch (section.kind) {\n case \"LIST\":\n return (\n <ol className=\"mr-rx-list\">\n {(p as ListPayload).items.map((item, i) => (\n <li key={i}>{item}</li>\n ))}\n </ol>\n );\n case \"KEY_VALUE\":\n return <FieldRows fields={(p as KeyValuePayload).items.map((item) => ({ label: item.key, value: item.value || \"—\" }))} />;\n case \"FOLLOW_UP\": {\n const f = p as FollowUpPayload;\n const date = isoToDisplayDate(f.date);\n return (\n <FieldRows\n fields={[\n { label: \"Follow-up date\", value: date ?? (f.date || f.interval), hint: date ? f.interval : undefined },\n { label: \"Notes\", value: f.notes },\n ]}\n />\n );\n }\n case \"IP_ADMISSION\": {\n const a = p as IpAdmissionPayload;\n return (\n <FieldRows\n fields={[\n { label: \"Admission advised\", value: a.recommended ? \"Yes\" : \"No\" },\n { label: \"Recommended procedures\", value: a.procedures.map((x) => x.procedure).filter(Boolean).join(\" · \") },\n { label: \"Notes\", value: a.notes },\n ]}\n />\n );\n }\n default:\n return <SectionTable kind={section.kind} payload={p as TablePayload} />;\n }\n}\n"]}