From 84e693685fed8cdabfb60cc7ad73f3c708f5f202 Mon Sep 17 00:00:00 2001 From: "adrian.crainic@bgasoft.com" Date: Mon, 23 Nov 2026 16:12:09 +0200 Subject: [PATCH 1/3] Add pdf-report to hl7 --- CHANGELOG.md | 46 +- Cargo.lock | 229 ++ Cargo.toml | 2 + STATUS.md | 14 + changelog.d/2026-11-19-hl7-files.md | 21 + changelog.d/2026-11-19-pdf-reports.md | 26 + changelog.d/2026-11-20-file-receipt-time.md | 12 + console/help/hl7-files.json | 15 + console/help/pdf-reports.json | 23 + console/src-tauri/Cargo.lock | 1 + console/src/api/engine.ts | 8 + console/src/api/ipc/IpcEngineApi.ts | 13 + console/src/api/ipc/channelConfig.ts | 5 + console/src/api/ipc/configNew.test.ts | 4 + console/src/api/ipc/configNewChannels.test.ts | 2 +- console/src/api/ipc/connectorConfig.ts | 13 +- console/src/api/ipc/endpointConfig.test.ts | 30 + console/src/api/ipc/endpointConfig.ts | 52 +- console/src/api/ipc/messageDetail.test.ts | 4 +- console/src/api/ipc/messageMap.ts | 1 + console/src/api/ipc/paths.test.ts | 12 +- console/src/api/ipc/paths.ts | 14 +- console/src/api/ipc/setup.ts | 68 +- console/src/api/ipc/steps.ts | 25 +- console/src/api/ipc/test/messageRecords.ts | 1 + console/src/api/ipc/test/newItems.ts | 2 + console/src/api/ipc/test/specStructs.ts | 1 + .../src/api/mock/MockEngineApi.config.test.ts | 2 + .../mock/MockEngineApi.message-fields.test.ts | 2 +- console/src/api/mock/channelCatalog.ts | 2 + console/src/api/mock/deliveryAttempts.ts | 5 +- console/src/api/mock/endpointCatalog.ts | 3 + console/src/api/mock/index.ts | 7 + console/src/api/mock/mappingCatalog.ts | 12 + console/src/api/mock/messageFields.ts | 4 +- console/src/api/mock/messageKinds.ts | 4 + console/src/api/mock/messageStore.ts | 1 + console/src/api/mock/pdfReports.ts | 118 + console/src/api/mock/validate.ts | 6 +- console/src/api/mock/validateConnector.ts | 24 +- console/src/api/mock/validateEndpoints.ts | 23 + console/src/api/types/config.ts | 21 +- console/src/api/types/core.ts | 9 +- console/src/api/types/messages.ts | 2 + console/src/api/types/setup.ts | 55 +- console/src/features/audit/auditLabels.ts | 1 + .../src/features/config/ConnectorFields.tsx | 19 +- .../config/ConnectorSettings.test.tsx | 37 +- .../src/features/config/EndpointFields.tsx | 69 +- .../features/config/EndpointSettings.test.tsx | 67 + console/src/features/config/PdfTestButton.tsx | 40 + console/src/features/config/StepFields.tsx | 11 + .../src/features/config/TemplateJsonField.tsx | 36 +- .../src/features/config/channelForm.test.ts | 57 + console/src/features/config/channelForm.ts | 20 +- .../src/features/config/connectorProtocols.ts | 21 +- console/src/features/config/endpointForm.ts | 42 +- .../config/presets/ConnectorPresets.tsx | 10 +- .../src/features/config/presets/apply.test.ts | 18 + console/src/features/config/presets/apply.ts | 51 + console/src/features/config/settingsForm.ts | 2 + console/src/features/config/stepForm.ts | 18 +- console/src/features/config/testFixtures.ts | 3 + console/src/features/config/validators.ts | 6 + .../src/features/messages/MessageNotices.tsx | 5 + .../messages/MessageOriginal.test.tsx | 2 +- console/src/features/messages/fixtures.ts | 1 + .../pdfReports/PdfReportTest.module.css | 38 + .../pdfReports/PdfReportTest.test.tsx | 112 + .../src/features/pdfReports/PdfReportTest.tsx | 253 ++ console/src/ipc/generated/AuditAction.ts | 2 +- console/src/ipc/generated/Destination.ts | 4 +- console/src/ipc/generated/FieldPosition.ts | 6 + console/src/ipc/generated/FolderSettings.ts | 13 +- console/src/ipc/generated/Hl7FileSettings.ts | 48 + console/src/ipc/generated/MessageRecord.ts | 4 + console/src/ipc/generated/OneOrMore.ts | 6 + console/src/ipc/generated/PdfField.ts | 51 + console/src/ipc/generated/PdfLine.ts | 15 + console/src/ipc/generated/PdfPage.ts | 15 + console/src/ipc/generated/PdfPhrase.ts | 22 + .../src/ipc/generated/PdfReportSettings.ts | 28 + console/src/ipc/generated/PdfReportTest.ts | 23 + .../src/ipc/generated/PdfReportTestResult.ts | 40 + console/src/ipc/generated/ProtocolKind.ts | 2 +- console/src/ipc/generated/Request.ts | 3 +- console/src/ipc/generated/Response.ts | 3 +- console/src/ipc/generated/SftpSettings.ts | 11 +- console/src/ipc/generated/SourceConnector.ts | 4 +- console/src/ipc/generated/TestDestination.ts | 18 + console/src/ipc/generated/index.ts | 11 + console/src/lib/protocols.ts | 11 + console/src/lib/status.ts | 2 + crates/packie-config/profiles/profiles.json | 641 +++++ crates/packie-config/src/endpoint/files.rs | 68 +- crates/packie-config/src/endpoint/mod.rs | 14 +- crates/packie-config/src/lib.rs | 11 +- .../packie-config/src/protocol/delimited.rs | 14 + crates/packie-config/src/protocol/hl7.rs | 41 +- crates/packie-config/src/protocol/mod.rs | 31 +- crates/packie-config/src/protocol/pdf.rs | 147 + crates/packie-config/src/protocol/profiles.rs | 8 +- crates/packie-config/src/validate/channels.rs | 6 +- .../packie-config/src/validate/endpoints.rs | 62 +- crates/packie-config/src/validate/mod.rs | 1 + crates/packie-config/src/validate/pdf.rs | 128 + .../packie-config/src/validate/protocols.rs | 94 +- crates/packie-config/tests/config.rs | 210 ++ crates/packie-config/tests/profiles.rs | 88 +- crates/packie-core/src/kinds.rs | 4 + crates/packie-engine/Cargo.toml | 4 + crates/packie-engine/src/audit.rs | 14 + crates/packie-engine/src/fields.rs | 75 +- crates/packie-engine/src/handler.rs | 11 +- crates/packie-engine/src/lib.rs | 6 +- crates/packie-engine/src/pdf.rs | 155 ++ crates/packie-engine/src/pdf_test.rs | 296 +++ crates/packie-engine/src/pdf_view.rs | 138 + crates/packie-engine/src/registry.rs | 20 +- crates/packie-engine/src/reports.rs | 18 +- crates/packie-engine/tests/engine.rs | 117 + crates/packie-ipc/src/audit.rs | 2 + crates/packie-ipc/src/lib.rs | 1 + crates/packie-ipc/src/messages.rs | 3 + crates/packie-ipc/src/pdf.rs | 102 + crates/packie-ipc/src/protocol.rs | 6 + crates/packie-pdf/Cargo.toml | 22 + crates/packie-pdf/src/error.rs | 55 + crates/packie-pdf/src/extract/font.rs | 536 ++++ crates/packie-pdf/src/extract/interp.rs | 484 ++++ crates/packie-pdf/src/extract/matrix.rs | 108 + crates/packie-pdf/src/extract/mod.rs | 185 ++ crates/packie-pdf/src/extract/standard14.rs | 2364 +++++++++++++++++ crates/packie-pdf/src/layout.rs | 309 +++ crates/packie-pdf/src/lib.rs | 87 + crates/packie-pdf/src/template.rs | 418 +++ crates/packie-pdf/tests/conformance.rs | 593 +++++ crates/packie-pdf/tests/properties.rs | 121 + crates/packie-pdf/tests/standard14.rs | 153 ++ crates/packie-pdf/tests/support/mod.rs | 350 +++ crates/packie-routing/Cargo.toml | 1 + crates/packie-routing/src/framer/mod.rs | 7 +- .../src/message/delivery/file.rs | 16 +- .../src/message/delivery/mod.rs | 19 +- crates/packie-routing/src/message/files.rs | 4 +- crates/packie-routing/src/message/mod.rs | 29 +- crates/packie-routing/src/message/pdf.rs | 270 ++ crates/packie-routing/src/message/pipeline.rs | 40 +- .../packie-routing/src/message/source/mod.rs | 28 +- .../src/message/sqlite_store/mod.rs | 14 + crates/packie-routing/src/message/store.rs | 9 + .../packie-routing/src/message/transform.rs | 152 +- crates/packie-routing/src/registry/mod.rs | 9 + crates/packie-routing/tests/common/mod.rs | 9 + .../packie-routing/tests/message_hl7_file.rs | 184 ++ crates/packie-routing/tests/message_pdf.rs | 213 ++ crates/packie-store/src/query.rs | 1 + crates/packie-store/src/receipt.rs | 30 +- crates/packie-store/src/schema.rs | 25 +- crates/packie-transform/Cargo.toml | 2 + crates/packie-transform/src/datetime.rs | 134 +- crates/packie-transform/src/formula.rs | 9 +- crates/packie-transform/src/lib.rs | 22 +- crates/packie-transform/src/mapping.rs | 2 +- crates/packie-transform/src/model.rs | 33 +- crates/packie-transform/src/path.rs | 48 +- crates/packie-transform/src/pdf.rs | 141 + crates/packie-transform/src/steps.rs | 115 +- crates/packie-transform/src/value.rs | 127 + crates/packie-transform/tests/pdf_to_hl7.rs | 184 ++ crates/packie-transport/src/files.rs | 9 + crates/packie-transport/src/folder/mod.rs | 56 +- crates/packie-transport/src/sftp/source.rs | 47 +- crates/packie-transport/tests/folder.rs | 33 + crates/packie/Cargo.toml | 1 + crates/packie/src/main.rs | 29 +- crates/packie/src/messages.rs | 7 +- crates/packie/src/pdf.rs | 142 + crates/packie/tests/e2e.rs | 199 ++ docs/architecture.md | 7 +- docs/decisions.md | 1 + docs/operations/configuration-reference.md | 56 +- docs/operations/running-and-monitoring.md | 8 + docs/requirements.md | 3 +- docs/spec/acceptance.md | 11 +- docs/spec/audit.md | 1 + docs/spec/configuration.md | 88 +- docs/spec/diagnostics.md | 5 +- docs/spec/message-channels.md | 16 +- docs/spec/operator-console.md | 13 +- docs/spec/pdf-reports.md | 201 ++ docs/testing.md | 2 +- fuzz/Cargo.lock | 514 ++++ fuzz/Cargo.toml | 7 + fuzz/README.md | 1 + fuzz/corpus/pdf_read/report | Bin 0 -> 5245 bytes fuzz/corpus/pdf_read/report-compressed | Bin 0 -> 4569 bytes fuzz/corpus/pdf_read/report-encrypted | Bin 0 -> 3525 bytes fuzz/fuzz_targets/pdf_read.rs | 43 + fuzz/fuzz_targets/transform_path.rs | 3 +- fuzz/run.sh | 1 + 201 files changed, 13554 insertions(+), 373 deletions(-) create mode 100644 changelog.d/2026-11-19-hl7-files.md create mode 100644 changelog.d/2026-11-19-pdf-reports.md create mode 100644 changelog.d/2026-11-20-file-receipt-time.md create mode 100644 console/help/hl7-files.json create mode 100644 console/help/pdf-reports.json create mode 100644 console/src/api/mock/pdfReports.ts create mode 100644 console/src/features/config/PdfTestButton.tsx create mode 100644 console/src/features/config/channelForm.test.ts create mode 100644 console/src/features/pdfReports/PdfReportTest.module.css create mode 100644 console/src/features/pdfReports/PdfReportTest.test.tsx create mode 100644 console/src/features/pdfReports/PdfReportTest.tsx create mode 100644 console/src/ipc/generated/FieldPosition.ts create mode 100644 console/src/ipc/generated/Hl7FileSettings.ts create mode 100644 console/src/ipc/generated/OneOrMore.ts create mode 100644 console/src/ipc/generated/PdfField.ts create mode 100644 console/src/ipc/generated/PdfLine.ts create mode 100644 console/src/ipc/generated/PdfPage.ts create mode 100644 console/src/ipc/generated/PdfPhrase.ts create mode 100644 console/src/ipc/generated/PdfReportSettings.ts create mode 100644 console/src/ipc/generated/PdfReportTest.ts create mode 100644 console/src/ipc/generated/PdfReportTestResult.ts create mode 100644 console/src/ipc/generated/TestDestination.ts create mode 100644 console/src/lib/protocols.ts create mode 100644 crates/packie-config/src/protocol/pdf.rs create mode 100644 crates/packie-config/src/validate/pdf.rs create mode 100644 crates/packie-engine/src/pdf.rs create mode 100644 crates/packie-engine/src/pdf_test.rs create mode 100644 crates/packie-engine/src/pdf_view.rs create mode 100644 crates/packie-ipc/src/pdf.rs create mode 100644 crates/packie-pdf/Cargo.toml create mode 100644 crates/packie-pdf/src/error.rs create mode 100644 crates/packie-pdf/src/extract/font.rs create mode 100644 crates/packie-pdf/src/extract/interp.rs create mode 100644 crates/packie-pdf/src/extract/matrix.rs create mode 100644 crates/packie-pdf/src/extract/mod.rs create mode 100644 crates/packie-pdf/src/extract/standard14.rs create mode 100644 crates/packie-pdf/src/layout.rs create mode 100644 crates/packie-pdf/src/lib.rs create mode 100644 crates/packie-pdf/src/template.rs create mode 100644 crates/packie-pdf/tests/conformance.rs create mode 100644 crates/packie-pdf/tests/properties.rs create mode 100644 crates/packie-pdf/tests/standard14.rs create mode 100644 crates/packie-pdf/tests/support/mod.rs create mode 100644 crates/packie-routing/src/message/pdf.rs create mode 100644 crates/packie-routing/tests/message_hl7_file.rs create mode 100644 crates/packie-routing/tests/message_pdf.rs create mode 100644 crates/packie-transform/src/pdf.rs create mode 100644 crates/packie-transform/src/value.rs create mode 100644 crates/packie-transform/tests/pdf_to_hl7.rs create mode 100644 crates/packie/src/pdf.rs create mode 100644 docs/spec/pdf-reports.md create mode 100644 fuzz/corpus/pdf_read/report create mode 100644 fuzz/corpus/pdf_read/report-compressed create mode 100644 fuzz/corpus/pdf_read/report-encrypted create mode 100644 fuzz/fuzz_targets/pdf_read.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 28a20f6..eafc76f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,10 +6,31 @@ What changed in OpenBGA Interface Engine, grouped by release with unreleased changes on top, then by impact. Types follow [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). -## Unreleased (2026-11-12 to 2026-11-17) +## Unreleased (2026-11-12 to 2026-11-20) ### High impact +- **Added:** Read PDF reports and send them on as HL7 messages (2026-11-19) + + A message channel can now read laboratory reports published as PDF files from a folder or SFTP + server. A template names the labels printed on the report; their values fill the outgoing HL7 + message, and the report itself can travel inside it. Reports a filter leaves out and reports + that cannot be read can be moved to their own folders, set in the folder or SFTP endpoint editor + under **After a file is read**. **Test with a PDF** in the channel + editor shows what a template reads from a report and the message it would send, before you + apply anything. A stored report shows as the text read from it, and its fields as the + template reads them. A newborn screening template and mapping are included as presets. + + Technical notes: + + New source protocol `pdf_report` (text layer only, no OCR) with the template settings of + configuration §7.7 (a `below` field's `phrase` −1 is the last phrase of its line); mappings read `field.`, `report.pages` and `report.file_base64`. + Folder and SFTP endpoints gain `filtered_directory` and `invalid_directory`. New text step + `strip_suffix`; date formats accept the unpadded tokens `M`, `d` and `H`. Invalid PDF reports + record a `reason_detail`; the message store migrates to schema version 11 when it opens. The + test tool is the `test_pdf_report` management request and `packie pdf test`, audited as + `pdf_report_test`. New dependency: `lopdf` (MIT). + - **Changed:** The product is now called OpenBGA Interface Engine (2026-11-17, [#3](https://github.com/openbga/interface-engine/pull/3)) The engine and console carry the new name. Alert e-mail subjects, export files and installers use it @@ -138,6 +159,29 @@ top, then by impact. Types follow [Keep a Changelog](https://keepachangelog.com/ ### Medium impact +- **Fixed:** Files are received when the engine takes them (2026-11-20) + + A message read from a file (a delimited file or a PDF report) was recorded as received at the + file's last-modified time. An older file dropped into a folder today appeared days back on the + Messages page, and retention could remove it almost at once. Such messages are now received at + the moment the engine takes the file. Files are still read oldest first. + +- **Added:** Write HL7 messages as files to a folder or SFTP server (2026-11-19) + + A message channel can now deliver HL7 messages as files: each message becomes one file in a + folder or on an SFTP server, for receivers that collect HL7 files instead of accepting a + network connection. You choose the file name pattern and the header fields the messages + carry. Messages received over HL7 can be written unchanged; others are built by a mapping, + such as the newborn screening preset for PDF reports. + + Technical notes: + + New destination protocol `hl7_file` on `folder` and `sftp` endpoints (configuration §7.8): + `file_name`, `on_exists` (`suffix`, `overwrite`, `fail`), the HL7 header fields and + `max_message_bytes`. The highest acknowledgement level is `handed_off`. A destination without a + mapping may use `hl7_file` for an `hl7_mllp` source. The newborn screening mapping preset now + targets `hl7_file`. + - **Fixed:** Messages show the configuration version in effect after an in-place change (2026-11-17, [#5](https://github.com/openbga/interface-engine/pull/5)) After a channel change that applied without a restart, new messages and the channel's status kept diff --git a/Cargo.lock b/Cargo.lock index 2bed075..0cd5732 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aead" version = "0.6.1" @@ -48,6 +54,21 @@ dependencies = [ "memchr", ] +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "android_system_properties" version = "0.1.6" @@ -426,6 +447,16 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -637,6 +668,15 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossbeam-channel" version = "0.5.17" @@ -885,6 +925,15 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2db04e74f0a9a93103b50e90b96024c9b2bdca8bce6a632ec71b88736d3d359" +[[package]] +name = "ecb" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26f2a8b3e564eba0877223dc343703ad0385794e882e6d13f3a4dd5c6b1f41ac" +dependencies = [ + "cipher", +] + [[package]] name = "ecdsa" version = "0.17.0" @@ -970,6 +1019,20 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "endi" version = "1.1.1" @@ -1085,6 +1148,17 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "fnv" version = "1.0.7" @@ -1469,6 +1543,9 @@ dependencies = [ "icu_properties", "icu_provider", "smallvec", + "utf16_iter", + "utf8_iter", + "write16", "zerovec", ] @@ -1827,6 +1904,33 @@ version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +[[package]] +name = "lopdf" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6ad532ff9262dd4bfd6e085400cbb39959d48cb8d08518b01b68f77bdf6feca" +dependencies = [ + "aes", + "bitflags 2.13.2", + "brotli-decompressor", + "cbc", + "ecb", + "encoding_rs", + "flate2", + "getrandom 0.4.3", + "indexmap", + "itoa", + "log", + "md-5", + "nom", + "rand 0.10.3", + "rangemap", + "sha2 0.11.1", + "stringprep", + "thiserror", + "weezl", +] + [[package]] name = "mach2" version = "0.4.3" @@ -1845,6 +1949,16 @@ dependencies = [ "regex-automata", ] +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest 0.11.3", +] + [[package]] name = "md5" version = "0.8.1" @@ -1872,6 +1986,16 @@ version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.4" @@ -1910,6 +2034,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "nix" version = "0.26.4" @@ -2155,6 +2285,7 @@ dependencies = [ name = "packie" version = "0.2.0" dependencies = [ + "base64", "clap", "nix 0.31.3", "packie-audit", @@ -2284,6 +2415,7 @@ dependencies = [ name = "packie-engine" version = "0.2.0" dependencies = [ + "base64", "packie-astm", "packie-backup", "packie-config", @@ -2292,7 +2424,9 @@ dependencies = [ "packie-hl7", "packie-ipc", "packie-notify", + "packie-pdf", "packie-transform", + "rust_decimal", "serde_json", "tempfile", "thiserror", @@ -2366,6 +2500,16 @@ dependencies = [ "ureq", ] +[[package]] +name = "packie-pdf" +version = "0.2.0" +dependencies = [ + "icu_normalizer", + "lopdf", + "proptest", + "thiserror", +] + [[package]] name = "packie-routing" version = "0.2.0" @@ -2379,6 +2523,7 @@ dependencies = [ "packie-files", "packie-hl7", "packie-ipc", + "packie-pdf", "packie-store", "packie-transform", "packie-transport", @@ -2432,6 +2577,7 @@ dependencies = [ name = "packie-transform" version = "0.2.0" dependencies = [ + "base64", "insta", "jiff", "packie-astm", @@ -2858,6 +3004,12 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rangemap" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" + [[package]] name = "recvmsg" version = "1.0.0" @@ -3473,6 +3625,18 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "similar" version = "2.7.0" @@ -3590,6 +3754,17 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + [[package]] name = "strsim" version = "0.11.1" @@ -3732,6 +3907,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.54.1" @@ -3955,12 +4136,33 @@ dependencies = [ "thiserror", ] +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" + [[package]] name = "universal-hash" version = "0.6.1" @@ -4017,6 +4219,15 @@ dependencies = [ "serde", ] +[[package]] +name = "utf16_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c7de35d9d8757dbc1f5125dc8b51438c68b4430546a735c3a9b91aaaaf9a18a" +dependencies = [ + "utf_types", +] + [[package]] name = "utf8-zero" version = "0.8.1" @@ -4173,6 +4384,12 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "weezl" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2" + [[package]] name = "widestring" version = "1.2.1" @@ -4437,6 +4654,12 @@ dependencies = [ "primefield", ] +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + [[package]] name = "writeable" version = "0.6.4" @@ -4627,6 +4850,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 1bb92a3..faf629e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,8 @@ packie-routing = { path = "crates/packie-routing" } packie-notify = { path = "crates/packie-notify" } # External crates +# Base64 for embedded PDF reports and the PDF test tool. +base64 = "0.23" clap = { version = "4.6.7", features = ["derive"] } csv = "1.4.0" fs4 = { version = "1.1.0", default-features = false, features = ["sync"] } diff --git a/STATUS.md b/STATUS.md index 291c26d..fa69aa8 100644 --- a/STATUS.md +++ b/STATUS.md @@ -52,6 +52,20 @@ behavior. - Run the unverified platform checks in the table above. - Package the console for Linux. +### In progress + +- PDF reports to HL7 (`pdf_report` source, outcome directories; PRO-03, PRO-07), specified in + [pdf-reports.md](docs/spec/pdf-reports.md). Built: the reader (`packie-pdf`), the PDF model, + `strip_suffix` and unpadded date tokens in mappings, the configuration and its validation, + the source with outcome directories and `reason_detail`, the newborn screening template and + mapping presets, the template editor in the console, and the test tool (`test_pdf_report`, + `packie pdf test`, **Test with a PDF…**, **Test against the current template**), the + message views (extracted text, fields, export with bodies), and the `hl7_file` destination + (one HL7 message per file on a folder or SFTP endpoint). Not built: the simulator scenarios + of acceptance E-08 to E-14. The HL7 goes to a health information exchange, first in its + test environment; its connection details (SFTP folder or MLLP) are pending, as are the + access details of the folder the reports are published in and the panel coding. + ### Known limitations - Instrument presets are built from published interface documentation and synthetic tests; diff --git a/changelog.d/2026-11-19-hl7-files.md b/changelog.d/2026-11-19-hl7-files.md new file mode 100644 index 0000000..76cf1c0 --- /dev/null +++ b/changelog.d/2026-11-19-hl7-files.md @@ -0,0 +1,21 @@ +--- +date: 2026-11-19 +type: added +impact: medium +title: Write HL7 messages as files to a folder or SFTP server +area: Channels +link: /channels +--- +A message channel can now deliver HL7 messages as files: each message becomes one file in a +folder or on an SFTP server, for receivers that collect HL7 files instead of accepting a +network connection. You choose the file name pattern and the header fields the messages +carry. Messages received over HL7 can be written unchanged; others are built by a mapping, +such as the newborn screening preset for PDF reports. + +## Technical notes + +New destination protocol `hl7_file` on `folder` and `sftp` endpoints (configuration §7.8): +`file_name`, `on_exists` (`suffix`, `overwrite`, `fail`), the HL7 header fields and +`max_message_bytes`. The highest acknowledgement level is `handed_off`. A destination without a +mapping may use `hl7_file` for an `hl7_mllp` source. The newborn screening mapping preset now +targets `hl7_file`. diff --git a/changelog.d/2026-11-19-pdf-reports.md b/changelog.d/2026-11-19-pdf-reports.md new file mode 100644 index 0000000..18c482a --- /dev/null +++ b/changelog.d/2026-11-19-pdf-reports.md @@ -0,0 +1,26 @@ +--- +date: 2026-11-19 +type: added +impact: high +title: Read PDF reports and send them on as HL7 messages +area: Channels +link: /channels +--- +A message channel can now read laboratory reports published as PDF files from a folder or SFTP +server. A template names the labels printed on the report; their values fill the outgoing HL7 +message, and the report itself can travel inside it. Reports a filter leaves out and reports +that cannot be read can be moved to their own folders, set in the folder or SFTP endpoint editor +under **After a file is read**. **Test with a PDF** in the channel +editor shows what a template reads from a report and the message it would send, before you +apply anything. A stored report shows as the text read from it, and its fields as the +template reads them. A newborn screening template and mapping are included as presets. + +## Technical notes + +New source protocol `pdf_report` (text layer only, no OCR) with the template settings of +configuration §7.7 (a `below` field's `phrase` −1 is the last phrase of its line); mappings read `field.`, `report.pages` and `report.file_base64`. +Folder and SFTP endpoints gain `filtered_directory` and `invalid_directory`. New text step +`strip_suffix`; date formats accept the unpadded tokens `M`, `d` and `H`. Invalid PDF reports +record a `reason_detail`; the message store migrates to schema version 11 when it opens. The +test tool is the `test_pdf_report` management request and `packie pdf test`, audited as +`pdf_report_test`. New dependency: `lopdf` (MIT). diff --git a/changelog.d/2026-11-20-file-receipt-time.md b/changelog.d/2026-11-20-file-receipt-time.md new file mode 100644 index 0000000..bd92076 --- /dev/null +++ b/changelog.d/2026-11-20-file-receipt-time.md @@ -0,0 +1,12 @@ +--- +date: 2026-11-20 +type: fixed +impact: medium +title: Files are received when the engine takes them +area: Messages +link: /messages +--- +A message read from a file (a delimited file or a PDF report) was recorded as received at the +file's last-modified time. An older file dropped into a folder today appeared days back on the +Messages page, and retention could remove it almost at once. Such messages are now received at +the moment the engine takes the file. Files are still read oldest first. diff --git a/console/help/hl7-files.json b/console/help/hl7-files.json new file mode 100644 index 0000000..cac546f --- /dev/null +++ b/console/help/hl7-files.json @@ -0,0 +1,15 @@ +{ + "id": "hl7-files", + "title": "HL7 files", + "summary": "Writing each HL7 message as a file to a folder or SFTP server.", + "routes": [], + "sections": [ + { + "title": "The destination", + "paragraphs": [ + "An HL7 v2 files destination writes each message as one file to a folder or SFTP server, for receivers that collect files instead of listening for a connection. Its settings (a JSON object) give the file_name, which may use {sample_id}, {control_id}, {message_id}, {date}, {time} and {seq}, and the header fields MSH-3 to MSH-6 of the messages it builds.", + "Writing the file is all the engine can confirm: the delivery is complete when the file is in place. A message larger than max_message_bytes is not written and the delivery fails. Without a mapping, messages from an HL7 source are written as they arrived." + ] + } + ] +} diff --git a/console/help/pdf-reports.json b/console/help/pdf-reports.json new file mode 100644 index 0000000..269257b --- /dev/null +++ b/console/help/pdf-reports.json @@ -0,0 +1,23 @@ +{ + "id": "pdf-reports", + "title": "PDF reports", + "summary": "Reading report files with a template and embedding them in the message sent on.", + "routes": [], + "sections": [ + { + "title": "The template", + "paragraphs": [ + "A PDF report source reads report files, one message per file. Its template (a JSON object) lists the fields to read: the label printed on the report and whether the value is right of it or below. Start from the newborn screening preset.", + "A value the report does not print is empty. A report whose labels do not match is stored invalid with the reason and nothing is sent; correct the template and resend it as a new message.", + "Test with a PDF, under the template, reads a report you choose and shows the fields and the message a destination would get; nothing is stored or sent. On an invalid report, Test against the current template reads it again.", + "In the message detail, a stored report's Text view is the text read from it, page by page, with between phrases; Hex shows the file. Fields lists the values the channel's template reads." + ] + }, + { + "title": "Folders and embedding", + "paragraphs": [ + "On the folder or SFTP endpoint, under After a file is read, a filtered and an unreadable reports folder keep left-out and unreadable reports apart. A mapping embeds the report with report.file_base64; an HL7 v2 files destination writes each message as a file for the receiver to collect." + ] + } + ] +} diff --git a/console/src-tauri/Cargo.lock b/console/src-tauri/Cargo.lock index b78600a..de93510 100644 --- a/console/src-tauri/Cargo.lock +++ b/console/src-tauri/Cargo.lock @@ -2795,6 +2795,7 @@ dependencies = [ name = "packie-transform" version = "0.2.0" dependencies = [ + "base64 0.23.1", "jiff", "packie-astm", "packie-au", diff --git a/console/src/api/engine.ts b/console/src/api/engine.ts index 1ca0652..50d810d 100644 --- a/console/src/api/engine.ts +++ b/console/src/api/engine.ts @@ -32,6 +32,8 @@ import type { MessagePage, MessageQuery, NotificationResult, + PdfReportTestRequest, + PdfReportTestResult, ProbeReport, ReportFile, ResendRequest, @@ -90,6 +92,12 @@ export interface EngineApi { testEndpoint(request: EndpointTestRequest): Promise; /** Sends one test message to every notification target the engine has; empty when none is configured. Audited. */ testNotification(): Promise; + /** + * Reads a PDF report with a template that need not be saved, and maps it for a destination + * when one is given; stores and sends nothing. A template or destination the engine's rules + * reject rejects with `validation`. Audited by the engine. + */ + testPdfReport(request: PdfReportTestRequest): Promise; // Commands pauseChannel(id: string): Promise; diff --git a/console/src/api/ipc/IpcEngineApi.ts b/console/src/api/ipc/IpcEngineApi.ts index f501faa..36d78f0 100644 --- a/console/src/api/ipc/IpcEngineApi.ts +++ b/console/src/api/ipc/IpcEngineApi.ts @@ -34,6 +34,8 @@ import type { MessagePage, MessageQuery, NotificationResult, + PdfReportTestRequest, + PdfReportTestResult, ProbeReport, ReportFile, ResendRequest, @@ -62,6 +64,8 @@ import { connectionStatusFrom } from "./settings"; import { atEndpointZero, notificationResultFromIpc, + pdfResultFromIpc, + pdfTestToIpc, probeFromIpc, serialPortFromIpc, } from "./setup"; @@ -225,6 +229,15 @@ export class IpcEngineApi implements EngineApi { return results.map(notificationResultFromIpc); } + /** + * Reads a PDF report with the editor's template. The engine names problems relative to the + * source connector (`settings.fields[0].label`) or under `destination.`. + */ + async testPdfReport(request: PdfReportTestRequest): Promise { + const result = await this.client.request(pdfTestToIpc(request), "pdf_report_tested"); + return pdfResultFromIpc(result); + } + // Commands private async command(channelId: string, command: "pause" | "resume" | "restart") { diff --git a/console/src/api/ipc/channelConfig.ts b/console/src/api/ipc/channelConfig.ts index e8fc3f6..c00526e 100644 --- a/console/src/api/ipc/channelConfig.ts +++ b/console/src/api/ipc/channelConfig.ts @@ -225,6 +225,11 @@ function destinationToWire( return next; } +/** A destination on its own, as a new one is written (the PDF report test maps for it). */ +export function destinationAlone(ui: DestinationConfig, issues: Issues): WireDestination { + return destinationToWire(ui, undefined, undefined, "destination", issues); +} + // ── Message channels ─────────────────────────────────────────────────────────────────── function sourceFromWire(raw: WireSource): SourceConfig { diff --git a/console/src/api/ipc/configNew.test.ts b/console/src/api/ipc/configNew.test.ts index 6b836d5..e3dbdc3 100644 --- a/console/src/api/ipc/configNew.test.ts +++ b/console/src/api/ipc/configNew.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import type { ConfigDocument } from "../types"; import { documentToWire } from "./configDocument"; +import { DEFAULT_CONSUMPTION } from "./endpointConfig"; import { AU, base, destination, message, sftp, withNew } from "./test/newItems"; import { documentProblems } from "./test/specSchema"; @@ -48,6 +49,7 @@ describe("new endpoints are written sparse", () => { mode: "watch", pollIntervalSec: 5, filePattern: "*", + ...DEFAULT_CONSUMPTION, }, ], [], @@ -113,6 +115,7 @@ describe("new endpoints are written sparse", () => { mode: "poll", pollIntervalSec: 30, filePattern: "*.csv", + ...DEFAULT_CONSUMPTION, }, ], [], @@ -241,6 +244,7 @@ describe("everything written has the shape the engine accepts", () => { mode: "poll", pollIntervalSec: 2, filePattern: "*.csv", + ...DEFAULT_CONSUMPTION, }, { ...sftp, id: "n5" }, { ...sftp, id: "n6", authMethod: "private_key", passphraseSecretName: "p" }, diff --git a/console/src/api/ipc/configNewChannels.test.ts b/console/src/api/ipc/configNewChannels.test.ts index d331009..f3d205c 100644 --- a/console/src/api/ipc/configNewChannels.test.ts +++ b/console/src/api/ipc/configNewChannels.test.ts @@ -254,7 +254,7 @@ describe("new channels are written sparse", () => { { severity: "error", path: "channels[3].source.settings.templateJson", - message: "A column template is required.", + message: "A template is required.", }, ]); }); diff --git a/console/src/api/ipc/connectorConfig.ts b/console/src/api/ipc/connectorConfig.ts index 878b024..b385307 100644 --- a/console/src/api/ipc/connectorConfig.ts +++ b/console/src/api/ipc/connectorConfig.ts @@ -1,8 +1,9 @@ /** * Protocol settings of connectors (docs/spec/configuration.md section 7), both ways. The * console models the HL7 acknowledgement mode, the ASTM link role, the AU instrument sheet and, - * for delimited files, the whole settings object as JSON text (`templateJson`). Everything else - * a protocol has (timeouts, identities, charsets) stays as it was. + * for delimited files, PDF reports and HL7 files, the whole settings object as JSON text + * (`templateJson`). Everything else a protocol has (timeouts, identities, charsets) stays as it + * was. */ import type { AstmSettings, Hl7Settings } from "@/ipc/generated"; @@ -102,6 +103,8 @@ export function settingsFromWire( return au === undefined ? {} : { au }; } case "delimited_file": + case "pdf_report": + case "hl7_file": return { templateJson: JSON.stringify(settings ?? {}, null, 2) }; case "raw": return {}; @@ -117,7 +120,7 @@ function templateFrom( const text = ui.templateJson ?? ""; let message = ""; let parsed: unknown = null; - if (text.trim() === "") message = "A column template is required."; + if (text.trim() === "") message = "A template is required."; else { try { parsed = JSON.parse(text); @@ -158,6 +161,8 @@ function newSettings( if (ui.au !== undefined) auToWire(settings, ui.au, undefined); break; case "delimited_file": + case "pdf_report": + case "hl7_file": return templateFrom(ui, path, issues) ?? {}; case "raw": break; @@ -197,6 +202,8 @@ export function settingsToWire( if (settings.au !== undefined) auToWire(next, settings.au, base.au); break; case "delimited_file": + case "pdf_report": + case "hl7_file": if (settings.templateJson !== base.templateJson) { return templateFrom(settings, path, issues) ?? next; } diff --git a/console/src/api/ipc/endpointConfig.test.ts b/console/src/api/ipc/endpointConfig.test.ts index f1be804..a67cb1e 100644 --- a/console/src/api/ipc/endpointConfig.test.ts +++ b/console/src/api/ipc/endpointConfig.test.ts @@ -34,3 +34,33 @@ describe("SFTP file name pattern", () => { expect(written.settings).toEqual({ ...raw.settings, file_pattern: "*.csv" }); }); }); + +describe("what happens to a file once it is read", () => { + it("reads the engine's defaults: move to processed, no outcome folders", () => { + expect(endpointFromWire(sparseSftp())).toMatchObject({ + onConsumed: "move", + processedDirectory: "processed", + filteredDirectory: "", + invalidDirectory: "", + }); + }); + + it("writes outcome folders, and an emptied one as null", () => { + const raw = sparseSftp(); + Object.assign(raw.settings, { filtered_directory: "skipped", invalid_directory: "errors" }); + const ui = endpointFromWire(raw); + if (ui.kind !== "sftp") throw new Error("expected an SFTP endpoint"); + const written = endpointToWire({ ...ui, filteredDirectory: "" }, raw); + expect(written.settings).toMatchObject({ + filtered_directory: null, + invalid_directory: "errors", + }); + }); + + it("leaves the defaults out of a new endpoint", () => { + const ui = endpointFromWire(sparseSftp()); + const written = endpointToWire({ ...ui, id: "new" }, undefined); + expect(written.settings).not.toHaveProperty("on_consumed"); + expect(written.settings).not.toHaveProperty("filtered_directory"); + }); +}); diff --git a/console/src/api/ipc/endpointConfig.ts b/console/src/api/ipc/endpointConfig.ts index 57236a5..c7a74e7 100644 --- a/console/src/api/ipc/endpointConfig.ts +++ b/console/src/api/ipc/endpointConfig.ts @@ -5,7 +5,7 @@ * Reading fills the specification's defaults, so a sparse document reads like a complete one. * Writing starts from the original object and overwrites only the fields whose console value * differs from what reading the original gave; everything the console does not model - * (timeouts, keep-alive tuning, virtual links, `tags`, directories, ...) survives. A new + * (timeouts, keep-alive tuning, virtual links, `tags`, write modes, ...) survives. A new * endpoint is written sparse: required fields, and modeled fields that differ from the default. */ @@ -13,6 +13,7 @@ import type { SecretRef } from "@/ipc/generated"; import { clone } from "@/lib/clone"; import type { EndpointConfig, + FileConsumption, FolderEndpointConfig, SerialEndpointConfig, SftpEndpointConfig, @@ -72,6 +73,17 @@ const tcpListenerFrom = (base: Base, t: WireTcpListenerSettings): TcpListenerEnd keepalive: t.keep_alive ?? true, }); +/** The consumption settings both file kinds share, defaults filled in. */ +const consumptionFrom = (t: WireConsumption): FileConsumption => ({ + onConsumed: t.on_consumed ?? "move", + processedDirectory: t.processed_directory ?? "processed", + filteredDirectory: t.filtered_directory ?? "", + invalidDirectory: t.invalid_directory ?? "", +}); + +/** What a file endpoint does when its document says nothing: move files to `processed`. */ +export const DEFAULT_CONSUMPTION: FileConsumption = consumptionFrom({}); + const folderFrom = (base: Base, t: WireFolderSettings): FolderEndpointConfig => ({ ...base, kind: "folder", @@ -79,6 +91,7 @@ const folderFrom = (base: Base, t: WireFolderSettings): FolderEndpointConfig => mode: t.mode ?? "watch", pollIntervalSec: t.poll_interval_seconds ?? 30, filePattern: t.file_pattern ?? "*", + ...consumptionFrom(t), }); const sftpFrom = (base: Base, t: WireSftpSettings): SftpEndpointConfig => ({ @@ -94,6 +107,7 @@ const sftpFrom = (base: Base, t: WireSftpSettings): SftpEndpointConfig => ({ remotePath: t.remote_directory, pollIntervalSec: t.poll_interval_seconds ?? 60, filePattern: t.file_pattern ?? "*", + ...consumptionFrom(t), }); export function endpointFromWire(raw: WireEndpoint): EndpointConfig { @@ -174,6 +188,29 @@ const TCP_LISTENER: Patch = }, }; +/** An optional folder: empty is written as null (the processed folder). */ +const orNull = (directory: string) => (directory === "" ? null : directory); + +type WireConsumption = Pick< + WireFolderSettings, + "on_consumed" | "processed_directory" | "filtered_directory" | "invalid_directory" +>; + +const CONSUMPTION: Patch = { + onConsumed: (r, u) => { + r.on_consumed = u.onConsumed; + }, + processedDirectory: (r, u) => { + r.processed_directory = u.processedDirectory; + }, + filteredDirectory: (r, u) => { + r.filtered_directory = orNull(u.filteredDirectory); + }, + invalidDirectory: (r, u) => { + r.invalid_directory = orNull(u.invalidDirectory); + }, +}; + const FOLDER: Patch = { path: (r, u) => { r.path = u.path; @@ -187,6 +224,7 @@ const FOLDER: Patch = { filePattern: (r, u) => { r.file_pattern = u.filePattern; }, + ...CONSUMPTION, }; function setAuth(r: WireSftpSettings, u: SftpEndpointConfig): void { @@ -227,6 +265,14 @@ const SFTP: Patch = { filePattern: (r, u) => { r.file_pattern = u.filePattern; }, + ...CONSUMPTION, +}; + +const CONSUMED_DEFAULTS = { + on_consumed: "move", + processed_directory: "processed", + filtered_directory: null, + invalid_directory: null, }; /** What a new endpoint leaves out because the engine assumes it. */ @@ -239,8 +285,8 @@ const DEFAULTS: Record> = { idle_timeout_seconds: 0, keep_alive: true, }, - folder: { mode: "watch", poll_interval_seconds: 30, file_pattern: "*" }, - sftp: { port: 22, poll_interval_seconds: 60, file_pattern: "*" }, + folder: { mode: "watch", poll_interval_seconds: 30, file_pattern: "*", ...CONSUMED_DEFAULTS }, + sftp: { port: 22, poll_interval_seconds: 60, file_pattern: "*", ...CONSUMED_DEFAULTS }, }; function patchSettings( diff --git a/console/src/api/ipc/messageDetail.test.ts b/console/src/api/ipc/messageDetail.test.ts index 70a08f6..eacfe53 100644 --- a/console/src/api/ipc/messageDetail.test.ts +++ b/console/src/api/ipc/messageDetail.test.ts @@ -27,12 +27,12 @@ describe("a message through the engine", () => { type: "message_fields", fields: [], truncated: false, - unavailable: "Fields are listed for HL7 and ASTM messages.", + unavailable: "Fields are listed for HL7, ASTM and PDF report messages.", })); expect(await api.getMessageFields("msg-1")).toEqual({ fields: [], truncated: false, - unavailable: "Fields are listed for HL7 and ASTM messages.", + unavailable: "Fields are listed for HL7, ASTM and PDF report messages.", }); }); diff --git a/console/src/api/ipc/messageMap.ts b/console/src/api/ipc/messageMap.ts index 883ec4e..ac453c5 100644 --- a/console/src/api/ipc/messageMap.ts +++ b/console/src/api/ipc/messageMap.ts @@ -176,6 +176,7 @@ export function detailFromIpc(raw: RawRecord, endpointLabel: string | undefined) respondedAt: raw.responded_at, abortReason: raw.abort_reason, reasonCode: raw.reason_code, + reasonDetail: raw.reason_detail, duplicateOf: raw.duplicate_of, revisionOf: raw.revision_of, revisedBy: raw.revised_by, diff --git a/console/src/api/ipc/paths.test.ts b/console/src/api/ipc/paths.test.ts index efc83ed..78518bf 100644 --- a/console/src/api/ipc/paths.test.ts +++ b/console/src/api/ipc/paths.test.ts @@ -48,10 +48,13 @@ const TABLE: Row[] = [ ["endpoints[6].settings.auth.passphrase", "endpoints[6].passphraseSecretName"], ["endpoints[6].settings.host_key_fingerprint", "endpoints[6].hostKeyFingerprint"], ["endpoints[6].settings.remote_directory", "endpoints[6].remotePath"], + // what a file source does after reading + ["endpoints[5].settings.processed_directory", "endpoints[5].processedDirectory"], + ["endpoints[5].settings.invalid_directory", "endpoints[5].invalidDirectory"], // endpoint settings the console does not model stay as the engine names them ["endpoints[1].settings.read_timeout_ms", "endpoints[1].settings.read_timeout_ms"], ["endpoints[4].settings.accept_backlog", "endpoints[4].settings.accept_backlog"], - ["endpoints[5].settings.processed_directory", "endpoints[5].settings.processed_directory"], + ["endpoints[5].settings.write_mode", "endpoints[5].settings.write_mode"], ["endpoints[6].settings.operation_timeout_ms", "endpoints[6].settings.operation_timeout_ms"], ["endpoints[1].settings.virtual_link", "endpoints[1].settings.virtual_link"], ["endpoints[1].tags", "endpoints[1].tags"], @@ -279,6 +282,7 @@ describe("toUiPath with the document the engine checked", () => { mapping: { rules: [{ op: "explode", to: "A" }] }, }, { destination_id: "d2", label: "D2", endpoint: "b", protocol: "astm" }, + { destination_id: "d3", label: "D3", endpoint: "b", protocol: "hl7_file" }, ], }, { @@ -329,6 +333,12 @@ describe("toUiPath with the document the engine checked", () => { expect(toUiPath("channels[0].destinations[0].settings.charset", document)).toBe( "channels[0].destinations[0].settings.charset", ); + // An HL7 file destination's settings, header fields included, are one JSON text. + for (const key of ["version", "file_name", "sending_facility"]) { + expect(toUiPath(`channels[0].destinations[3].settings.${key}`, document)).toBe( + "channels[0].destinations[3].settings.templateJson", + ); + } }); it("translates bridge fields", () => { diff --git a/console/src/api/ipc/paths.ts b/console/src/api/ipc/paths.ts index 4241eac..3c0e517 100644 --- a/console/src/api/ipc/paths.ts +++ b/console/src/api/ipc/paths.ts @@ -51,6 +51,10 @@ const ENDPOINT_FIELDS: Record = { "auth.passphrase.secret": "passphraseSecretName", host_key_fingerprint: "hostKeyFingerprint", remote_directory: "remotePath", + on_consumed: "onConsumed", + processed_directory: "processedDirectory", + filtered_directory: "filteredDirectory", + invalid_directory: "invalidDirectory", }; /** Fields whose console value is a list, so an index in the engine path stays. */ @@ -323,16 +327,18 @@ const VARIANT_KEYS: Record = { sample_id_path: "sampleIdPath", }; +/** Protocols whose settings the console edits as one JSON text (`templateJson`). */ +const JSON_SETTINGS = new Set(["delimited_file", "pdf_report", "hl7_file"]); + function settingsKey(key: string, protocol: string | undefined): Translated { + if (protocol !== undefined && JSON_SETTINGS.has(protocol)) return "templateJson"; const plain = withoutIndexes(key); const known = VARIANT_KEYS[plain]; - if (known !== undefined && protocol !== "au" && protocol !== "delimited_file") return known; + if (known !== undefined && protocol !== "au") return known; if (plain === "ack_mode") return "ackMode"; if (plain === "role") return "astmRole"; const first = plain.split(".")[0] ?? ""; - if (DELIMITED_KEYS.has(first) || (protocol === "delimited_file" && first === "charset")) { - return "templateJson"; - } + if (DELIMITED_KEYS.has(first)) return "templateJson"; if (protocol === "hl7_mllp" || protocol === "astm") return null; const au = AU_FIELDS[plain]; if (au === undefined) return null; diff --git a/console/src/api/ipc/setup.ts b/console/src/api/ipc/setup.ts index 1aca92e..4ed1d3a 100644 --- a/console/src/api/ipc/setup.ts +++ b/console/src/api/ipc/setup.ts @@ -1,19 +1,28 @@ -// Setup checks (`list_serial_ports`, `test_endpoint`, `test_notification`): the engine's -// reports as the console's, and a console endpoint as the engine's `EndpointTest`. Pure. +// Setup checks (`list_serial_ports`, `test_endpoint`, `test_notification`, `test_pdf_report`): +// the engine's reports as the console's, and a console endpoint as the engine's `EndpointTest`. +// Pure. import type { + PdfReportTestResult as PdfReportTestResultIpc, NotificationResult as RawNotification, SerialPort as RawPort, ProbeReport as RawProbe, + Request, } from "@/ipc/generated"; import type { EngineError, NotificationResult, NotificationSettings, + PdfReportTestRequest, + PdfReportTestResult, ProbeReport, SerialPortInfo, } from "../types"; +import { destinationAlone } from "./channelConfig"; +import { issueList } from "./connectorConfig"; +import { engineError } from "./errors"; import { toUiPath } from "./paths"; +import { isRecord } from "./util"; import type { WireConfig } from "./wire"; export function serialPortFromIpc(raw: RawPort): SerialPortInfo { @@ -116,3 +125,58 @@ export function atEndpointZero(error: unknown, document: WireConfig): unknown { })), }; } + +/** + * The engine's request for a PDF report test: the template parsed from the editor's JSON, the + * destination in the document's form. Problems converting them are raised as `validation` at + * `templateJson` and `destination.`. + */ +export function pdfTestToIpc( + request: PdfReportTestRequest, +): Extract { + const issues = issueList(); + let settings: unknown = null; + try { + settings = JSON.parse(request.templateJson); + } catch { + issues.add("templateJson", "The template is not valid JSON."); + } + if (issues.list.length === 0 && !isRecord(settings)) { + issues.add("templateJson", "The template must be a JSON object."); + } + const destination = + request.destination === undefined ? null : destinationAlone(request.destination, issues); + if (issues.list.length > 0 || !isRecord(settings)) { + throw engineError( + "validation", + "The template or the destination cannot be tested as they are.", + issues.list.map(({ path, message }) => ({ field: path, message })), + ); + } + return { + type: "test_pdf_report", + settings, + file: request.file ?? null, + message_id: request.messageId ?? null, + destination: + destination === null + ? null + : { + protocol: destination.protocol, + settings: (destination.settings ?? {}) as Record, + mapping: (destination.mapping ?? null) as Record | null, + }, + }; +} + +export function pdfResultFromIpc(result: PdfReportTestResultIpc): PdfReportTestResult { + return { + ok: result.ok, + reasonCode: result.reason_code, + reasonDetail: result.reason_detail, + pages: result.pages, + fields: result.fields, + output: result.output, + outputError: result.output_error, + }; +} diff --git a/console/src/api/ipc/steps.ts b/console/src/api/ipc/steps.ts index a710034..11307e6 100644 --- a/console/src/api/ipc/steps.ts +++ b/console/src/api/ipc/steps.ts @@ -34,12 +34,27 @@ function sliceFromJson(json: Json): Step | null { : null; } +function replaceFromJson(json: Json): Step | null { + const { find, with: replacement } = json; + return hasOnly(json, ["step", "find", "with"]) && + typeof find === "string" && + typeof replacement === "string" + ? { step: "replace", find, with: replacement } + : null; +} + +function stripSuffixFromJson(json: Json): Step | null { + return hasOnly(json, ["step", "from"]) && typeof json.from === "string" + ? { step: "strip_suffix", from: json.from } + : null; +} + function stepFromJson(json: unknown): Step | null { if (!isRecord(json) || typeof json.step !== "string") return null; if (SIMPLE_STEPS.has(json.step)) { return hasOnly(json, ["step"]) ? ({ step: json.step } as Step) : null; } - const { chars, separator, take, find, with: replacement } = json; + const { chars, separator, take } = json; switch (json.step) { case "strip_leading": return hasOnly(json, ["step", "chars"]) && typeof chars === "string" @@ -54,11 +69,9 @@ function stepFromJson(json: unknown): Step | null { case "slice": return sliceFromJson(json); case "replace": - return hasOnly(json, ["step", "find", "with"]) && - typeof find === "string" && - typeof replacement === "string" - ? { step: "replace", find, with: replacement } - : null; + return replaceFromJson(json); + case "strip_suffix": + return stripSuffixFromJson(json); default: return null; } diff --git a/console/src/api/ipc/test/messageRecords.ts b/console/src/api/ipc/test/messageRecords.ts index 09d0b9b..0822bd2 100644 --- a/console/src/api/ipc/test/messageRecords.ts +++ b/console/src/api/ipc/test/messageRecords.ts @@ -97,6 +97,7 @@ export function record(extra: Partial = {}): MessageRecord { responded_at: "2026-11-06T12:00:00Z", abort_reason: null, reason_code: null, + reason_detail: null, duplicate_of: null, revision_of: null, revised_by: null, diff --git a/console/src/api/ipc/test/newItems.ts b/console/src/api/ipc/test/newItems.ts index 4ac036c..0a0fdca 100644 --- a/console/src/api/ipc/test/newItems.ts +++ b/console/src/api/ipc/test/newItems.ts @@ -1,3 +1,4 @@ +import { DEFAULT_CONSUMPTION } from "@/api/ipc/endpointConfig"; /** Builders for the items the `configNew` tests add to the rich document. */ import type { @@ -94,4 +95,5 @@ export const sftp = { remotePath: "/in", pollIntervalSec: 60, filePattern: "*", + ...DEFAULT_CONSUMPTION, } satisfies EndpointConfig; diff --git a/console/src/api/ipc/test/specStructs.ts b/console/src/api/ipc/test/specStructs.ts index 980a9cf..ebde5cb 100644 --- a/console/src/api/ipc/test/specStructs.ts +++ b/console/src/api/ipc/test/specStructs.ts @@ -333,6 +333,7 @@ export const STRUCTS: Record = { required: ["step", "start"], }, step_replace: allRequired(["step", "find", "with"]), + step_strip_suffix: allRequired(["step", "from"]), // Calculation operands (section 8.2, Calculations). formula_from: { known: ["from", "steps"], required: ["from"] }, formula_find: { diff --git a/console/src/api/mock/MockEngineApi.config.test.ts b/console/src/api/mock/MockEngineApi.config.test.ts index fc4645c..5c804b1 100644 --- a/console/src/api/mock/MockEngineApi.config.test.ts +++ b/console/src/api/mock/MockEngineApi.config.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from "vitest"; import { documentToWire } from "@/api/ipc/configDocument"; +import { DEFAULT_CONSUMPTION } from "../ipc/endpointConfig"; import { at, mockApiFactory, rejection } from "./mockTestSupport"; const create = mockApiFactory({ messageCount: 500, seed: 7 }); @@ -235,6 +236,7 @@ describe("applyConfig", () => { mode: "watch", pollIntervalSec: 5, filePattern: "*.csv", + ...DEFAULT_CONSUMPTION, }); doc.channels = doc.channels.filter((c) => c.id !== "ch-br-d100"); const result = await api.applyConfig(doc, "move the LIS port"); diff --git a/console/src/api/mock/MockEngineApi.message-fields.test.ts b/console/src/api/mock/MockEngineApi.message-fields.test.ts index f96f9c0..3f17c99 100644 --- a/console/src/api/mock/MockEngineApi.message-fields.test.ts +++ b/console/src/api/mock/MockEngineApi.message-fields.test.ts @@ -55,7 +55,7 @@ describe("parsed fields", () => { expect(await fieldsOf(api, row?.id ?? "")).toEqual({ fields: [], truncated: false, - unavailable: "Fields are listed for HL7 and ASTM messages.", + unavailable: "Fields are listed for HL7, ASTM and PDF report messages.", }); } const invalid = rows.find((r) => r.state === "invalid" && r.protocol === "hl7_mllp"); diff --git a/console/src/api/mock/channelCatalog.ts b/console/src/api/mock/channelCatalog.ts index 8e2c39e..bfe6b44 100644 --- a/console/src/api/mock/channelCatalog.ts +++ b/console/src/api/mock/channelCatalog.ts @@ -36,9 +36,11 @@ interface MessageDef { const RESULT_TYPE: Record = { hl7_mllp: "ORU^R01", + hl7_file: "ORU^R01", astm: "ASTM result", au: "AU result", delimited_file: "CSV row", + pdf_report: "PDF report", raw: "Raw frame", }; diff --git a/console/src/api/mock/deliveryAttempts.ts b/console/src/api/mock/deliveryAttempts.ts index 44325ec..05622df 100644 --- a/console/src/api/mock/deliveryAttempts.ts +++ b/console/src/api/mock/deliveryAttempts.ts @@ -12,6 +12,7 @@ import { iso } from "./util"; export function topAckLevel(destination: DestinationInfo): AckLevel { switch (destination.protocol) { case "delimited_file": + case "hl7_file": return "handed_off"; case "astm": return "received"; @@ -27,7 +28,9 @@ export function topAckLevel(destination: DestinationInfo): AckLevel { /** The acknowledgement code a destination answers with when it accepts, if its protocol has one. */ function acceptCode(destination: DestinationInfo): string | null { if (destination.protocol === "hl7_mllp") return destination.ackMode === "none" ? null : "AA"; - return destination.protocol === "delimited_file" ? null : "ACK"; + return destination.protocol === "delimited_file" || destination.protocol === "hl7_file" + ? null + : "ACK"; } export type Outcome = "failed" | "rejected" | "timed_out" | "outcome_unknown"; diff --git a/console/src/api/mock/endpointCatalog.ts b/console/src/api/mock/endpointCatalog.ts index 831a65b..294a931 100644 --- a/console/src/api/mock/endpointCatalog.ts +++ b/console/src/api/mock/endpointCatalog.ts @@ -1,3 +1,4 @@ +import { DEFAULT_CONSUMPTION } from "../ipc/endpointConfig"; import type { EndpointConfig, FolderEndpointConfig, @@ -81,6 +82,7 @@ function folder(id: string, label: string, path: string, filePattern: string) { mode: "watch", pollIntervalSec: 5, filePattern, + ...DEFAULT_CONSUMPTION, }; return config; } @@ -108,6 +110,7 @@ function sftp( remotePath, pollIntervalSec: 60, filePattern: "*", + ...DEFAULT_CONSUMPTION, }; return config; } diff --git a/console/src/api/mock/index.ts b/console/src/api/mock/index.ts index c965d39..ce73e60 100644 --- a/console/src/api/mock/index.ts +++ b/console/src/api/mock/index.ts @@ -33,6 +33,8 @@ import type { MessagePage, MessageQuery, NotificationResult, + PdfReportTestRequest, + PdfReportTestResult, ProbeReport, ReportFile, ResendRequest, @@ -50,6 +52,7 @@ import * as audited from "./audited"; import { downloadText } from "./download"; import { MockHost } from "./mockHost"; import { sendTestNotifications } from "./notifications"; +import { testPdfReport } from "./pdfReports"; import { probeEndpoint } from "./probe"; import { serialPortsOf } from "./serialPorts"; import { engineInfo, engineSettings } from "./settings"; @@ -159,6 +162,10 @@ export class MockEngineApi extends MockHost implements EngineApi { return this.request(() => sendTestNotifications(this.world)); } + testPdfReport(request: PdfReportTestRequest): Promise { + return this.request(() => testPdfReport(this.world, request)); + } + pauseChannel(id: string): Promise { return this.request(() => audited.channelCommand(this.world, "pause", id)); } diff --git a/console/src/api/mock/mappingCatalog.ts b/console/src/api/mock/mappingCatalog.ts index 799f85a..bcec538 100644 --- a/console/src/api/mock/mappingCatalog.ts +++ b/console/src/api/mock/mappingCatalog.ts @@ -308,6 +308,18 @@ export function connectorSettings( }; case "delimited_file": return { templateJson: delimitedTemplate(role) }; + case "hl7_file": + return { + templateJson: JSON.stringify({ file_name: "ORU_{sample_id}_{seq}.hl7" }, null, 2), + }; + case "pdf_report": + return { + templateJson: JSON.stringify( + { fields: [{ name: "sample_id", label: "Lab Number:", required: true }] }, + null, + 2, + ), + }; case "astm": return { astmRole: "computer", diff --git a/console/src/api/mock/messageFields.ts b/console/src/api/mock/messageFields.ts index 3f4c0fb..cb1d290 100644 --- a/console/src/api/mock/messageFields.ts +++ b/console/src/api/mock/messageFields.ts @@ -94,7 +94,7 @@ function astmFields(text: string): MessageField[] | null { } /** - * The fields the engine would list for an original (`GetMessage`'s `fields`): HL7 and ASTM by + * The fields the engine would list for an original (`getMessageFields`): HL7 and ASTM by * the paths filters use, a reason in words for what does not parse (`parses` false: the * message is invalid) or has no field list. */ @@ -105,7 +105,7 @@ export function parsedFields(text: string, protocol: Protocol, parses = true): M unavailable, }); if (protocol !== "hl7_mllp" && protocol !== "astm") { - return none("Fields are listed for HL7 and ASTM messages."); + return none("Fields are listed for HL7, ASTM and PDF report messages."); } const all = !parses ? null : protocol === "hl7_mllp" ? hl7Fields(text) : astmFields(text); if (all === null) { diff --git a/console/src/api/mock/messageKinds.ts b/console/src/api/mock/messageKinds.ts index 5ae2199..55d0f00 100644 --- a/console/src/api/mock/messageKinds.ts +++ b/console/src/api/mock/messageKinds.ts @@ -41,9 +41,11 @@ export const stateRank = (kind: number): number => export const PREFIX: Record = { hl7_mllp: "MC", + hl7_file: "HF", astm: "AS", au: "AU", delimited_file: "ROW-", + pdf_report: "PDF-", raw: "RW", }; @@ -76,6 +78,8 @@ export function displayType(protocol: Protocol, type: string): string | null { return "au"; case "delimited_file": return "delimited"; + case "pdf_report": + return "pdf_report"; default: return null; } diff --git a/console/src/api/mock/messageStore.ts b/console/src/api/mock/messageStore.ts index 2054e3c..c91c11c 100644 --- a/console/src/api/mock/messageStore.ts +++ b/console/src/api/mock/messageStore.ts @@ -166,6 +166,7 @@ export class MessageStore extends MessageCommands { responseCode: response?.code ?? null, respondedAt: response === null ? null : iso(response.atMs), ...(created === null ? u.reasonOf(i, kind) : { reasonCode: null, abortReason: null }), + reasonDetail: null, duplicateOf: created === null && kind === K_DUPLICATE ? `msg-${u.duplicateOf(i)}` : null, revisionOf: created === null ? this.idOf(this.revisions.revisionOf(i)) : null, revisedBy: created === null ? this.idOf(this.revisions.revisedBy(i)) : null, diff --git a/console/src/api/mock/pdfReports.ts b/console/src/api/mock/pdfReports.ts new file mode 100644 index 0000000..fbce09d --- /dev/null +++ b/console/src/api/mock/pdfReports.ts @@ -0,0 +1,118 @@ +// The PDF report test of the mock engine (docs/spec/pdf-reports.md §9). The mock cannot read PDF +// files: it takes a file that starts with `%PDF` (or a stored message) as a report printing each +// label of the template once on its own line, followed by a synthetic value, so the editor's test +// view can be built and checked. Any other file is unreadable. A destination gets a short HL7 +// message with the report embedded, shortened as the engine shortens it. + +import { isRecord } from "../ipc/util"; +import type { PdfReportTestRequest, PdfReportTestResult } from "../types"; +import type { MockWorld } from "./world"; + +interface TemplateField { + name: string; + label: string; +} + +/** The fields of a template, each with its first label; null when it is not a template. */ +function templateFields(json: string): TemplateField[] | null { + let template: unknown; + try { + template = JSON.parse(json); + } catch { + return null; + } + if (!isRecord(template) || !Array.isArray(template.fields)) return null; + const fields: TemplateField[] = []; + for (const field of template.fields) { + if (!isRecord(field) || typeof field.name !== "string") return null; + const labels = Array.isArray(field.label) ? field.label : [field.label]; + if (typeof labels[0] !== "string") return null; + fields.push({ name: field.name, label: labels[0] }); + } + return fields; +} + +function isPdf(file: string | undefined): boolean { + try { + return file !== undefined && atob(file).startsWith("%PDF"); + } catch { + return false; + } +} + +const EMPTY: Omit = { + reasonCode: null, + reasonDetail: null, + pages: [], + fields: [], + output: null, + outputError: null, +}; + +export function testPdfReport( + world: MockWorld, + request: PdfReportTestRequest, +): PdfReportTestResult { + const details = { + source: request.messageId === undefined ? "file" : "message", + destination: request.destination?.protocol ?? null, + }; + const object = + request.messageId === undefined + ? {} + : { objectType: "message" as const, objectId: request.messageId }; + world.audit.record({ action: "pdf_report_test", outcome: "requested", details, ...object }); + const fields = templateFields(request.templateJson); + if (fields === null || fields.length === 0) { + world.audit.record({ action: "pdf_report_test", outcome: "failed", details, ...object }); + return world.fail("validation", "The template has 1 error; nothing was read.", [ + { + field: "templateJson", + message: "The template must be a JSON object with 1 to 200 fields.", + }, + ]); + } + const result = + request.messageId !== undefined || isPdf(request.file) + ? read(fields, request) + : { + ...EMPTY, + ok: false, + reasonCode: "pdf_unreadable", + reasonDetail: "the file is not a readable PDF", + }; + world.audit.record({ + action: "pdf_report_test", + outcome: "succeeded", + details: { ...details, ok: result.ok }, + ...object, + }); + return result; +} + +function read(fields: TemplateField[], request: PdfReportTestRequest): PdfReportTestResult { + const values = fields.map((field, i) => ({ + path: `field.${field.name}`, + value: `SYN-${String(i + 1).padStart(4, "0")}`, + })); + const lines = fields.map((field, i) => { + const text = `${field.label} ${values[i]?.value ?? ""}`; + return { + center: 100 + 14 * i, + phrases: [{ text, left: 40, right: 40 + 5 * text.length, size: 9 }], + }; + }); + const output = + request.destination === undefined + ? null + : "MSH|^~\\&|PACKIE|LAB|||20261012120500||ORU^R01|MOCK-0001|P|2.5.1\r" + + `PID|||${values[0]?.value ?? ""}\r` + + "OBX|1|ED|REPORT^Report^L||^AP^PDF^Base64^JVBERi0xLjcKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nO1dW4…(1204 characters)||||||F\r"; + return { + ...EMPTY, + ok: true, + pages: [{ number: 1, lines }], + fields: [...values, { path: "report.pages", value: "1" }], + output, + }; +} diff --git a/console/src/api/mock/validate.ts b/console/src/api/mock/validate.ts index 3586296..f67207a 100644 --- a/console/src/api/mock/validate.ts +++ b/console/src/api/mock/validate.ts @@ -1,3 +1,4 @@ +import { passesThrough } from "@/lib/protocols"; import type { ChannelConfig, ConfigDocument, @@ -156,7 +157,10 @@ function validateDestination( error(issues, `${path}.label`, "The label is required and at most 100 characters."); } // `passthrough_protocol`: with no mapping the original message is delivered as it is. - if (destination.mappings.length === 0 && destination.protocol !== channel.source.protocol) { + if ( + destination.mappings.length === 0 && + !passesThrough(channel.source.protocol, destination.protocol) + ) { error( issues, `${path}.protocol`, diff --git a/console/src/api/mock/validateConnector.ts b/console/src/api/mock/validateConnector.ts index 75ecc86..bb3400a 100644 --- a/console/src/api/mock/validateConnector.ts +++ b/console/src/api/mock/validateConnector.ts @@ -13,7 +13,9 @@ const PROTOCOL_ENDPOINTS: Record = { astm: ["serial", "tcp_client", "tcp_listener"], au: ["serial", "tcp_client", "tcp_listener"], hl7_mllp: ["tcp_client", "tcp_listener"], + hl7_file: ["folder", "sftp"], delimited_file: ["folder", "sftp"], + pdf_report: ["folder", "sftp"], raw: [], }; @@ -72,17 +74,17 @@ function checkTemplate(connector: ConnectorConfig, path: string, issues: Issues) const at = `${path}.settings.templateJson`; const text = connector.settings.templateJson ?? ""; if (blank(text)) { - error(issues, at, "The column template is required for delimited files."); + error(issues, at, "The template is required."); return; } try { const parsed: unknown = JSON.parse(text); if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { - error(issues, at, "The column template must be a JSON object, written with { }."); + error(issues, at, "The template must be a JSON object, written with { }."); } } catch (cause) { const reason = cause instanceof Error ? cause.message : "invalid JSON"; - error(issues, at, `The column template is not valid JSON: ${reason}`); + error(issues, at, `The template is not valid JSON: ${reason}`); } } @@ -181,6 +183,22 @@ function checkSettings( case "delimited_file": checkTemplate(connector, path, issues); return; + case "pdf_report": + if (role === "destination") { + error( + issues, + `${path}.protocol`, + "A PDF report is read from files only; it cannot be a destination.", + ); + } + checkTemplate(connector, path, issues); + return; + case "hl7_file": + if (role === "source") { + error(issues, `${path}.protocol`, "HL7 files are only written; they cannot be a source."); + } + checkTemplate(connector, path, issues); + return; case "au": if (settings.au === undefined) { error(issues, `${path}.settings.au`, "The AU instrument settings are required."); diff --git a/console/src/api/mock/validateEndpoints.ts b/console/src/api/mock/validateEndpoints.ts index ff20d3b..5379f9b 100644 --- a/console/src/api/mock/validateEndpoints.ts +++ b/console/src/api/mock/validateEndpoints.ts @@ -1,6 +1,7 @@ import type { ConfigDocument, EndpointConfig, + FileConsumption, SftpEndpointConfig, TcpListenerEndpointConfig, } from "../types"; @@ -102,6 +103,26 @@ function checkFilePattern(pattern: string, path: string, issues: Issues): void { } } +/** The folders a read file moves to: inside the endpoint's own, and apart from each other. */ +function checkConsumption(endpoint: FileConsumption, path: string, issues: Issues): void { + const folders = [ + ["processedDirectory", endpoint.processedDirectory], + ["filteredDirectory", endpoint.filteredDirectory], + ["invalidDirectory", endpoint.invalidDirectory], + ] as const; + const seen = new Set(); + for (const [field, folder] of folders) { + if (folder === "") continue; + const outside = /^([/\\]|[A-Za-z]:)/.test(folder) || folder.split(/[/\\]/).includes(".."); + if (outside) error(issues, `${path}.${field}`, "Use a folder inside the endpoint's folder."); + else if (seen.has(folder)) error(issues, `${path}.${field}`, "Each folder must differ."); + seen.add(folder); + } + if (endpoint.onConsumed === "move" && endpoint.processedDirectory === "") { + error(issues, `${path}.processedDirectory`, "The processed folder is required."); + } +} + function validateEndpointKind(endpoint: EndpointConfig, path: string, issues: Issues): void { switch (endpoint.kind) { case "serial": @@ -119,9 +140,11 @@ function validateEndpointKind(endpoint: EndpointConfig, path: string, issues: Is case "folder": required(issues, `${path}.path`, endpoint.path, "The folder path"); checkFilePattern(endpoint.filePattern, `${path}.filePattern`, issues); + checkConsumption(endpoint, path, issues); return; case "sftp": validateSftp(endpoint, path, issues); + checkConsumption(endpoint, path, issues); } } diff --git a/console/src/api/types/config.ts b/console/src/api/types/config.ts index 12bdec4..4f67f13 100644 --- a/console/src/api/types/config.ts +++ b/console/src/api/types/config.ts @@ -44,7 +44,20 @@ export interface TcpListenerEndpointConfig extends EndpointConfigBase { keepalive: boolean; } -export interface FolderEndpointConfig extends EndpointConfigBase { +/** + * What a source does with a file once its content is stored (docs/spec/configuration.md §5.4). + * Folders are relative to the endpoint's folder or remote path. + */ +export interface FileConsumption { + onConsumed: "move" | "delete" | "leave"; + processedDirectory: string; + /** PDF report sources: where a report the source filters leave out goes; empty for `processedDirectory`. */ + filteredDirectory: string; + /** PDF report sources: where a report that cannot be read goes; empty for `processedDirectory`. */ + invalidDirectory: string; +} + +export interface FolderEndpointConfig extends EndpointConfigBase, FileConsumption { kind: "folder"; path: string; mode: "watch" | "poll"; @@ -53,7 +66,7 @@ export interface FolderEndpointConfig extends EndpointConfigBase { filePattern: string; } -export interface SftpEndpointConfig extends EndpointConfigBase { +export interface SftpEndpointConfig extends EndpointConfigBase, FileConsumption { kind: "sftp"; host: string; port: number; @@ -277,7 +290,9 @@ export type Step = | { step: "split"; separator: string; take: number } /** At most `length` characters from `start` (0-based); null for the rest of the text. */ | { step: "slice"; start: number; length: number | null } - | { step: "replace"; find: string; with: string }; + | { step: "replace"; find: string; with: string } + /** The text at `from` (another field of the source) removed from the end, at a word boundary. */ + | { step: "strip_suffix"; from: string }; export type StepKind = Step["step"]; diff --git a/console/src/api/types/core.ts b/console/src/api/types/core.ts index d9fe41a..c670038 100644 --- a/console/src/api/types/core.ts +++ b/console/src/api/types/core.ts @@ -93,7 +93,14 @@ export type StopReason = | "not_implemented"; /** Protocol tags of docs/spec/configuration.md §6.4. */ -export type Protocol = "astm" | "au" | "hl7_mllp" | "delimited_file" | "raw"; +export type Protocol = + | "astm" + | "au" + | "hl7_mllp" + | "hl7_file" + | "delimited_file" + | "pdf_report" + | "raw"; export type DeliveryState = | "queued" diff --git a/console/src/api/types/messages.ts b/console/src/api/types/messages.ts index d2cafbf..c1f1485 100644 --- a/console/src/api/types/messages.ts +++ b/console/src/api/types/messages.ts @@ -191,6 +191,8 @@ export interface MessageDetail { abortReason: string | null; /** Why it was filtered or is invalid (`source_filter`, `parse_error`). */ reasonCode: string | null; + /** For an invalid PDF report: what failed, in template terms (never report text). */ + reasonDetail: string | null; /** The earlier message this one duplicates. */ duplicateOf: string | null; /** The earlier message with the same identity and other content. */ diff --git a/console/src/api/types/setup.ts b/console/src/api/types/setup.ts index 661250d..dc31fbe 100644 --- a/console/src/api/types/setup.ts +++ b/console/src/api/types/setup.ts @@ -1,7 +1,7 @@ // Setup checks (docs/spec/diagnostics.md §10) and notifications (§6.1): read-only, nothing is // sent to an instrument or a destination system. import type { SerialPortKind } from "@/ipc/generated"; -import type { EndpointConfig } from "./config"; +import type { DestinationConfig, EndpointConfig } from "./config"; export type { SerialPortKind }; @@ -55,6 +55,59 @@ export interface ProbeReport { summary: string; } +/** + * A PDF report read with a template, and mapped for a destination when one is given + * (docs/spec/pdf-reports.md §9): the editor's current, possibly unsaved, settings. Nothing is + * stored or sent; the engine audits the test. + */ +export interface PdfReportTestRequest { + /** The source's template as the editor holds it (a JSON object). */ + templateJson: string; + /** The report: its bytes in Base64, at most 8 MiB. */ + file?: string; + /** Or a stored PDF report message, whose original is read. */ + messageId?: string; + /** A destination of the channel to map the report for. */ + destination?: DestinationConfig; +} + +/** One phrase of an extracted line, in points from the top left of the page. */ +interface PdfPhraseLayout { + text: string; + left: number; + right: number; + size: number; +} + +interface PdfLineLayout { + /** Vertical center, points from the top of the page. */ + center: number; + phrases: PdfPhraseLayout[]; +} + +interface PdfPageLayout { + number: number; + lines: PdfLineLayout[]; +} + +/** What a PDF report test found. Report content: shown only in the test's own view. */ +export interface PdfReportTestResult { + /** The report reads with the template. */ + ok: boolean; + /** Why not: `pdf_unreadable`, `pdf_no_text`, `pdf_limits`, `template_mismatch`, `field_invalid`. */ + reasonCode: string | null; + /** What failed, in template terms. */ + reasonDetail: string | null; + /** The extracted lines, to write or correct a template. */ + pages: PdfPageLayout[]; + /** `field.` and `report.pages` with their values; empty when the report does not read. */ + fields: { path: string; value: string }[]; + /** The message mapped for the destination, the embedded report shortened. */ + output: string | null; + /** The mapping's transform error instead. */ + outputError: string | null; +} + /** The outcome of a test message to one notification target. */ export interface NotificationResult { /** `email` or `webhook`. */ diff --git a/console/src/features/audit/auditLabels.ts b/console/src/features/audit/auditLabels.ts index 970e285..a0f81a0 100644 --- a/console/src/features/audit/auditLabels.ts +++ b/console/src/features/audit/auditLabels.ts @@ -33,6 +33,7 @@ export const ACTION_LABELS: Readonly> = { traffic_view: "Traffic transcript opened", client_export: "Client export written", endpoint_test: "Endpoint tested", + pdf_report_test: "PDF report tested", notification_test: "Notification test sent", engine_start: "Engine started", engine_stop: "Engine stopped", diff --git a/console/src/features/config/ConnectorFields.tsx b/console/src/features/config/ConnectorFields.tsx index 5c01279..4f7a7a6 100644 --- a/console/src/features/config/ConnectorFields.tsx +++ b/console/src/features/config/ConnectorFields.tsx @@ -5,9 +5,10 @@ import { ChoiceInput, PickerInput, TextInput } from "@/components/FormFields"; import type { RecordOption } from "@/components/RecordPicker"; import { protocolLabel } from "@/lib/status"; import { AuFields } from "./AuFields"; -import { passthroughProblem, STARTER_TEMPLATE } from "./channelForm"; +import { HL7_FILE_STARTER, passthroughProblem, STARTER_TEMPLATE } from "./channelForm"; import { protocolsFor } from "./connectorProtocols"; import { FormCheckbox } from "./FormCheckbox"; +import { PdfTestButton } from "./PdfTestButton"; import { ConnectorPresets } from "./presets/ConnectorPresets"; import { parseCodes, sampleIdPathProblem } from "./settingsForm"; import { TemplateJsonField } from "./TemplateJsonField"; @@ -185,7 +186,15 @@ function ProtocolSettings({ case "au": return ; case "delimited_file": - return ; + case "hl7_file": + return ; + case "pdf_report": + return ( + <> + + {side === "source" && } + + ); default: return null; } @@ -244,7 +253,7 @@ export function ConnectorFields({ const protocol = useWatch({ control, name: `${prefix}.protocol` }) as Protocol | null; const endpointId = useWatch({ control, name: `${prefix}.endpointId` }) as string | null; const kind = endpoints.find((endpoint) => endpoint.id === endpointId)?.kind ?? null; - const allowed: Protocol[] = protocolsFor(kind); + const allowed: Protocol[] = protocolsFor(kind, side); const options = allowed.map((id) => ({ id, label: protocolLabel(id) })); // A protocol the endpoint no longer suits stays visible, so the error has something to name. if (protocol && !allowed.includes(protocol)) { @@ -278,7 +287,9 @@ export function ConnectorFields({ }} onChange={(chosen) => { const blank = String(getValues(templateName) ?? "").trim() === ""; - if (chosen === "delimited_file" && blank) setValue(templateName, STARTER_TEMPLATE); + if (!blank) return; + if (chosen === "delimited_file") setValue(templateName, STARTER_TEMPLATE); + if (chosen === "hl7_file") setValue(templateName, HL7_FILE_STARTER); }} /> diff --git a/console/src/features/config/ConnectorSettings.test.tsx b/console/src/features/config/ConnectorSettings.test.tsx index 37a5a5b..3ae19bb 100644 --- a/console/src/features/config/ConnectorSettings.test.tsx +++ b/console/src/features/config/ConnectorSettings.test.tsx @@ -61,6 +61,7 @@ describe("source: duplicate detection and protocol by endpoint kind", () => { "AU", "HL7 v2", "Delimited files", + "PDF reports", ]); await pickEndpoint(user, source, "Endpoint", /^Chemistry serial/); expect(await optionsOf(user, source, "Protocol")).toEqual(["ASTM", "AU"]); @@ -69,12 +70,43 @@ describe("source: duplicate detection and protocol by endpoint kind", () => { await pickEndpoint(user, source, "Endpoint", /^Analyzer link/); expect(await optionsOf(user, source, "Protocol")).toEqual(["ASTM", "AU", "HL7 v2"]); await pickEndpoint(user, source, "Endpoint", /^Incoming folder/); - expect(await optionsOf(user, source, "Protocol")).toEqual(["Delimited files"]); + expect(await optionsOf(user, source, "Protocol")).toEqual(["Delimited files", "PDF reports"]); await pickEndpoint(user, source, "Endpoint", /^Partner SFTP/); - expect(await optionsOf(user, source, "Protocol")).toEqual(["Delimited files"]); + expect(await optionsOf(user, source, "Protocol")).toEqual(["Delimited files", "PDF reports"]); const destination = group("Destination 1"); await pickEndpoint(user, destination, "Endpoint", /^Chemistry serial/); expect(await optionsOf(user, destination, "Protocol")).toEqual(["ASTM", "AU"]); + // A PDF report is only ever read, HL7 files only written. + await pickEndpoint(user, destination, "Endpoint", /^Partner SFTP/); + expect(await optionsOf(user, destination, "Protocol")).toEqual([ + "HL7 v2 files", + "Delimited files", + ]); + }); + + it("starts an HL7 file destination with a file name and the header fields", async () => { + const { user } = await openNewMessage(); + const destination = group("Destination 1"); + await pickEndpoint(user, destination, "Endpoint", /^Partner SFTP/); + await pick(user, destination, "Protocol", "HL7 v2 files"); + const settings = within(destination).getByRole("textbox", { + name: "File and header settings (JSON)", + }); + const starter = JSON.parse((settings as HTMLTextAreaElement).value) as Record; + expect(starter.file_name).toBe("{sample_id}_{date}{time}_{seq}.hl7"); + expect(starter).toHaveProperty("sending_facility"); + }); + + it("offers a PDF test under a PDF report source's template", async () => { + const { user } = await openNewMessage(); + const source = group("Source"); + await pickEndpoint(user, source, "Endpoint", /^Incoming folder/); + await pick(user, source, "Protocol", "Delimited files"); + expect(within(source).queryByRole("button", { name: "Test with a PDF…" })).toBeNull(); + await pick(user, source, "Protocol", "PDF reports"); + expect(within(source).getByText("Report template (JSON)")).toBeTruthy(); + await user.click(within(source).getByRole("button", { name: "Test with a PDF…" })); + expect(await screen.findByRole("dialog", { name: "Test with a PDF" })).toBeTruthy(); }); it("names a protocol that no longer suits a changed endpoint and refuses to save it", async () => { @@ -86,6 +118,7 @@ describe("source: duplicate detection and protocol by endpoint kind", () => { await pickEndpoint(user, source, "Endpoint", /^Incoming folder/); expect(await optionsOf(user, source, "Protocol")).toEqual([ "Delimited files", + "PDF reports", "ASTM (does not suit this endpoint)", ]); await user.click(screen.getByRole("button", { name: "Save and apply" })); diff --git a/console/src/features/config/EndpointFields.tsx b/console/src/features/config/EndpointFields.tsx index 629e82f..6c58aac 100644 --- a/console/src/features/config/EndpointFields.tsx +++ b/console/src/features/config/EndpointFields.tsx @@ -16,6 +16,7 @@ import { HOST_KEY_FINGERPRINT, PEER_ADDRESS, portNumber, + subfolder, wholeNumber, } from "./validators"; @@ -43,6 +44,11 @@ const FOLDER_MODES = [ { id: "watch", label: "Watch for new files" }, { id: "poll", label: "Poll on a schedule" }, ]; +const ON_CONSUMED = [ + { id: "move", label: "Move it into a folder" }, + { id: "delete", label: "Delete it" }, + { id: "leave", label: "Leave it where it is" }, +]; function SerialFields() { return ( @@ -179,6 +185,55 @@ function FolderFields() { ); } +/** + * What a source does with a file once its content is stored (docs/spec/configuration.md §5.4), + * and for PDF reports the folders that keep filtered and unreadable reports apart. + */ +function AfterReading() { + const form = useFormContext(); + const action = useWatch({ control: form.control, name: "onConsumed" }); + return ( + + + + {action === "move" && ( + <> + + + + + )} + + + ); +} + interface SecretNameProps { /** The form field holding the name. */ name: "secretName" | "passphraseSecretName"; @@ -284,8 +339,18 @@ export function ConnectionFields({ kind }: { kind: EndpointKind }) { case "tcp_listener": return ; case "folder": - return ; + return ( + <> + + + + ); case "sftp": - return ; + return ( + <> + + + + ); } } diff --git a/console/src/features/config/EndpointSettings.test.tsx b/console/src/features/config/EndpointSettings.test.tsx index 8648532..dd5b501 100644 --- a/console/src/features/config/EndpointSettings.test.tsx +++ b/console/src/features/config/EndpointSettings.test.tsx @@ -227,3 +227,70 @@ describe("EndpointEditPage: connection settings", () => { }); }); }); + +describe("EndpointEditPage: after a file is read", () => { + async function openFolder() { + const rendered = await openNewEndpoint(stubApi()); + await pick(rendered.user, document.body, "Kind", "Folder"); + await rendered.user.type(screen.getByRole("textbox", { name: /^Label/ }), "Reports"); + await rendered.user.type( + screen.getByRole("textbox", { name: /^Folder path/ }), + "/data/reports", + ); + return rendered; + } + + it("moves files to processed by default and saves the filtered and unreadable folders", async () => { + const { api, user } = await openFolder(); + const section = screen.getByRole("group", { name: "After a file is read" }); + const processed = within(section).getByRole("textbox", { name: /^Processed folder/ }); + expect((processed as HTMLInputElement).value).toBe("processed"); + await user.type(within(section).getByRole("textbox", { name: /^Filtered reports/ }), "skipped"); + await user.type( + within(section).getByRole("textbox", { name: /^Unreadable reports/ }), + "errors", + ); + expect(await lastDocument(user, api)).toMatchObject({ + kind: "folder", + onConsumed: "move", + processedDirectory: "processed", + filteredDirectory: "skipped", + invalidDirectory: "errors", + }); + }); + + it("refuses a folder outside the endpoint's own before calling the engine", async () => { + const { api, user } = await openFolder(); + await user.type(screen.getByRole("textbox", { name: /^Filtered reports/ }), "../elsewhere"); + await user.click(screen.getByRole("button", { name: "Validate" })); + expect( + await screen.findByText("Enter a folder inside the endpoint's folder, such as processed."), + ).toBeTruthy(); + expect(api.validateConfig).not.toHaveBeenCalled(); + }); + + it("drops the outcome folders when files are deleted instead", async () => { + const { api, user } = await openFolder(); + await user.type(screen.getByRole("textbox", { name: /^Filtered reports/ }), "skipped"); + await pick(user, document.body, "Then", "Delete it"); + expect(screen.queryByRole("textbox", { name: /^Filtered reports/ })).toBeNull(); + expect(await lastDocument(user, api)).toMatchObject({ + onConsumed: "delete", + filteredDirectory: "", + }); + }); + + it("keeps the folders of an existing SFTP endpoint", async () => { + const doc = sampleConfig(); + doc.endpoints.push({ + ...sampleSftp(), + filteredDirectory: "skipped", + invalidDirectory: "errors", + } as never); + const api = stubApi({ getConfig: async () => doc }); + await openEndpoint("partner-sftp", "Partner SFTP", api); + expect( + (screen.getByRole("textbox", { name: /^Unreadable reports/ }) as HTMLInputElement).value, + ).toBe("errors"); + }); +}); diff --git a/console/src/features/config/PdfTestButton.tsx b/console/src/features/config/PdfTestButton.tsx new file mode 100644 index 0000000..9eb1678 --- /dev/null +++ b/console/src/features/config/PdfTestButton.tsx @@ -0,0 +1,40 @@ +// "Test with a PDF…" under a PDF report source's template (docs/spec/pdf-reports.md §9): reads +// a chosen report with the template as the editor holds it, and maps it for one of the +// channel's destinations as they are edited, before anything is applied. +import { useState } from "react"; +import { useFormContext } from "react-hook-form"; +import type { DestinationConfig } from "@/api/types"; +import { Button } from "@/components/Button"; +import { PdfReportTest } from "@/features/pdfReports/PdfReportTest"; +import { type ChannelFormValues, valuesToChannel } from "./channelForm"; + +export function PdfTestButton({ templateName }: { templateName: string }) { + const { getValues } = useFormContext(); + const [test, setTest] = useState<{ + templateJson: string | null; + destinations: DestinationConfig[]; + } | null>(null); + function open() { + const channel = valuesToChannel(getValues() as ChannelFormValues); + const template = getValues(templateName) as string | undefined; + setTest({ + templateJson: template?.trim() ? template : null, + destinations: channel?.kind === "message" ? channel.destinations : [], + }); + } + return ( + <> + + {test !== null && ( + { + if (!isOpen) setTest(null); + }} + templateJson={test.templateJson} + destinations={test.destinations} + /> + )} + + ); +} diff --git a/console/src/features/config/StepFields.tsx b/console/src/features/config/StepFields.tsx index 60c989b..318cd12 100644 --- a/console/src/features/config/StepFields.tsx +++ b/console/src/features/config/StepFields.tsx @@ -14,6 +14,7 @@ const KINDS: { id: StepKind; label: string }[] = [ { id: "split", label: "Take one part of a split" }, { id: "slice", label: "Keep part of the text" }, { id: "replace", label: "Replace text" }, + { id: "strip_suffix", label: "Remove another field from the end" }, { id: "upper", label: "Upper case" }, { id: "lower", label: "Lower case" }, ]; @@ -27,6 +28,8 @@ const KIND_HELP: Record = { slice: "Keeps at most Length characters from Start (the first character is 0). Empty when Start is past the end.", replace: "Replaces every occurrence of the text, exactly as typed, with the other text.", + strip_suffix: + "Removes the text of another field from the end, ignoring case: TEST BABY DOE without DOE becomes TEST BABY. When the text does not end with it, the result is empty.", upper: "Changes letters to upper case.", lower: "Changes letters to lower case.", }; @@ -92,6 +95,14 @@ function StepFields({ name }: { name: string }) { /> )} + {kind === "strip_suffix" && ( + + )} {kind === "replace" && ( <> - Column template (JSON) + {TEXT[protocol].label}