@pih/esm-commons-app 2.1.1-pre.119 → 2.1.1-pre.122

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.
@@ -1,4 +1,4 @@
1
- import { Type } from '@openmrs/esm-framework';
1
+ import { Type, validators } from '@openmrs/esm-framework';
2
2
 
3
3
  /**
4
4
  * In OpenMRS Microfrontends, all config parameters are optional.
@@ -27,6 +27,43 @@ export const configSchema = {
27
27
  _description: 'UUID for the Heart beat of 2nd fetus concept',
28
28
  },
29
29
  },
30
+ dispensing: {
31
+ medicationDispenseLabel: {
32
+ enabled: {
33
+ _type: Type.Boolean,
34
+ _description:
35
+ "Enable the Print label button on completed medication dispense records. Requires the Zebra Browser Print desktop app to be installed and running on the user's machine.",
36
+ _default: true,
37
+ },
38
+ reportDefinitionUuid: {
39
+ _type: Type.UUID,
40
+ _description: 'UUID of the report definition used to generate the medication dispense label PDF.',
41
+ _default: '52f6e567-4e36-11f1-94ae-5e789c4020d9',
42
+ },
43
+ reportDesignUuid: {
44
+ _type: Type.UUID,
45
+ _description: 'UUID of the PDF report design for the medication dispense label.',
46
+ _default: '75bde2ff-4eb4-11f1-94ae-5e789c4020d9',
47
+ },
48
+ printMethod: {
49
+ _type: Type.String,
50
+ _description:
51
+ '"pdf-direct" sends raw PDF bytes to the printer, which renders them using its own firmware ' +
52
+ '(requires Link-OS with apl.enable = "pdf" — no license key needed). ' +
53
+ '"browser-print" has the Browser Print helper convert PDF→ZPL first, which works on any Zebra printer ' +
54
+ 'but requires a PDF conversion license key on Windows/macOS.',
55
+ _default: 'browser-print',
56
+ _validators: [validators.oneOf(['pdf-direct', 'browser-print'])],
57
+ },
58
+ browserPrintFeatureKey: {
59
+ _type: Type.String,
60
+ _description:
61
+ 'PDF conversion license key for the Browser Print helper on Windows/macOS. ' +
62
+ 'Only used when printMethod is "browser-print". Not needed on Linux with the open-source shim.',
63
+ _default: '',
64
+ },
65
+ },
66
+ },
30
67
  };
31
68
 
32
69
  export interface ConfigObject {
@@ -34,5 +71,15 @@ export interface ConfigObject {
34
71
  hemoglobinUuid: string;
35
72
  glucoseUuid: string;
36
73
  fhrUuid: string;
74
+ secondFhrUuid: string;
75
+ };
76
+ dispensing: {
77
+ medicationDispenseLabel: {
78
+ enabled: boolean;
79
+ reportDefinitionUuid: string;
80
+ reportDesignUuid: string;
81
+ printMethod: 'pdf-direct' | 'browser-print';
82
+ browserPrintFeatureKey: string;
83
+ };
37
84
  };
38
85
  }
@@ -0,0 +1,66 @@
1
+ import React, { useState } from 'react';
2
+ import { Button } from '@carbon/react';
3
+ import { Printer } from '@carbon/react/icons';
4
+ import { useTranslation } from 'react-i18next';
5
+ import { showSnackbar, useConfig } from '@openmrs/esm-framework';
6
+ import { type ConfigObject } from '../config-schema';
7
+ import { printDispenseLabelToZebra } from './zebra-label-print.resource';
8
+
9
+ // Minimal interface — mirrors the relevant fields from the dispensing app's MedicationDispense type
10
+ // without introducing a hard dependency on that module.
11
+ interface MedicationDispense {
12
+ id?: string;
13
+ status?: string;
14
+ }
15
+
16
+ interface ZebraLabelPrintActionProps {
17
+ medicationDispense: MedicationDispense;
18
+ patientUuid: string;
19
+ encounterUuid: string;
20
+ }
21
+
22
+ const COMPLETED_STATUS = 'completed';
23
+
24
+ const ZebraLabelPrintAction: React.FC<ZebraLabelPrintActionProps> = ({ medicationDispense }) => {
25
+ const { t } = useTranslation();
26
+ const { medicationDispenseLabel: config } = useConfig<ConfigObject>().dispensing;
27
+ const [isPrinting, setIsPrinting] = useState(false);
28
+
29
+ if (!config.enabled || medicationDispense?.status !== COMPLETED_STATUS || !medicationDispense?.id) {
30
+ return null;
31
+ }
32
+
33
+ const handlePrint = () => {
34
+ setIsPrinting(true);
35
+ printDispenseLabelToZebra(
36
+ medicationDispense.id,
37
+ config.reportDefinitionUuid,
38
+ config.reportDesignUuid,
39
+ config.printMethod,
40
+ config.browserPrintFeatureKey,
41
+ )
42
+ .then(() => {
43
+ showSnackbar({
44
+ kind: 'success',
45
+ title: t('success', 'Success'),
46
+ subtitle: t('labelSentToPrinter', 'Label sent to printer'),
47
+ });
48
+ })
49
+ .catch((err: Error) => {
50
+ showSnackbar({
51
+ kind: 'error',
52
+ title: t('printLabelFailed', 'Print label failed'),
53
+ subtitle: err?.message ?? t('unknownError', 'An unknown error occurred'),
54
+ });
55
+ })
56
+ .finally(() => setIsPrinting(false));
57
+ };
58
+
59
+ return (
60
+ <Button kind="ghost" size="sm" renderIcon={Printer} disabled={isPrinting} onClick={handlePrint}>
61
+ {isPrinting ? t('printing', 'Printing…') : t('printLabel', 'Print label')}
62
+ </Button>
63
+ );
64
+ };
65
+
66
+ export default ZebraLabelPrintAction;
@@ -0,0 +1,49 @@
1
+ import { openmrsFetch, restBaseUrl } from '@openmrs/esm-framework';
2
+ import { getDefaultZebraDevice } from './zebra-pdf-print';
3
+
4
+ export async function printDispenseLabelToZebra(
5
+ dispenseUuid: string,
6
+ reportDefinitionUuid: string,
7
+ reportDesignUuid: string,
8
+ printMethod: 'pdf-direct' | 'browser-print' = 'pdf-direct',
9
+ browserPrintFeatureKey = '',
10
+ ): Promise<void> {
11
+ const url =
12
+ `${restBaseUrl}/reportingrest/runReport/${reportDefinitionUuid}/${reportDesignUuid}` +
13
+ `?medicationDispenseUuid=${encodeURIComponent(dispenseUuid)}`;
14
+
15
+ const [response, device] = await Promise.all([openmrsFetch(url, { method: 'POST' }), getDefaultZebraDevice()]);
16
+
17
+ const pdf = await response.blob();
18
+
19
+ if (device) {
20
+ try {
21
+ if (printMethod === 'pdf-direct') {
22
+ await device.sendFile(pdf);
23
+ } else {
24
+ const options = browserPrintFeatureKey ? { keys: { pdf: browserPrintFeatureKey } } : undefined;
25
+ await device.convertAndSendFile(pdf, options);
26
+ }
27
+ return;
28
+ } catch {
29
+ // fall through to browser print dialog
30
+ }
31
+ }
32
+
33
+ openBrowserPrintDialog(pdf);
34
+ }
35
+
36
+ function openBrowserPrintDialog(blob: Blob): void {
37
+ const url = URL.createObjectURL(blob);
38
+ const iframe = document.createElement('iframe');
39
+ iframe.style.cssText = 'position:fixed;width:0;height:0;opacity:0;pointer-events:none;';
40
+ iframe.src = url;
41
+ document.body.appendChild(iframe);
42
+ iframe.onload = () => {
43
+ iframe.contentWindow?.print();
44
+ setTimeout(() => {
45
+ document.body.removeChild(iframe);
46
+ URL.revokeObjectURL(url);
47
+ }, 60_000);
48
+ };
49
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Minimal Zebra Browser Print client for PDF label printing.
3
+ *
4
+ * Both print pathways route through the Zebra Browser Print helper app
5
+ * running locally at 127.0.0.1:9100 (HTTP) or 127.0.0.1:9101 (HTTPS).
6
+ * The helper must be installed and running on the user's machine.
7
+ *
8
+ * PATHWAY 1 — PDF Direct (recommended for Link-OS printers):
9
+ * Sends raw PDF bytes to the helper via POST /write.
10
+ * The helper proxies the bytes to the printer, which rasterizes the PDF
11
+ * internally using its own firmware renderer. Requires the printer to have
12
+ * Link-OS with apl.enable = "pdf". No license key needed.
13
+ *
14
+ * PATHWAY 2 — Browser Print conversion (fallback for older printers):
15
+ * Sends the PDF to the helper via POST /convert.
16
+ * The helper converts PDF→ZPL and sends the resulting ZPL to the printer.
17
+ * Works on any Zebra printer. On Windows/macOS with the official Zebra helper,
18
+ * a PDF conversion license key is required. On Linux with the open-source shim
19
+ * (pih/zebra-printing-tools), no key is needed.
20
+ */
21
+
22
+ const HELPER_BASE =
23
+ typeof location !== 'undefined' && location.protocol === 'https:'
24
+ ? 'https://127.0.0.1:9101'
25
+ : 'http://127.0.0.1:9100';
26
+
27
+ async function helperRequest(method: string, path: string, body?: string | FormData): Promise<string> {
28
+ const opts: RequestInit = { method };
29
+ if (body !== undefined) {
30
+ if (typeof body === 'string') {
31
+ opts.headers = { 'Content-Type': 'text/plain;charset=UTF-8' };
32
+ opts.body = body;
33
+ } else {
34
+ opts.body = body; // FormData — do not set Content-Type; fetch supplies the multipart boundary
35
+ }
36
+ }
37
+ const r = await fetch(HELPER_BASE + path, opts);
38
+ const text = await r.text();
39
+ if (!r.ok) throw new Error(`Zebra helper ${method} ${path} → ${r.status}: ${text}`);
40
+ return text;
41
+ }
42
+
43
+ export class ZebraDevice {
44
+ private readonly _json: object;
45
+ private _queue: Promise<unknown> = Promise.resolve();
46
+
47
+ constructor(json: object) {
48
+ this._json = json;
49
+ }
50
+
51
+ private _enqueue<T>(op: () => Promise<T>): Promise<T> {
52
+ // Serialize all operations on this device so concurrent calls don't
53
+ // interleave their /write+/read pairs and produce garbled responses.
54
+ const next = this._queue.then(
55
+ () => op(),
56
+ () => op(),
57
+ );
58
+ this._queue = next.catch(() => {});
59
+ return next;
60
+ }
61
+
62
+ /**
63
+ * PDF Direct: raw PDF bytes → printer firmware renders them.
64
+ * Simpler and faster when the printer supports it (Link-OS, apl.enable = "pdf").
65
+ */
66
+ sendFile(pdfBlob: Blob): Promise<string> {
67
+ return this._enqueue(() => {
68
+ const fd = new FormData();
69
+ fd.append('json', JSON.stringify({ device: this._json }));
70
+ fd.append('blob', pdfBlob);
71
+ return helperRequest('POST', '/write', fd);
72
+ });
73
+ }
74
+
75
+ /**
76
+ * Browser Print conversion: helper converts PDF→ZPL, then sends ZPL.
77
+ * Works on any Zebra printer. Pass options.keys.pdf for Windows/macOS.
78
+ */
79
+ convertAndSendFile(pdfBlob: Blob, options?: { keys?: { pdf?: string } }): Promise<string> {
80
+ return this._enqueue(() => {
81
+ const opts: Record<string, unknown> = { action: 'print', ...options };
82
+ if (!opts.fromFormat && pdfBlob.type) {
83
+ const t = pdfBlob.type.toLowerCase();
84
+ if (t.startsWith('image/') || t.startsWith('application/')) {
85
+ opts.fromFormat = t.replace('image/', '').replace('application/', '').replace('x-ms-', '');
86
+ }
87
+ }
88
+ const fd = new FormData();
89
+ fd.append('json', JSON.stringify({ options: opts, device: this._json }));
90
+ fd.append('blob', pdfBlob);
91
+ return helperRequest('POST', '/convert', fd);
92
+ });
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Returns the default device registered with the Browser Print helper,
98
+ * or null if the helper is not running or no device is configured.
99
+ */
100
+ export async function getDefaultZebraDevice(): Promise<ZebraDevice | null> {
101
+ try {
102
+ const text = await helperRequest('GET', '/default?type=printer');
103
+ if (!text) return null;
104
+ return new ZebraDevice(JSON.parse(text));
105
+ } catch {
106
+ return null;
107
+ }
108
+ }
package/src/index.ts CHANGED
@@ -47,6 +47,11 @@ export const triageWaitingQueueActions = getAsyncLifecycle(
47
47
  { featureName: 'triageWaitingQueueActions', moduleName },
48
48
  );
49
49
 
50
+ export const zebraLabelPrintAction = getAsyncLifecycle(
51
+ () => import('./dispensing/zebra-label-print-action.extension'),
52
+ { featureName: 'zebraLabelPrintAction', moduleName },
53
+ );
54
+
50
55
  export function startupApp() {
51
56
  defineConfigSchema(moduleName, configSchema);
52
57
  }
package/src/routes.json CHANGED
@@ -28,6 +28,11 @@
28
28
  "name": "triage-waiting-queue-actions",
29
29
  "component": "triageWaitingQueueActions",
30
30
  "slot": "queue-table-triage-waiting-queue-actions-slot"
31
+ },
32
+ {
33
+ "name": "zebra-label-print-action",
34
+ "component": "zebraLabelPrintAction",
35
+ "slot": "medication-dispense-action-slot"
31
36
  }
32
37
  ],
