001/*-
002 * #%L
003 * Smile CDR - CDR
004 * %%
005 * Copyright (C) 2016 - 2024 Smile CDR, Inc.
006 * %%
007 * All rights reserved.
008 * #L%
009 */
010package ca.cdr.api.pub.hl7v2.common.abstraction;
011
012import ca.uhn.hl7v2.HL7Exception;
013import ca.uhn.hl7v2.model.AbstractMessage;
014import ca.uhn.hl7v2.model.v25.group.OMG_O19_ORDER;
015import ca.uhn.hl7v2.model.v25.group.ORM_O01_ORDER;
016import ca.uhn.hl7v2.model.v25.message.OMG_O19;
017import ca.uhn.hl7v2.model.v25.message.ORM_O01;
018import ca.uhn.hl7v2.model.v25.segment.OBR;
019import ca.uhn.hl7v2.model.v25.segment.ORC;
020
021import java.util.List;
022import java.util.function.Function;
023import java.util.stream.Collectors;
024
025/**
026 * Wraps the relevant portion of an HL7 V2 message to an {@link IOrderMessage}
027 */
028public class OrderMessageFactory {
029
030        public IOrderMessage asOrderMessage(AbstractMessage theMsg) throws HL7Exception {
031                if (theMsg instanceof ORM_O01) {
032                        return asOrderMessage((ORM_O01) theMsg);
033                } else if (theMsg instanceof OMG_O19) {
034                        return asOrderMessage((OMG_O19) theMsg);
035                } else {
036                        return null;
037                }
038        }
039
040        private IOrderMessage asOrderMessage(ORM_O01 theMessage) throws HL7Exception {
041                OrderMessage retVal = new OrderMessage();
042
043                Function<ORM_O01_ORDER, ORC> orcF = ORM_O01_ORDER::getORC;
044                Function<ORM_O01_ORDER, OBR> obrF = o -> o.getORDER_DETAIL().getOBR();
045
046                List<IOrderMessage.IOrder> orders = theMessage.getORDERAll().stream()
047                                .map(t -> new OrderMessageOrder<>(t, orcF, obrF))
048                                .collect(Collectors.toList());
049
050                retVal.setOrders(
051                                orders, () -> new OrderMessageOrder<>(theMessage.insertORDER(theMessage.getORDERReps()), orcF, obrF));
052
053                return retVal;
054        }
055
056        private IOrderMessage asOrderMessage(OMG_O19 theMessage) throws HL7Exception {
057                OrderMessage retVal = new OrderMessage();
058
059                Function<OMG_O19_ORDER, ORC> orcF = OMG_O19_ORDER::getORC;
060                Function<OMG_O19_ORDER, OBR> obrF = OMG_O19_ORDER::getOBR;
061
062                List<IOrderMessage.IOrder> orders = theMessage.getORDERAll().stream()
063                                .map(t -> new OrderMessageOrder<>(t, orcF, obrF))
064                                .collect(Collectors.toList());
065
066                retVal.setOrders(
067                                orders, () -> new OrderMessageOrder<>(theMessage.insertORDER(theMessage.getORDERReps()), orcF, obrF));
068
069                return retVal;
070        }
071}