33
38
  "workspaces2": [
@@ -6,15 +6,21 @@
6
6
  "fullInfantDashboard": "Full Infant Dashboard",
7
7
  "fullPatientChart": "Full patient chart",
8
8
  "fullPregnancyDashboard": "Full Pregnancy Dashboard",
9
+ "labelSentToPrinter": "Label sent to printer",
9
10
  "maternalTriageForm": "Maternal triage form",
10
11
  "patientDischarged": "Patient discharged",
11
12
  "patientDischargedMessage": "{{patientName}} has been discharged from the ward.",
12
13
  "patientHasNoActiveVisit": "Patient has no active visit",
14
+ "printing": "Printing…",
15
+ "printLabel": "Print label",
16
+ "printLabelFailed": "Print label failed",
13
17
  "removePatient": "Remove patient",
18
+ "success": "Success",
14
19
  "transition": "Transition",
15
20
  "triage": "Triage",
16
21
  "triageFormSubmitted": "Triage form successfully submitted for {{patient}}.",
17
22
  "undoTransition": "Undo transition",
23
+ "unknownError": "An unknown error occurred",
18
24
  "visitSummary": "Visit summary",
19
25
  "vitalSigns": "Vital signs"
20
26
  }
@@ -1,4 +1,10 @@
1
1
  {
2
+ "labelSentToPrinter": "Etiqueta enviada a la impresora",
2
3
  "patientVisitSummary": "Patient visit summary",
3
- "visitSummary": "Visit summary"
4
+ "printLabel": "Imprimir etiqueta",
5
+ "printLabelFailed": "Error al imprimir la etiqueta",
6
+ "printing": "Imprimiendo…",
7
+ "success": "Éxito",
8
+ "unknownError": "Se produjo un error desconocido",
9
+ "visitSummary": "Resumen de la visita"
4
10
  }
@@ -1,4 +1,10 @@
1
1
  {
2
+ "labelSentToPrinter": "Étiquette envoyée à l'imprimante",
2
3
  "patientVisitSummary": "Patient visit summary",
3
- "visitSummary": "Visit summary"
4
+ "printLabel": "Imprimer l'étiquette",
5
+ "printLabelFailed": "Échec de l'impression de l'étiquette",
6
+ "printing": "Impression en cours…",
7
+ "success": "Succès",
8
+ "unknownError": "Une erreur inconnue s'est produite",
9
+ "visitSummary": "Résumé de la visite"
4
10
  }