<?xml version="1.0" encoding="UTF-8"?>
<Export generator="Cache" version="22" zv="Cache for Windows (x86-32) 2009.1.6 (Build 921U)" ts="2011-12-21 11:19:20">
<Routine name="AGMPBC32" type="INT" languagemode="0" timestamp="62006,48676"><![CDATA[
AGMPBC32 ;IHS/SD/TPF - SIMPLE PULL FOR C32 FOLKS ; 12/15/2007
 ;;7.2;PATIENT REGISTRATION;;OCT 07, 2010
 Q
PULLC32 ;EP - PULL FACILITY DATA
 S GLOREF="^AGMPBULK"
 K @GLOREF
 S JOB=$J
 S B="|"
 N DUZ2,TEMPDUZ2,DIREC,DIREC2
 ;
 K ^AGMPBULK(JOB)
 S COUNT=0
 D NOW^%DTC
 S BEGIN=%
 S DURSTART=$P($H,",",2)
 S IEN=0
 F  S IEN=$O(^DPT(IEN)) Q:'IEN  D
 .Q:$G(^DPT(IEN,0))=""  ;EMPTY ENTRY
 .Q:$D(^DPT(IEN,-9))  ;DO NOT PROCESS MERGED STUBS
 .S COUNT=COUNT+1
 .S DUZ2=0
 .F  S DUZ2=$O(^AUPNPAT(IEN,41,DUZ2)) Q:'DUZ2  D
 ..Q:$P($G(^AGFAC(DUZ2,0)),U,21)'="Y"  ;ONLY 'OFFICAL REGISTERING FACILITIES"
 ..S STATION=$$GET1^DIQ(4,DUZ2_",",99,"I")
 ..S ^AGMPBULK(JOB,IEN,STATION)=IEN_","_STATION
 ;
 S DIREC=$$GET1^DIQ(9009061,DUZ(2)_",",2201,"E")
 S IP=$$GET1^DIQ(779.1,1_",",.01)
 S FILENM="C32_PULL_FOR_ALEX_FROM_RPMS_DB_"_IP_".DAT"
 D SENDFILE(DIREC,FILENM,"AGMPBULK(")
 D END(DIREC)
 Q
 ;
END(DIREC) ;EP - STORE BATCH RUN COUNT AND TIME
 D NOW^%DTC
 S END=%
 S DUREND=$P($H,",",2)
 S DURATION=DUREND-DURSTART
 S DURATION=$FN(DURATION/60,",",2)
 S Y=BEGIN X ^DD("DD") S BEGIN=Y
 S Y=END X ^DD("DD") S END=Y
 K ^AGMPBULK(JOB)
 S ^AGMPBULK("AGMPBULK",$J,"C32","DIRECTORY LOCATION")=$S(DIREC="":"DIRECTORY UNDEFINED",1:DIREC)
 S ^AGMPBULK("AGMPBULK",$J,"C32","EXTRACT STARTED")=BEGIN
 S ^AGMPBULK("AGMPBULK",$J,"C32","ENTRACT ENDED")=END
 S ^AGMPBULK("AGMPBULK",$J,"C32","ELAPSED TIME")=DURATION
 S ^AGMPBULK("AGMPBULK",$J,"C32","RECORDS PROCESSED")=COUNT
 Q
 ;
SENDFILE(XBUF,XBFN,XBGL) ; EP - CREATE FLAT FILE FOR UFMS USING XBGSAVE
 ;XBUF=DIRECTORY
 ;XBFN=FILENAME
 ;XBGL=GLOBAL
 S XBQSHO=""
 S XBF=$J                       ; Beginning 1st level numeric subscript
 S XBE=$J                       ; Ending 1st level numeric subscript
 S XBFLT=1                      ; indicates flat file
 S XBMED="F"                    ; Flag indicates file as media
 S XBCON=1                      ; Q if non-canonic
 S XBQ="N"
 S XBFLG=0
 I '$G(BATCH) S XBS1=""  ;SO IT WON'T FTP ACROSS.
 E  D
 .S XBS1=$S('$D(ZTQUEUED):"AGMP MPI F",1:"AGMP MPI B")
 D ^XBGSAVE
 Q
]]></Routine>


<Routine name="AGMPHLU1" type="INT" languagemode="0" timestamp="62048,42879"><![CDATA[
AGMPHLU1 ; IHS/SD/TPF - MPI HLO UTILITIES		 ; 12/15/2007
 ;;7.2;PATIENT REGISTRATION;;OCT 07, 2010
 Q
 ;
 ;OIT PROGRAMMER USE ONLY - NO OPTION
LOADTST(EVENT,START,LASTCNT) ;EP - TEST MPI LOAD
 N IEN,COUNT,CNT
 S COUNT=0
 S IEN=$G(START)
 S:IEN="" IEN=0
 F CNT=1:1 S IEN=$O(^DPT(IEN)) Q:'IEN!(COUNT>LASTCNT)  D
 .Q:$P($G(^DPT(IEN,"MPI")),U)'=""  ;DURING TESTING DON'T SEND IF ALREADY SENT
 .Q:$D(^DPT(IEN,-9))
 .Q:'$O(^AUPNPAT(IEN,41,0))
 .S COUNT=COUNT+1
 .I '(CNT#100) W "."
 .D NOW^%DTC S NOW=%
 .I EVENT="A01" D CREATE^AGMPHL01(4,IEN,NOW) Q
 .I EVENT="A03" D CREATE^AGMPHL03(1,IEN,"T"_NOW) Q
 .D CREATMSG^AGMPIHLO(IEN,EVENT)
 W !,"TOTAL "_EVENT_" MESSAGES SENT: ",COUNT
 Q
 ;
FINDERR ;EP - SEACH FOR ERR IN ^HLA
FROMERR ;EP
 K DIR
 S DIR(0)="DO^::E"
 S DIR("A")="Enter from Date"
 S DIR("B")="T"
 D ^DIR
 Q:$D(DTOUT)!$D(DUOUT)!$D(DIROUT)!(Y="")
 S FROMERR=Y
TOERR ;EP
 K DIR
 S DIR(0)="DO^::E"
 S DIR("A")="Enter to Date"
 S DIR("B")="T"
 D ^DIR
 G:$D(DTOUT)!$D(DUOUT)!$D(DIROUT)!(Y="") FROMERR
 S TOERR=Y_".999999"
 I FROMERR>TOERR D  G FROMERR
 .W !!,"FROM DATE CAN NOT BE GREATER THAN TO DATE!!" H 2
 S FROMERR=FROMERR-.00001
SHOW ;EP
 K DIR
 S DIR(0)="YO"
 S DIR("A")="Display originating message"
 S DIR("B")="N"
 D ^DIR
 G:$D(DTOUT)!$D(DUOUT)!$D(DIROUT)!(Y="") TOERR
 S SHOW=Y
 W !!,"FINDING ERR SEGMENTS IN HLA"
 N COUNT,MSG,DASH
 S COUNT=0
 D DOCOUNT(.COUNT)
 W !!,"THERE WERE "_COUNT_" ERR ERRORS FOUND"
 I COUNT=0 D  Q
 .K DIR
 .S DIR(0)="E"
 .D ^DIR
 S %ZIS="MQ"
 W !
 D ^%ZIS
 Q:POP
 I $D(IO("Q")) D QUEERR Q
 U IO
QUEPRINT ;EP ENTER FROM TASKMAN
 S $P(DASH,"-",81)=""
 N CODECNT
 S TOTCOUNT=0
 S ESC=0
 S PAGE=1
 D NOW^%DTC S Y=% X ^DD("DD") S PRTDATE=Y
 D HDRERR
 S MSGDATE=FROMERR-.0001
 F  S MSGDATE=$O(^HLA("B",MSGDATE)) Q:MSGDATE=""!(ESC)  D
 .Q:+MSGDATE>TOERR!(+MSGDATE<FROMERR)
 .S MSGIEN=""
 .F  S MSGIEN=$O(^HLA("B",MSGDATE,MSGIEN)) Q:MSGIEN=""!(ESC)  D
 ..S LINK=$P($G(^HLB(MSGIEN,0)),U,5)
 ..Q:LINK'="MPI"
 ..;W !,MSGDATE
 ..Q:$P($G(^HLA(MSGIEN,1,3,0)),U)'="ERR"
 ..S ENTRYDT=$P($G(^HLA(MSGIEN,0)),U)
 ..S ACKCODE=$P($G(^HLA(MSGIEN,1,1,0)),U,2)
 ..S MSGID=$P($G(^HLA(MSGIEN,1,1,0)),U,3)
 ..S OMSGIEN=$P(MSGID," ",2)
 ..S LOCALID=$P($P($G(^HLA(OMSGIEN,1,3,0)),"|",3),"~")
 ..S TOTCOUNT=TOTCOUNT+1
 ..I $Y>(IOSL-4),(IO=IO(0)),'$D(IO("S")) K DIR S DIR(0)="E" D:'$D(ZTQUEUED) ^DIR S ESC=$G(X)=U Q:ESC  D HDRERR
 ..I $Y>(IOSL-4),$D(ZTQUEUED) D HDRERR
 ..W !!,DASH
 ..W !,"PATIENT DFN: ",LOCALID
 ..W !,"HLA IEN: ",MSGIEN
 ..W !,"MSG ID: ",MSGID
 ..W !,"ORIGINATING MSG IEN: ",OMSGIEN
 ..W !,"ACK CODE: ",ACKCODE
 ..W !,$G(^HLA(MSGIEN,1,3,0))
 ..S CODECNT(ACKCODE)=$G(CODECNT(ACKCODE))+1
 ..I SHOW D LISTOMSG(OMSGIEN)  ;LIST ORIGINATING MESSAGE
 D PRTERRCD(.CODECNT)  ;PRINT ACK CODE COUNTS
 W !!!,"TOTAL ERRORS: ",TOTCOUNT
 I '$D(ZTQUEUED) D
 .U 0
 .W !
 .K DIR
 .S DIR(0)="E"
 .D ^DIR
 D ^%ZISC
 Q
 ;
HDRERR ;EP - HEADER
 W @IOF
 W !,$$C^XBFUNC("MSG ERR REPORT",IOM)
 W ?70,"PAGE ",PAGE
 S PAGE=PAGE+1
 W !,$$CJ^XLFSTR("DATE PRINTED: "_PRTDATE,IOM)
 W !,$$CJ^XLFSTR("PRINTED BY: "_$P($G(^VA(200,DUZ,0)),U),IOM)
 W !,DASH,!!
 Q
 ;
PRTERRCD(CODECNT) ;EP
 N ACKCODE
 S ACKCODE=""
 F  S ACKCODE=$O(CODECNT(ACKCODE)) Q:ACKCODE=""  D
 .W !,"TOTAL "_ACKCODE_" ERRS: ",CODECNT(ACKCODE)
 Q
 ;
QUEERR ; EP - QUE AE ERROR REPORT
 S ZTRTN="QUEPRINT^AGMPHLU1"
 S ZTDESC="HLO AE ERROR MESSAGE REPORT"
 S ZTSAVE("FROMERR")=""
 S ZTSAVE("TOERR")=""
 S ZTSAVE("SHOW")=""
 D ^%ZTLOAD
 I $D(ZTSK)[0 W !!?5,"Report Cancelled!"
 E  W !!?5,"Report task #: ",$G(ZTSK)
 D HOME^%ZIS
 Q
 ;
DOCOUNT(COUNT) ;EP - GET COUNT OF ERR MSGS
 S MSGIEN=0 F  S MSGIEN=$O(^HLA(MSGIEN)) Q:'MSGIEN  D
 .S ENTRYDT=$P($G(^HLA(MSGIEN,0)),U)
 .Q:ENTRYDT>TOERR!(ENTRYDT<FROMERR)
 .Q:$P($G(^HLA(MSGIEN,1,3,0)),U)'="ERR"
 .S COUNT=COUNT+1
 Q
 ;
LISTOMSG(OMSGIEN) ;EP - LIST ORIGINATING MESSAGE
 N DATA
 W !!,"ORINATING MESSAGE:"
 S REC=0
 F  S REC=$O(^HLA(OMSGIEN,1,REC)) Q:'REC  D
 .S DATA=$G(^HLA(OMSGIEN,1,REC,0))
 .Q:DATA=""
 .W !,DATA
 Q
 ;
FINDSEG(SEG,SHOW) ;EP - FIND SEG SEGMENT IN MESSAGE
 ;YOU CAN USE THIS FOR ANY EN MASSE CHANGES
 ;OIT PROGRAMMER USE ONLY - NO OPTION
 N IEN,REC,MSGTYPE,FOUND
 S FOUND=0
 I SEG="MSH" S GLOREF="^HLB"
 E  S GLOREF="^HLA"
 S IEN=0
 F  S IEN=$O(@GLOREF@(IEN)) Q:'IEN  D
 .I SEG'="MSH" D
 ..S REC=0
 ..F  S REC=$O(@GLOREF@(IEN,1,REC)) Q:'REC  D
 ...Q:$P($G(@GLOREF@(IEN,1,REC,0)),U)'=SEG
 ...;PLACE ANY EDITS NEEDED HERE
 ...W !,@GLOREF@(IEN,1,REC,0)
 ...S TEMP=$P(@GLOREF@(IEN,1,REC,0),U,45)
 ...S DATE=$P(TEMP," ")
 ...S TIME=$P(TEMP," ",2)
 ...W !,"DATE: ",DATE
 ...W !,"TIME: ",TIME
 ...S FOUND=FOUND+1
 ...S FOUND(IEN)=""
 .E  D   ;EDITS TO MSH HEADER
 ..Q:$P($G(@GLOREF@(IEN,0)),U,4)'="O"  ;ONLY OUTGOING
 ..;PLACE ANY EDITS NEEDED HERE
 ..W !!!,"IEN: ",IEN
 ..W !,$G(@GLOREF@(IEN,1))
 ..W !,$P($G(@GLOREF@(IEN,1)),U,6)
 ..;S TEMP=$P($G(@GLOREF@(IEN,1)),U,6)
 ..;I $P(TEMP,"~")="8990" Q
 ..;S $P(TEMP,"~")="8990"
 ..;B "S+"
 ..;S $P(@GLOREF@(IEN,1),U,6)=TEMP
 ..S FOUND=FOUND+1
 ..S FOUND(IEN)=""
 W !,"FOUND "_FOUND_" "_SEG_" IN MESSAGE"
 ;ZW FOUND
 Q
 ;
ASKEVN ;EP - ASK EVENT
 N EVENT,MSGTYPE,ACKCODE,ONLYCNT
 K DIR
 S DIR(0)="SO^A28:ADD A PATIENT;A08:UPDATE A PATIENT;A40:MERGE PATIENTS"
 S DIR(0)=DIR(0)_";A01:ADMIT/CHECKIN A PATIENT;A03:DISCHARGE/CHECK OUT A PATIENT"
 S DIR(0)=DIR(0)_";M05:TREATING FACILITY UPDATE"  ;OR MFN?
 S DIR("A")="ENTER EVENT"
 D ^DIR
 Q:$D(DTOUT)!$D(DUOUT)!(Y="")
 S EVENT=Y
ASKTYPE ;EP - ASK MSG TYPE
 K DIR
 S DIR(0)="SO^ADT:ADMIT DISCHARGE TRANSFER;ACK:ACKNOWLEDGEMENTS;MFN:TREATING FACILITY UPDATE"
 S DIR("A")="ENTER MSG TYPE"
 D ^DIR
 G:$D(DTOUT)!$D(DUOUT)!(Y="") ASKEVN
 S MSGTYPE=Y
 ;B "S+"
 S ACKCODE=""
 I MSGTYPE="ACK" D  Q:$D(DTOUT)!$D(DUOUT)!(Y="")
 .K DIR
 .S DIR(0)="SO^AA:APPLICATION ACCEPT;AE:APPLICATION ERROR;AR:APPLICATION REJECT"
 .S DIR(0)=DIR(0)_";CA:COMMIT ACCEPT;CE:COMMIT ERROR;CR:COMMIT REJECT"  ;OR MFN?
 .S DIR("A")="ENTER ACK CODE"
 .D ^DIR
 .S ACKCODE=Y
ASKCNT ;EP - ASK IF ONLY A COUNT IS NEEDED
 K DIR
 S DIR(0)="YO"
 S DIR("A")="TOTALS ONLY"
 D ^DIR
 G:$D(DTOUT)!$D(DUOUT)!(Y="") ASKTYPE
 S ONLYCNT=Y=1
 S %ZIS="MQ"
 W !
 D ^%ZIS
 Q:POP
 I $D(IO("Q")) D QUEEVN Q
 U IO
FINDEVN ;EP - FIND EVENT
 ;FINDEVN("A28","ACK","CA")
 N IEN,REC,FOUND,DASH
 S $P(DASH,"-",81)=""
 D NOW^%DTC S Y=% X ^DD("DD") S PRTDATE=Y
 S PAGE=1
 D HDREVN
 S ESC=0
 S FOUND=0
 S IEN=0
 F  S IEN=$O(^HLA(IEN)) Q:'IEN!ESC  D
 .I EVENT'="" Q:$P($G(^HLA(IEN,0)),U,4)'=EVENT
 .I MSGTYPE'="" Q:$P($G(^HLA(IEN,0)),U,3)'=MSGTYPE
 .Q:$G(^HLA(IEN,1,1,0))'[ACKCODE
 .I $Y>(IOSL-4),(IO=IO(0)),'$D(IO("S")) K DIR S DIR(0)="E" D:'$D(ZTQUEUED) ^DIR S ESC=$G(X)=U Q:ESC  D HDREVN
 .I $Y>(IOSL-4),$D(ZTQUEUED) D HDREVN
 .I 'ONLYCNT D
 ..W !!,IEN_" *** "_$G(^HLA(IEN,0))
 ..D LISTOMSG(IEN)
 .S FOUND=FOUND+1
 W !,"FOUND "_FOUND_" '"_EVENT_"' EVENTS IN ^HLA WITH MSGTPYE '"_MSGTYPE
 I $G(ACKCODE)'="" W "' AND ACKCODE '"_ACKCODE_"'"
 D ^%ZISC
 I '$D(ZTQUEUED) D
 .U 0
 .W !
 .K DIR
 .S DIR(0)="E"
 .D ^DIR
 Q
 ;
QUEEVN ;EP -
 S ZTRTN="FINDEVN^AGMPHLU1"
 S ZTDESC="MPI FIND EVENT/TYPE/ACK REPORT"
 S ZTSAVE("EVENT")="",ZTSAVE("MSGTYPE")="",ZTSAVE("ACKCODE")=""
 D ^%ZTLOAD
 I $D(ZTSK)[0 W !!?5,"Report Cancelled!"
 E  W !!?5,"Report task #: ",$G(ZTSK)
 D HOME^%ZIS
 Q
 ;
HDREVN ;EP -
 W @IOF
 W !,$$C^XBFUNC("MPI FIND EVENT/TYPE/ACK REPORT",IOM)
 W ?70,"PAGE ",PAGE
 W !,$$CJ^XLFSTR("DATE PRINTED: "_PRTDATE,IOM)
 W !,$$CJ^XLFSTR("PRINTED BY: "_$P($G(^VA(200,DUZ,0)),U),IOM)
 W !,DASH,!!
 S PAGE=PAGE+1
 Q
 ;
RPTBYDT ;EP - REPORT OF MSG TYPE AND EVENT BY DATE RANGE
 N MSGTYPE,EVENT,FROM,TO,MSGDATE,REC,MSGTYPCT,EVENTCNT,TOTMSG,TYPEEVNT,DASH,ESC
ASKFROM ;EP
 K DIR
 S DIR(0)="DO^::E"
 S DIR("A")="Enter from Date"
 S DIR("B")="T"
 D ^DIR
 Q:$D(DTOUT)!$D(DUOUT)!$D(DIROUT)!(Y="")
 S FROM=Y
ASKTO ;EP
 K DIR
 S DIR(0)="DO^::E"
 S DIR("A")="Enter to Date"
 S DIR("B")="T"
 D ^DIR
 G:$D(DTOUT)!$D(DUOUT)!$D(DIROUT)!(Y="") ASKFROM
 S TO=Y_".999999"
 I FROM>TO D  G ASKFROM
 .W !!,"FROM DATE CAN NOT BE GREATER THAN TO DATE!!" H 2
REPEAT ;EP -
 S TYPEEVNT="" F  S TYPEEVNT=$O(TYPEEVNT(TYPEEVNT)) Q:TYPEEVNT=""  S TYPEEVNT(TYPEEVNT)=0
 S ESC=0
 S TOTMSG=0
 S MSGDATE=FROM-.01
 F  S MSGDATE=$O(^HLA("B",MSGDATE)) Q:MSGDATE=""!(ESC)  D
 .Q:+MSGDATE>TO!(+MSGDATE<FROM)
 .S REC=""
 .F  S REC=$O(^HLA("B",MSGDATE,REC)) Q:REC=""  D
 ..S LINK=$P($G(^HLB(REC,0)),U,5)
 ..Q:LINK'="MPI"
 ..S MSGTYPE=$P($G(^HLA(REC,0)),U,3)
 ..S EVENT=$P($G(^HLA(REC,0)),U,4)
 ..S TYPEEVNT=EVENT_U_MSGTYPE
 ..S TYPEEVNT(TYPEEVNT)=$G(TYPEEVNT(TYPEEVNT))+1
 ..S TOTMSG=TOTMSG+1
 D NOW^%DTC S Y=% X ^DD("DD") S PRTDATE=Y
 S PAGE=1
 S ESC=0
 S $P(DASH,"-",81)=""
 D BYDTHDR
 S FIRST=""
 S TYPEEVNT=""
 F CNT=1:1 S TYPEEVNT=$O(TYPEEVNT(TYPEEVNT)) Q:TYPEEVNT=""!ESC  D
 .I CNT'=1,(FIRST'=$P(TYPEEVNT,U)) W !!
 .S FIRST=$P(TYPEEVNT,U)
 .W !,TYPEEVNT,?12,$J(TYPEEVNT(TYPEEVNT),10)
 .W ?25,$J($FN(TYPEEVNT(TYPEEVNT)/TOTMSG*100,",",2),10)
 W !,"---------------------------------------"
 W !!,"TOTAL MSGS: ",$J(TOTMSG,10)
 I '$D(ZTQUEUED) D  S ESC=X=U Q:ESC
 .U 0
 .W !
 .K DIR
 .S DIR(0)="E"
 .D ^DIR
 I '$D(ZTQUEUED) G REPEAT
 Q
 ;
BYDTHDR ;EP - RPTBYDT HEADER
 W @IOF
 W !,$$C^XBFUNC("MESSAGE REPORT BY DATE",IOM)
 W ?70,"PAGE ",PAGE
 W !,$$CJ^XLFSTR("DATE PRINTED: "_PRTDATE,IOM)
 W !,$$CJ^XLFSTR("PRINTED BY: "_$P($G(^VA(200,DUZ,0)),U),IOM)
 W !,$$CJ^XLFSTR("AT FACILITY: "_$P($G(^DIC(4,DUZ(2),0)),U),IOM)
 S Y=FROM X ^DD("DD") S EXFROM=Y
 S Y=TO X ^DD("DD") S EXTO=Y
 W !,$$CJ^XLFSTR("FOR MESSAGES FROM "_EXFROM_" TO "_EXTO,IOM)
 W !,DASH,!!
 W !!,"EVENT^TYPE",?16,"TOTAL",?25,"% OF TOTAL"
 W !,"---------------------------------------"
 S PAGE=PAGE+1
 Q
 ;
NUMICNS ;EP - NUMBER OF ICNS POPULATED
 N IEN,POP,NOTPOP,HASCHART,PATS
 S (POP,NOTPOP,HASCHART)=0
 S IEN=0
 F  S IEN=$O(^DPT(IEN)) Q:'IEN  D
 .Q:$D(^DPT(IEN,-9))
 .Q:'$O(^AUPNPAT(IEN,41,0))
 .S HASCHART=0
 .S DUZ2=0
 .F  S DUZ2=$O(^AUPNPAT(IEN,41,DUZ2)) Q:'DUZ2  D
 ..Q:$P($G(^AGFAC(DUZ2,0)),U,21)'="Y"
 ..S HASCHART=1
 .Q:'HASCHART  ;DON'T COUNT IF PT HAS NO CHARTS
 .I $P($G(^DPT(IEN,"MPI")),U)'="" S POP=POP+1
 .E  S NOTPOP=NOTPOP+1,PATS(IEN)=""
 W !!,"NUMBER OF ICNs POPULATED: ",POP
 W !,"NUMBER NOT POPULATED: ",NOTPOP
 I NOTPOP>0 D
 .W !!,"PATIENTS NOT POPULATED"
 .W !,"----------------------"
 .S IEN=""
 .F  S IEN=$O(PATS(IEN)) Q:'IEN  D
 ..W !,$P($G(^DPT(IEN,0)),U)
 I '$D(ZTQUEUED) D
 .W !
 .K DIR
 .S DIR(0)="E"
 .D ^DIR
 Q
 ;
FINDMFK ;EP - FIND MFK MSG WITH AN UNSUCCESFUL MFE
 N MSGIE,REC,COUNT,DASH
 S %ZIS="MQ"
 W !
 D ^%ZIS
 Q:POP
 I $D(IO("Q")) D QUEMFK Q
 U IO
PRTMFK ;EP - ENTRY POINT FOR TASKING
 S $P(DASH,"-",81)=""
 D NOW^%DTC S Y=% X ^DD("DD") S PRTDATE=Y
 S $P(DASH,"-",81)=""
 S PAGE=1
 S ESC=0
 D HDRMFK
 S COUNT=0
 S MSGIEN=0
 F  S MSGIEN=$O(^HLA(MSGIEN)) Q:'MSGIEN!ESC  D
 .Q:$P($G(^HLA(MSGIEN,0)),U,3)'="MFK"
 .S REC=0
 F  S MSGIEN=$O(^HLA(MSGIEN)) Q:'MSGIEN!ESC  D
 .Q:$P($G(^HLA(MSGIEN,0)),U,3)'="MFK"
 .S REC=0
 .F  S REC=$O(^HLA(MSGIEN,1,REC)) Q:'REC!ESC  D
 ..Q:$P($G(^HLA(MSGIEN,1,REC,0)),U)'="MFA"
 ..S RESULT=$P($G(^HLA(MSGIEN,1,REC,0)),U,5)
 ..Q:RESULT="S"
 ..S MSGID=$P($G(^HLA(MSGIEN,0)),U)
 ..S COUNT=COUNT+1
 ..I $Y>(IOSL-4),(IO=IO(0)),'$D(IO("S")) K DIR S DIR(0)="E" D:'$D(ZTQUEUED) ^DIR S ESC=$G(X)=U Q:ESC  D HDRMFK
 ..I $Y>(IOSL-4),$D(ZTQUEUED) D HDRMFK
 ..W !!,DASH
 ..W !,"HLA IEN: ",MSGIEN
 ..W !,"MSG ID: ",MSGID
 ..W !!,$G(^HLA(MSGIEN,1,REC-2,0))
 ..W !,$G(^HLA(MSGIEN,1,REC,0))
 W !!!,"COUNT OF UNSUCCESSFUL MFE: ",COUNT
 D ^%ZISC
 I '$D(ZTQUEUED) D
 .U 0
 .W !
 .K DIR
 .S DIR(0)="E"
 .D ^DIR
 Q
 ;
HDRMFK ;EP - HEADER
 W @IOF
 W !,$$C^XBFUNC("UNSUCCESSFUL MFE REPORT",IOM)
 W ?60,"PAGE ",PAGE
 S PAGE=PAGE+1
 W !,$$CJ^XLFSTR("DATE PRINTED: "_PRTDATE,IOM)
 W !,$$CJ^XLFSTR("PRINTED BY: "_$P($G(^VA(200,DUZ,0)),U),IOM)
 W !,DASH,!!
 Q
 ;
QUEMFK ; EP - QUE MFE ERROR REPORT
 S ZTRTN="PRTMFK^AGMPHLU1"
 S ZTDESC="HLO MFE ERROR MESSAGE REPORT"
 D ^%ZTLOAD
 I $D(ZTSK)[0 W !!?5,"Report Cancelled!"
 E  W !!?5,"Report task #: ",$G(ZTSK)
 D HOME^%ZIS
 Q
 ;
RESETICN ;EP - CLEAR INTEGRATION CONTROL NUMBER
 ;OIT PROGRAMMER ONLY OPTION
 ;THIS IS USED IF A SITE NEEDS TO BE RELOADED INTO THE MPI
 ;FOR SOME REASON. PARTICULARLY WHEN A BETA SITE IS RELOADED AND THEREFORE
 ;PATIET ARE ASSIGNED NEW EUID BY THE MPI
ONE ;EP - RESET JUST ONE PATIENT
 W !!,"USE THIS OPTION TO CLEAR THE INTEGRATION CONTROL NUMBER"
 W !,"THIS CAN BE USED WHEN A SITE NEEDS TO BE RELOADED INTO THE MPI"
 W !,"IF A SITE IS RELOADED THEN NEW EUIDs WILL BE ASSIGNED."
 W !!
 N DIR,DIC,DIE,DA,DR
 S DIR(0)="YO"
 S DIR("A")="RESET ALL PATIENTS"
 Q:$D(DTOUT)!($D(DUOUT))!(Y="")
 I Y="Y" D ALLRESET Q
 W !,"ENTER PATIENT TO RESET"
 D PTLK^AG
 Q:'$D(DFN)
 I '$D(^DPT(DFN,"MPI")) D  G ONE
 .W !!,"PATIENT HAS NO ICN"
 .K DIR
 .S DIR(0)="E"
 .D ^DIR
 S DA=DFN
 S DIE="^DPT("
 S DR="991.01///@;991.02///@"
 D ^DIE
 Q
ALLRESET ;EP - RESET ALL ICNs THAT ARE POPULATED
 ;OIT PROGRAMMER ONLY OPTION
 N DIR,DIC,DIE,DA,DR
 S DIE="^DPT("
 S DR="991.01///@;991.02///@"
 S DA=0
 F  S DA=$O(^DPT(DA)) Q:'DA  D
 .Q:'$D(^DPT(DA,"MPI"))
 .D ^DIE
 Q
 ;
CLEARALL ;EP - RESET ALL FOR RETESTING SESSION
 ;OIT PROGRAMMER ONLY OPTION
 ;D CLEAR
 ;D ALLRESET
 ;K ^DGCN(391.91)
 ;S ^DGCN(391.91,0)="TREATING FACILITY LIST^391.91PI^^"
 Q
 ;CLEAR HLO MESSAGE GLOBALS
CLEAR ;EP - CLEAR HLO MESSAGE GLOBALS
 ;OIT PROGRAMMER ONLY OPTION
 ;K ^HLA,^HLB,^HLC,^HLTMP
 ;S ^HLA(0)="HLO MESSAGE BODY^777DI^^"
 ;S ^HLB(0)="HLO MESSAGES^778O^^"
 Q
 ;
QUEVSENT ;EP - MSGS IN QUEUE VS TOTAL MSGS
 W @IOF
 N HLOG,PORT,MPILINK,REC,OUTCOUNT,TOTCOUNT,INCOUNT,MSGTYPE,EVENT,MPIIEN,ESC
 S ESC=0
 S HLOG=$O(^HLCS(870,"B","MPI",""))  ;MPI LOGICAL LINK
 S PORT=$$GET1^DIQ(870,HLOG_",",400.08,"E")  ;TCP/IP PORT (OPTIMIZED)
 S MPILINK="MPI:"_PORT
 S (TOTCOUNT,OUTCOUNT,INCOUNT)=0
 S TRANDATE=""
 F  S TRANDATE=$O(^HLB("QUEUE","IN",TRANDATE)) Q:'TRANDATE  D
 .S MSGTYPE=""
 .F  S MSGTYPE=$O(^HLB("QUEUE","IN",TRANDATE,"RPMS-MPI",MSGTYPE)) Q:MSGTYPE=""  D
 ..S EVENT=""
 ..F  S EVENT=$O(^HLB("QUEUE","IN",TRANDATE,"RPMS-MPI",MSGTYPE,EVENT)) Q:EVENT=""  D
 ...S MPIIEN=""
 ...F  S MPIIEN=$O(^HLB("QUEUE","IN",TRANDATE,"RPMS-MPI",MSGTYPE,EVENT,MPIIEN)) Q:MPIIEN=""  D
 ....S INCOUNT=INCOUNT+1
 S MPIIEN=""
 F  S MPIIEN=$O(^HLB("QUEUE","OUT",MPILINK,"MPI RPMS",MPIIEN)) Q:'MPIIEN  D
 .S OUTCOUNT=OUTCOUNT+1
 S MPIIEN=0
 F  S MPIIEN=$O(^HLB(MPIIEN)) Q:'MPIIEN  D
 .S LINK=$P($G(^HLB(MPIIEN,0)),U,5)
 .Q:LINK'="MPI"
 .S TOTCOUNT=TOTCOUNT+1
 W !!,"     MESSAGES IN THE IN QUEUE: ",$J($FN(INCOUNT,","),9)
 W !,"        MESSAGES IN OUT QUEUE: ",$J($FN(OUTCOUNT,","),9)
 W !,"TOTAL MESSAGES IN HLO GLOBALS: ",$J($FN(TOTCOUNT,","),9)
 I '$D(ZTQUEUED) D  Q:ESC
 .U 0
 .W !
 .K DIR
 .S DIR(0)="E"
 .D ^DIR
 .S ESC=X=U
 I '$D(ZTQUEUED) G QUEVSENT
 Q
]]></Routine>


<Class name="AGMPI.Adapters.HLOGlobalInbound">
<IncludeCode>EnsHL7</IncludeCode>
<Super>Ens.InboundAdapter</Super>
<TimeChanged>62046,52680.031739</TimeChanged>
<TimeCreated>61592,31859.341221</TimeCreated>

<Property name="ReceivingFacilityName">
<Description>
Log of changes
fje 04/11/09 general cleanup of comments and alerts
Name of the Receiving Facility to filter HL7 messages.</Description>
<Type>%String</Type>
<Parameter name="MAXLEN" value="200"/>
</Property>

<Property name="MaxNmbrMsgs">
<Description>
Maximum number of messages to retrieve/send per poll/task. </Description>
<Type>%Integer</Type>
</Property>

<Property name="NmbrMsgsSnt">
<Description>
The number of messages retrieved.</Description>
<Type>%Integer</Type>
</Property>

<Property name="AInfo">
<Description>
Information to send an alert from the business service
 if populated.</Description>
<Type>%String</Type>
</Property>

<Property name="Throttle">
<Description>
Time to hang before processing another message,
used to manage the throughput.</Description>
<Type>%Integer</Type>
</Property>

<Property name="SiteID">
<Description>
Site ID.  This is the STATION NUMBER</Description>
<Type>%String</Type>
</Property>

<Parameter name="SETTINGS">
<Type>%String</Type>
<Default>ReceivingFacilityName, MaxNmbrMsgs, Throttle, SiteID</Default>
</Parameter>

<Method name="OnTask">
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
  Set $ZT="Trap", tSC=$$$OK
  // Set variable to determine if trace events is active.
  // Setting this to one in RPMS will record trace events in Ensemble Portal.
  //Set tWriteTrace = +$G(^AGMPI("TRACE","MPI"))  trace all
  //Set tWriteTrace = +$G(^AGMPI("TRACE",14752))  station numbers
  Set tWriteTrace = +$G(^AGMPI("TRACE",..ReceivingFacilityName))
  // Initialize a start time variable.
  Set StrtTime = $P($H,",",2)	
  // Initialize the Alert Information property to the null string.
  Set ..AInfo=""
  // Initialize the number of messages sent during this connection.
  Set ..NmbrMsgsSnt=0
  // Initialize a variable(Flag) to use to quit when we reach the maximum
  // number of messages.
  Set tQuitAll=0
  // If we do not have a Receiving Facility Name defined an email alert 
  // is fired and no messages are processed.
  if (""=..ReceivingFacilityName) {
	If tWriteTrace $$$TRACE("There's no receiving facility name set")
    Set ..AInfo=..AInfo_" No Receiving Facility Name is set for the Inbound HLO Global Adapter, no messages are being processed." 
  	Do ..BusinessHost.SendAlert(##Class(Ens.AlertRequest).%New($LB(..BusinessHost.%ConfigName,"ERROR in Configuration", ..AInfo)))
	Quit
  }
   // HLB global properties  ^HLB(IEN,0) 
   // $P 2 - pointer to the Message body in the HLA global
   // $P 4 - message type (O for outbound, I for inbound)
   // $P 16 - processed Date/Time, null if message has not 
   // been previously processed
   // $p 20 - completion status, SU if successful
   // HLB global properties  ^HLB(IEN,4)
   // $p1 - Accept ACK Date/Time set from Outbound (RPMS) adapter
   // $p2 - Accept ACK Message ID
    	 
  // Set the field delimiter for the HLB data set.
  Set tFD = "^"
  // Set the initial ID value to zero.
  Set tid=0
  // Set the ^HLB QUEUE Node variables.
  // ^HLB("QUEUE","OUT",tNTYPE,tLINK,tid)
  Set tNTYPE="", tLLink=""
  // Lock the HLB Global.
  Lock +^HLB:900  // Try for 15 minutes.
  While '$T {
	 //We've failed to obtain a lock, send an alert out.
   	 Do ..BusinessHost.SendAlert(##Class(Ens.AlertRequest).%New($LB(..BusinessHost.%ConfigName,"There is an issue obtaining a lock on the HLB global in the HLOGlobalInbound Adapter: ")))
     Lock +^HLB:900  // Try again
  }
  If tWriteTrace $$$TRACE("We have locked the HLB node")
  // Loop Through the HLB Global using the ^HLB("QUEUE","OUT"... node.
  For {
	If tWriteTrace $$$TRACE("Begin FOR loop of ^HLB(QUEUE,OUT,X node")
	// If tQuitAll is valued we need to exit because we've 
	//  processed the maximum number of messages for this polling interval.
	if tQuitAll Quit    

	//Example of HLB global showing messages to be processed
	//^HLB("QUEUE","OUT","MPI:5200","MPI RPMS",TID)=""
	Set tNTYPE= $O(^HLB("QUEUE","OUT",tNTYPE))
	// If the tNDate variable is null we do not have any more nodes
	//  at this level to process.
	if tNTYPE="" Quit
	For {
	  If tWriteTrace $$$TRACE("Begin FOR loop of ^HLB(QUEUE,OUT,X,Y node")
	  // If tQuitAll is valued we need to exit because we've 
	  //  processed the maximum number of messages for this interval.
	  if tQuitAll Quit  	
	  Set tLLink= $O(^HLB("QUEUE","OUT",tNTYPE,tLLink))
	  // If the tLLink variable is null we do not have any more nodes
	  //  at this level to process.
	  if tLLink="" Quit
	  For {
		If tWriteTrace $$$TRACE("Begin FOR loop of ^HLB(QUEUE,OUT,X,Y,IEN node")
		// If tQuitAll is valued we need to exit because we've 
		//  processed the maximum number of messages for this interval.
		if tQuitAll Quit  
	    Set tid= $O(^HLB("QUEUE","OUT",tNTYPE,tLLink,tid))
		// If the tid variable is null we do not have any more
		//  nodes at this level to process.
		if +tid=0 Quit
		      
		// We've identified an index to use
		    If tWriteTrace $$$TRACE("IEN= "_tid)
            // Start a transaction.
            TStart
  	        // If there is no data in the Zero node of the global we 
  	        //  stop the transaction, unlock the global and go to 
  	        //  the begining of the DO loop.
	        If '$D(^HLB(tid,0),tZNdata) {
	          TCommit  
	          Lock -^HLB  
              If tWriteTrace $$$TRACE("We have unlocked the HLB node")
	          Continue
	        } 
	        If tWriteTrace $$$TRACE("Data is in the zero node of HLB")
	        // Set the message type variable.
	        Set tType=$p(tZNdata,tFD,4)
	        // If the type is not an outbound message we do not process
	        //  it, We're checking it here again to insure we have
	        //  an outbound message.
	        if '(tType="O") {
	          TCommit  
	          Lock -^HLB  
 			  If tWriteTrace $$$TRACE("We have unlocked the HLB node")
	          Continue  
	        }
	        If tWriteTrace $$$TRACE("The message is an outbound message")
	        Set tDtPc=$p(tZNdata,tFD,16) 
	        // If the Date Processed value is not null, then we have 
	        // already sent this message.
	        if '(tDtPc="") { 
	          TCommit  
	          Lock -^HLB
              If tWriteTrace $$$TRACE("We have unlocked the HLB node")
	          Continue 
	        }
	        If tWriteTrace $$$TRACE("The processed date is null-needs processing")
	        
	        // Set ID for the message to retrieve from the HLA global.
	        Set tID=$p(tZNdata,tFD,2)
	        // Concatenate the data from the first two nodes in the HLB
	        //  global to get the MSH segment. 
	        Set tMSH=$G(^HLB(tid,1))_$G(^HLB(tid,2))
	        //  Strip all alphabetic and numeric characters from the 
	        //  MSH segment and set the Field Separator to the first 
	        //  char and set the Subfield Separator to the second char.
 	        Set tFS=$E($ZStrip(tMSH,"*AN"),1)
 	        set tSFS=$E($ZStrip(tMSH,"*AN"),2)
 	        // Set the message type from the MSH segment.
 	        Set tMsgType=$P(tMSH,tFS,9)
            // If the third component of the message type field is blank
            //  we do not want the extra ^ character following the
            //  second subfield.
            if $P(tMsgType,tSFS,3)="" {
              Set $P(tMSH,tFS,9)= $P(tMsgType,tSFS,1,2)
            }
	        // Get the segment name.
	        Set tSegName=$S(""=tFS:"", 1:$P(tMSH,tFS))
	        // If there isn't a segment name we do not send this message.

	        if tSegName="" {
	          TCommit  
	          Lock -^HLB  
 			  If tWriteTrace $$$TRACE("We have unlocked the HLB node")
	          Continue 
	        }
	        If tWriteTrace $$$TRACE("We have a MSH Messge to process")
	        // If the receiving facility of the message doesn't match 
	        //  the ReceivingFacility in the parameter, we do not send 
	        //  this message.

	        if '(..ReceivingFacilityName=$P(tMSH,tFS,5)) {
	          TCommit  
	          Lock -^HLB  
              If tWriteTrace $$$TRACE("We have unlocked the HLB node")
	          Continue 
	        }
			If tWriteTrace $$$TRACE("The Receiving Facility matches message")
	// We've identified a message that should be sent to the receiving facility.
	// Build the HL7 message to send to the RPMS Service.
			If tWriteTrace $$$TRACE("We have identified a messagge to send:: ")
	        // Set the segment separator.
	        Set tSS=$c(13)
	        // Add the MSH segment to the text string.
	        Set tMsgTxt=tMSH_tSS
            // Set the segment index to zero.
            Set iSeg=0
            // Set the segment data to the null sting to begin with.
            Set tSegData=""

            // Lock the HLA global.
            Lock +^HLA:900  // Try for 15 minutes.
            While '$T {
	          //We've failed to obtain a lock, send an alert out.
   	          Do ..BusinessHost.SendAlert(##Class(Ens.AlertRequest).%New($LB(..BusinessHost.%ConfigName,"There is an issue obtaining a lock on the HLA global in the HLOGlobalInbound Adapter: ")))
              Lock +^HLA:900  // Try again
            }
 			If tWriteTrace $$$TRACE("We have Locked the HLA node")
	        // Loop through the message segments adding them to the 
	        //  Message string.
	        for {
	          // Get the next segment from the HLA global.
	          Set iSeg=$O(^HLA(tID,1,iSeg))
	          // If there are no more segments to load we exit out of 
	          //  the for loop.
	          Quit:+iSeg=0
	  		  // Set the tSegData variable.
	  		  Set tHldr=$D(^HLA(tID,1,iSeg,0),tSegData)
	  		  // If the length of data in the current node is is 
	  		  //  greater than zero we need to add this to the 
	  		  //  Message string.
	          if $L(tSegData)>0 {
			    // If the segment # is odd and has data,  check to see if there is 
			    //more data in the even node.  If even has data then
			    //add to the odd node befor processing
			    //      iSeg # 2 =1 if odd, zero if even
			    if (iSeg # 2){
				    Set tHldr=$D(^HLA(tID,1,iSeg+1,0),tSegData2)
				    if $L(tSegData2)>0 {
				         Set tSegData=tSegData_tSegData2
				         Set iSeg=iSeg+1
				    }
			    }
			    
			    //if '(iSeg # 2) {
		  		//  Set tMsgTxt=tMsgTxt_tSegData
				// Otherwise we add a segment separator also.
				//} else {
	      	  Set tMsgTxt=tMsgTxt_tSegData_tSS
				//}
	  		  }
		    }	

		    // Unlock the global in case there's another operaton that
			//  neds to write to it.
			Lock -^HLA  
 			If tWriteTrace $$$TRACE("We have unlocked the HLA node")
			
    		// Create the HL7 message document to send to the business 
    		//  process that will route the message.
            Set hl7obj=##class(EnsLib.HL7.Message).ImportFromString(tMsgTxt)
            
	        // Check to see that the hl7obj is an object.
			Set tSC= $ISOBJECT(hl7obj)
			// If it's not send an a message to the ENS.Alert Process.
			If 'tSC {
		      Set tSC=%objlasterror
	  	      Set ..AInfo=" Failed to create an HL7 message with the information retrieved from the HLA global, IEN= "_tID
	  		  Set ..AInfo=..AInfo_" ERROR:= "_##class(%SYSTEM.Status).GetErrorText(tSC)
   			  Do ..BusinessHost.SendAlert(##Class(Ens.AlertRequest).%New($LB(..BusinessHost.%ConfigName,"There was an issue creating a valid HL7 message in the HLOGlobalInbound Adapter: ", ..AInfo)))
	  		  Set ..AInfo=""
	  		  tCommit
	  	  	  Lock -^HLB
 			  If tWriteTrace $$$TRACE("We have unlocked the HLB node")
	  		  Continue
			}
			If tWriteTrace $$$TRACE("Message is built and we're sending it to the RPMS Service.")

			
			// Send the message to the Business Host.  
			set tSC=..BusinessHost.ProcessInput(hl7obj)
		    Set ..NmbrMsgsSnt=..NmbrMsgsSnt+1
			If tWriteTrace $$$TRACE("We returned from the RPMS Service with tSC= "_tSC_":")

			// If we get here we sent a message to the production and
			//  we need to update the 16th field within the HLB global.
	
			Set X=$HOROLOG,X=($ZDATETIME(X,8,1,9)-17000000)
			Set Y=$PIECE($HOROLOG,",",2),Z=$ZTIME(Y,2)
			Set Z=$P(Z,":",1)_$P(Z,":",2)
			Set $p(^HLB(tid,0),tFD,16)=(X_"."_Z) 
			
			// We've sent/Processed the message, we need to remove
			//  the QUEUE node and decrement the counter by one
			k ^HLB("QUEUE","OUT",tNTYPE,tLLink,tid)
	        s:+$G(^HLC("QUEUECOUNT","OUT",tNTYPE,tLLink)) ^HLC("QUEUECOUNT","OUT",tNTYPE,tLLink)=^HLC("QUEUECOUNT","OUT",tNTYPE,tLLink)-1
			// Complete the transaction and unlock the global.
			TCommit
			Lock -^HLB
 			If tWriteTrace $$$TRACE("We have unlocked the HLB node")
			If tWriteTrace $$$TRACE("Message was sent, QUEUE node deleted, and count decremented")

			
	        // If the number of messages sent equals the Maximum Number 
	        //  of message to send per interval, we set the tQuitAll
	        //  flag.
			If ( ..NmbrMsgsSnt =..MaxNmbrMsgs)  {
			  Set tQuitAll=1
			  Quit
			}
			// Set the Current Time variable
			Set CrrntTime = $P($H,",",2)
			// Set the processing time, if the start time is greater than the
			//  current time (we passed midnight) and will always set the 
			//  processing time to a value greater than the call interval. 
			If StrtTime > CrrntTime {
			  Set PrcssngTime = StrtTime - CrrntTime
			} else {
			  Set PrcssngTime = CrrntTime - StrtTime
			}
			// If the processing time is greater than the Call Interval
			//  return control to the Service that called the adapter.
			if (PrcssngTime > ..CallInterval) {
			  Set tQuitAll=1
			  Quit
			}
			// Pause the processing of messages.
			HANG (..Throttle/1000)
  		} // Closing the third For loop.
	} // Closing the second For loop.
  } // Closing the first For loop.
  Lock -^HLB
  If tWriteTrace $$$TRACE("We have unlocked the HLB node")
  // Exiting the Inbound Adapter.
  Quit tSC
  
Trap
	// We erred out, set the error information and roll back the last transaction.
	Set $ZT="",tSC=$$$EnsSystemError
	If tWriteTrace $$$TRACE("An error was captured and is being sent")

    Do ..BusinessHost.SendAlert(##Class(Ens.AlertRequest).%New($LB(..BusinessHost.%ConfigName,"There was an error in the HLOGlobalInbound Adapter: ", tSC)))
	TRollback  Lock -^HLB,-^HLA Quit tSC
]]></Implementation>
</Method>

<UDLText name="T">
<Content><![CDATA[
//Closing the Method

]]></Content>
</UDLText>
</Class>


<Class name="AGMPI.Adapters.HLOGlobalOutbound">
<IncludeCode>EnsHL7</IncludeCode>
<IncludeGenerator>EnsHL7</IncludeGenerator>
<Super>Ens.OutboundAdapter</Super>
<TimeChanged>62426,49489.158143</TimeChanged>
<TimeCreated>61592,32226.677662</TimeCreated>

<Property name="SiteID">
<Description>
Facility number.</Description>
<Type>%String</Type>
</Property>

<Property name="LLink">
<Description>
Logical Link between the two systems (i.e. Den-RPMS)</Description>
<Type>%String</Type>
</Property>

<Parameter name="SETTINGS">
<Type>%String</Type>
<Default>SiteID, LLink</Default>
</Parameter>

<Method name="FileMessage">
<FormalSpec>InboundMsg:EnsLib.HL7.Message</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
	Set $ZT="Trap", tSC=$$$OK
	// Set a variable that we'll use to determine if we write 
	//  trace events.
	//Set tWriteTrace = +$G(^AGMPI("TRACE","MPI"))  ;trace all
	//Set tWriteTrace = +$G(^AGMPI("TRACE",14752))  station numbers
	Set tWriteTrace = +$G(^AGMPI("TRACE",..SiteID))
	If tWriteTrace $$$TRACE("Begin processing a message")
       
	// Set the ID to null.
	Set tIEN=""
	// Set a variable to use as our loop exit test.
	Set tLI = 0
	// Set the field delimiter for the HLB data set.
	Set tFD = "^"
	Set U="^"  ;IHS/SD/TPF 10/30/2009
	If tWriteTrace $$$TRACE("Attempting to lock ^HLB")
	
	// Lock the HLB and HLA Globals.
	Lock +^HLB:900  // Try for 15 minutes.
	//If 1
	While '$T {
		//We've failed to obtain a lock, send an alert out.
		Do ..BusinessHost.SendAlert(##Class(Ens.AlertRequest).%New($LB(..BusinessHost.%ConfigName,"There is an issue obtaining a lock on the HLB global in the HLOGlobalOutbound Adapter: ")))
		Lock +^HLB:900  // Try again
	}
    
	If tWriteTrace $$$TRACE("Attempting to lock ^HLA")
	Lock +^HLA:900  // Try for 15 minutes.
	//if 1
	While '$T {
		//We've failed to obtain a lock, send an alert out.
		Do ..BusinessHost.SendAlert(##Class(Ens.AlertRequest).%New($LB(..BusinessHost.%ConfigName,"There is an issue obtaining a lock on the HLA global in the HLOGlobalOutbound Adapter: ")))
		Lock +^HLA:900  // Try again
	}

	Do {
		If tWriteTrace $$$TRACE("We got to the transaction start")
    
		// Start a transaction.
		//tStart
		If tWriteTrace $$$TRACE("Started the Transaction")
		set ttMsgID=InboundMsg.%Id()
		If tWriteTrace $$$TRACE("ttMsgID= "_ttMsgID)
		// Get the segment count.
		Set tSegCount=InboundMsg.SegCountGet()
		If tWriteTrace $$$TRACE("tSegCount= "_tSegCount)
		// Temp variable to hold the message separators.
		Set tSeparators=InboundMsg.Separators
		// Temp variable to hold the segment field separator.
		Set tFS= InboundMsg.FS
		If tWriteTrace $$$TRACE("Message Field Separators tFS= "_tFS)
		// Temp variable to hold the sub-component separator.
		Set tCS= InboundMsg.CS
		If tWriteTrace $$$TRACE("Sub Component Separators tCS= "_tCS)
		// Get the MSH segment, it's always the first segment of
		//  a HL7 message.
		Set tMSH=InboundMsg.GetValueAt(1)
		If tWriteTrace $$$TRACE("First Segment of message tMSH= "_tMSH)
		// Get the message type.  The second piece of the MSHP:9 field.
		Set tMType=$P($P(tMSH,tFS,9),tCS,2)
		If tWriteTrace $$$TRACE("Message type tMType= "_tMType)
		// Get the message class.  The first piece of the MSHP:9 field.
		Set tMClass=$P($P(tMSH,tFS,9),tCS,1)
		If tWriteTrace $$$TRACE("Message class tMClass= "_tMClass)
		// Get the sending facility from the MSH segment.
		Set tSndFclty=$P(tMSH,tFS,5)
		If tWriteTrace $$$TRACE("Sending Facility tSndFclty= "_tSndFclty)
 
		Set tMSA=InboundMsg.GetValueAt(2)  //GET MSA SEGMENT
		If tWriteTrace $$$TRACE("tMSA segment= "_tMSA)
     
 
		// If the message class is an ACK it is a response to
		//  a sent message we sent and will update the HLB global
		//  using the IEN from the 'B' CrossReference sub Control ID .
		if (tMClass="ACK") {  //IHS/SD/TPF 11/9/2009 NEED TO CREATE ACK MESSAGES TO PROCESS
			If tWriteTrace $$$TRACE("ACK message, updating the HLB Global")
			// Get the Control ID from the MSH:10 field.
			//Set tCntrlID = $P(tMSH,tFS,10)  ;TPF 3/30/2010  CHANGED FOR NEW MPI FRAMEWORK
			Set tCntrlID = $P(tMSA,tFS,3)
			;NEED FOLLOWING FOR MFN SINCE IT HAS NO MSA
			IF 'tCntrlID S tCntrlID=$P(tMSH,tFS,10)
		
			If tWriteTrace $$$TRACE("The message control ID is= "_tCntrlID)
			// If there isn't a control ID in the message we need to
			//  send an alert and exit the processing of the message.
			if 'tCntrlID {
				Do ..BusinessHost.SendAlert(##Class(Ens.AlertRequest).%New($LB(..BusinessHost.%ConfigName,"Failure: The HLOGlobalOutound adapter failed to Process Message "_ttMsgID_" (an ACK) because it did not contain a Message Control ID:::")))
				Quit
			}
			// Get the tIEN from the 'B' Crossreference.
			Set tIEN= $O(^HLB("B",tCntrlID,""))
			If tIEN="" Set tIEN=$O(^HLB("B"," "_tCntrlID,""))
			If tWriteTrace $$$TRACE("The tIEN for the response is= "_tIEN)
			if 'tIEN {
				Do ..BusinessHost.SendAlert(##Class(Ens.AlertRequest).%New($LB(..BusinessHost.%ConfigName,"Failure: The HLOGlobalOutound adapter failed to Process Message "_ttMsgID_" (an ACK) because the 'B' reference node did not exist for Message Control ID "_tCntrlID_":::")))
				Quit
			}
			// Get the MSA segment.
			Set tMSA= InboundMsg.GetValueAt(2)
			If tWriteTrace $$$TRACE("MSA Segment = "_tMSA)
			// if the Acknowledgment Code is AA, accepted
	   
	  
			if $P(tMSA,tFS,2)="AA"
			{
				// Set the Accept Acknowledgment field to 1
				Set $P(^HLB(tIEN,0),tFD,17)=1   //.17 ACCEPT ACK'D  -AA RECEIVED
				// Set the acknowledge date in the $p1 of the 4 node
				//  Get the current Date/Time.
				Set tCDT=$H 
				Set X=($ZDATETIME(tCDT,8,1,9)-17000000)
				Set Y=$P($H,",",2)
				Set Z=$ZTIME(Y,2)
				Set Z=$P(Z,":",1)_$P(Z,":",2)
				Set pDate=(X_"."_Z)
				Set $P(^HLB(tIEN,4),tFD,1)=pDate
				If tWriteTrace $$$TRACE("Set the Acknowledgement Date/Time in the HLB 4 node "_pDate)
				// Set the acknowledge Message ID in the $p2 of the 4 node
				Set tCID=$P(tMSA,tFS,3)
				Set $P(^HLB(tIEN,4),tFD,2)=tCID   //4.02 ACCEPT ACK MESSAGE ID
				set ttMSA=$p(tMSA,tFS,1)_tFS_$p(tMSA,tFS,2)_tFS_$p(tMSA,tFS,3)
				Set $P(^HLB(tIEN,4),tFD,3)=ttMSA   //4.03 ACCEPT ACK MSA SEGMENT
				If tWriteTrace $$$TRACE("ACCEPT ACK MSA SEGMENT ttMSA = "_ttMSA)
				If tWriteTrace $$$TRACE("Set the Acknowledgement Message ID in the HLB 4 node "_tCID)
			} elseif $p(tMSA,tFS,2)'="CA" {
				//In this case a CE (COMMIT ERROR), CR (COMMIT REJECT), AE (ACCEPT ERROR), or AR (ACCEPT REJECT) was received
				If tWriteTrace $$$TRACE("Setting the Acknowledgment Code to a value other than SU")
				// Set the completion status to AE.
				Set $p(^HLB(tIEN,0),tFD,20)= "AE"  //.2 COMPLETION STATUS
   	    
				// Set the error information and Error cross ref
				Set $p(^HLB(tIEN,0),tFD,21)= $P(tMSA,tFS,3)  //.21 ERROR TEXT
				If ($p(^HLB(tIEN,0),tFD,5)'="")&($p(^HLB(tIEN,0),tFD,16)'="") {
					Set ^HLB("ERRORS","AE",$p(^HLB(tIEN,0),tFD,5),$p(^HLB(tIEN,0),tFD,16),tIEN)=""
				}
		       
				Do ..BusinessHost.SendAlert(##Class(Ens.AlertRequest).%New($LB(..BusinessHost.%ConfigName,"Alert: The HLOGlobalOutound adapter received message "_ttMsgID_" (an ACK message) that did not contain an 'AA' or 'CA' Acknowledgment Code: The MessageControl ID is "_tCntrlID_":::")))
			}
	  
			If tWriteTrace $$$TRACE("The HLB global has been updated with the ACK information for IEN= "_tIEN)  

			// If the message class is an inbound message other than an ACK.
			//} else { //IHS/SD/TPF 11/9/2009 NEED TO PROCESS ALL MESSAGES RECEIVED
  	
		} 
  	
		//END FIRST IF
		//elseif (tMClass="ACK")!(tMClass="MFN")
		if (tMClass="ACK")!(tMClass="MFN") {  //IHS/SD/TPF 11/9/2009 NEED TO PROCESS ACKS AND MFN MESSAGES RECEIVED

			If tWriteTrace $$$TRACE("Updating HLA and HLB Globals in else")
			set tHLBIEN=..GetNewHLBIEN()
			If tWriteTrace $$$TRACE("The HLB IEN we're using is "_tHLBIEN)
			if 'tHLBIEN {
				do ..BusinessHost.SendAlert(##Class(Ens.AlertRequest).%New($LB(..BusinessHost.%ConfigName,"Failure: The HLOGlobalOutbound adapter was unable to obtain an unused IEN for ^HLB")))
				quit
			}
			
			set tHLAIEN=..GetNewHLAIEN()
			If tWriteTrace $$$TRACE("The HLA IEN we're using is "_tHLAIEN)
			if 'tHLAIEN {
				do ..BusinessHost.SendAlert(##Class(Ens.AlertRequest).%New($LB(..BusinessHost.%ConfigName,"Failure: The HLOGlobalOutbound adapter was unable to obtain an unused IEN for ^HLA")))
				quit
			}
	  	
			If tWriteTrace $$$TRACE("Adding information to the HLB Global")
 
			// save the information into the HLB global.
			// Set the ZeroNode Data information.
			// Set the Control ID (SitID parameter_Space_HLB IEN).
			Set tCntrlID=..SiteID_" "_tHLBIEN
			// Set the tHLBIEN zero node to the the null string.
			Set ^HLB(tHLBIEN,0)=""
			Set $P(^HLB(0),U,3)=tHLBIEN  ;IHS/SD/TPF 10/28/2009 KEEP FM INTEGRITY OF HLO FILE
			Set $P(^HLB(0),U,4)=$P(^HLB(0),U,4)+1  ;IHS/SD/TPF 10/28/2009 KEEP FM INTEGRITY OF HLO FILE
			Set $P(^HLA(0),U,3)=tHLAIEN  ;IHS/SD/TPF 10/28/2009 KEEP FM INTEGRITY OF HLO FILE
			Set $P(^HLA(0),U,4)=$P(^HLA(0),U,4)+1  ;IHS/SD/TPF 10/28/2009 KEEP FM INTEGRITY OF HLO FILE
			// Set the MsgID.
			Set $p(^HLB(tHLBIEN,0),tFD,1)=tCntrlID
			// Set the HLA pointer.
			If tWriteTrace $$$TRACE("Set the ^HLA pointer "_tHLAIEN)
			Set $p(^HLB(tHLBIEN,0),tFD,2)=tHLAIEN
			// Set the Msg Direction to Inbound.
			Set $p(^HLB(tHLBIEN,0),tFD,4)="I"
			// Set the Logical Link (Sending App.)over which the 
			//  message is being transmitted.
			Set $p(^HLB(tHLBIEN,0),tFD,5)=$p(tMSH,tFS,3)
			// Set the Queue (Sending Facility).
			Set $p(^HLB(tHLBIEN,0),tFD,6)=tSndFclty
			
			// If a Commit Ack, we don't need to process it any further.
			if $p(tMSA,tFS,2)="CA" {
				// Mark ACK successfully processed.
				set $p(^HLB(tHLBIEN,0),tFD,20)="SU"
				// Set the purge Date/Time to 7 days in the future.
				//  Get the current Date/Time.
				Set tCDT=$H 
				//  Add seven days to the Date.
				Set $P(tCDT,",",1)=$P(tCDT,",",1)+7
				Set X=($ZDATETIME(tCDT,8,1,9)-17000000)
				Set Y=$P($H,",",2)
				Set Z=$ZTIME(Y,2)
				Set Z=$P(Z,":",1)_$P(Z,":",2)
				Set pDate=(X_"."_Z)
				Set $P(^HLB(tHLBIEN,0),tFD,9)=pDate
			}
  	
			// Set the Date/Time we received the message.
			Set X=$HOROLOG,X=($ZDATETIME(X,8,1,9)-17000000)
			Set Y=$PIECE($HOROLOG,",",2),Z=$ZTIME(Y,2)
			Set Z=$P(Z,":",1)_$P(Z,":",2)
			Set cDate=(X_"."_Z)
			Set $p(^HLB(tHLBIEN,0),tFD,16)=cDate 


			// Set the HLB first and second nodes to the MSH segment
			Set ^HLB(tHLBIEN,1)=$P(tMSH,tFS,1,6)
			Set ^HLB(tHLBIEN,2)=tFS_$P(tMSH,tFS,7,17)  //TPF 4/1/2010 ABOVE LINE WAS DROPPING AL^AL ACKNOWLEDGEMENTS 
	  
			// Set the HLA zero node information
			Set $P(^HLA(tHLAIEN,0),tFD,1)=cDate
			Set $P(^HLA(tHLAIEN,0),tFD,2)=0
			Set $P(^HLA(tHLAIEN,0),tFD,3)=tMClass
			Set $P(^HLA(tHLAIEN,0),tFD,4)=tMType
			Set $P(^HLA(tHLAIEN,0),tFD,5)=$P(tMSH,tFS,12)
			Set $P(^HLA(tHLAIEN,0),tFD,20)= tSeparators
			//Set B cross reference
			Set ^HLA("B",cDate,tHLAIEN)=""
  	  
  	  
			// Set a node sub-index to use in setting the HLA node
			Set tNI=0
			If tWriteTrace $$$TRACE("Writing information to the HLA Global") 	  
			For tSI=2:1:tSegCount {
				// Increment the node sub-index
				Set tNI=tNI+1
				//  tHLAIEN is the Index, while i+i-1 is where we're saving the segment,
				//  because we're only storing the segments in the odd number indices
				//  unless the segment character count is above 240 then we split the
				//  segment saving the first half in the odd number index and the 
				//  second in the next even number index.
				Set tSegData=InboundMsg.GetValueAt(tSI) 
      
				Set ^HLA(tHLAIEN,1,tNI+tNI-1,0)=tSegData
				if '(tSI = tSegCount) {
					Set ^HLA(tHLAIEN,1,tNI+tNI,0)=""
				}
			}	 
		} // End the for loop, adding the HLA information
		// Add the 'B', 'C' and 'SEARCH' nodes and their information.
		s ^HLB("B",tCntrlID,tHLBIEN)=""
		// s ^HLB("C",tHLAIEN,tHLBIEN)="" for Outgoing messages only
		s ^HLB("C",tHLAIEN,tHLBIEN)=""  ;IHS/SD/TPF 10/30/2009 WHY? IT DOESN'T LIST THESE IN FM IF ITS NOT SET.
		s ^HLB("AC",$p(tMSH,tFS,4)_$p(tMSH,tFS,3)_tCntrlID,tHLBIEN)=""
	  
		If tWriteTrace $$$TRACE("cDate = "_cDate)
		If tWriteTrace $$$TRACE("..LLink = "_..LLink)
		If tWriteTrace $$$TRACE("tMClass = "_tMClass)
		If tWriteTrace $$$TRACE("tMType = "_tMType)
		If tWriteTrace $$$TRACE("tHLBIEN = "_tHLBIEN)
		If tWriteTrace $$$TRACE("tHLAIEN = "_tHLAIEN)
	  
		// If this is a commit ACK, we don't need to process it further,
		// so add this message to the queue only if it's not a CA.
		if $p(tMSA,tFS,2)'="CA" {
			S ^HLB("QUEUE","IN",cDate,..LLink,tMClass,tMType,tHLBIEN)=""
		}
		// End the else portion of the ACK check //IHS/SD/TPF 11/09/2009 TOOK OUT ELSE TO PROCESS ACKS AND MFN AS MESSAGES
	} While (0)
	
	//tCommit
	Lock -^HLA, -^HLB 
	If tWriteTrace $$$TRACE("Updated the HLA and HLB Globals, leaving the HLOGlobalOutbound adapter")
	Quit $$$OK 

Trap
	// We erred out, set the error information and roll back the last transaction.
	If tWriteTrace $$$TRACE("Entered the error trap portion")
	Set $ZT="",tSC=$$$EnsSystemError
 	Do ..BusinessHost.SendAlert(##Class(Ens.AlertRequest).%New($LB(..BusinessHost.%ConfigName,"Failure: The HLOGlobalOutound adapter failed: Error= "_tSC_"::")))
	TRollback  Lock -^HLB,-^HLA Quit $$$OK
]]></Implementation>
</Method>

<UDLText name="T">
<Content><![CDATA[
//End the method

]]></Content>
</UDLText>

<Method name="GetNewHLBIEN">
<Description>
Gets the next available IEN for the ^HLB global using the same logic
as NEWIEN^HLOF778A. Messages in this adapter are always inbound, TCP.</Description>
<ClassMethod>1</ClassMethod>
<ReturnType>%Integer</ReturnType>
<Implementation><![CDATA[
	set tStartIEN=$g(^HLC("FILE778","IN","TCP"))  // Protect against an infinite loop.

	do {
		set tIEN=$i(^HLC("FILE778","IN","TCP"))
		set tMaxIEN=100000000000

		while (tIEN>tMaxIEN) {
			lock +^HLC("FILE778","IN","TCP"):200
			if $t,$g(^HLC("FILE778","IN","TCP"))>tMaxIEN {
				set ^HLC("FILE778","IN","TCP")=1,tIEN=1
			}
			lock -^HLC("FILE778","IN","TCP")
		}
		
		set tIEN2=tIEN+200000000000
	} while ($d(^HLB(tIEN2)) && (tIEN'=tStartIEN))
	
	if (tIEN=tStartIEN) { quit "" }

	quit (tIEN2)
]]></Implementation>
</Method>

<Method name="GetNewHLAIEN">
<Description>
Gets the next available IEN for the ^HLA global using the same logic
as NEWIEN^HLOF777. Messages in this adapter are always inbound, TCP.</Description>
<ClassMethod>1</ClassMethod>
<ReturnType>%Integer</ReturnType>
<Implementation><![CDATA[
	set tStartIEN=$g(^HLC("FILE777","IN","TCP"))  // Protect against an infinite loop.

	do {
		set tIEN=$i(^HLC("FILE777","IN","TCP"))
		set tMaxIEN=100000000000

		while (tIEN>tMaxIEN) {
			lock +^HLC("FILE777","IN","TCP"):200
			if $t,$g(^HLC("FILE777","IN","TCP"))>tMaxIEN {
				set ^HLC("FILE777","IN","TCP")=1,tIEN=1
			}
			lock -^HLC("FILE777","IN","TCP")
		}
		
		set tIEN2=tIEN+100000000000
	} while ($d(^HLA(tIEN2)) && (tIEN'=tStartIEN))

	if (tIEN=tStartIEN) { quit "" }

	quit (tIEN2)
]]></Implementation>
</Method>
</Class>


<Class name="AGMPI.AlertEmailAddress">
<Super>%Persistent,%Populate,%XML.Adaptor</Super>
<TimeChanged>62388,57265.344408</TimeChanged>
<TimeCreated>61593,36022.526551</TimeCreated>

<Property name="Name">
<Type>%String</Type>
<Required>1</Required>
</Property>

<Property name="EmailAddress">
<Type>%String</Type>
<Required>1</Required>
</Property>

<Property name="EmailType">
<Type>%String</Type>
<Required>1</Required>
<Parameter name="VALUELIST" value=",To,Cc"/>
</Property>

<Storage name="Default">
<Type>%Library.CacheStorage</Type>
<DataLocation>^AGMPI.AlertEmailAddressD</DataLocation>
<DefaultData>AlertEmailAddressDefaultData</DefaultData>
<IdLocation>^AGMPI.AlertEmailAddressD</IdLocation>
<IndexLocation>^AGMPI.AlertEmailAddressI</IndexLocation>
<StreamLocation>^AGMPI.AlertEmailAddressS</StreamLocation>
<Data name="AlertEmailAddressDefaultData">
<Structure>listnode</Structure>
<Subscript/>
<Value name="1">
<Value>%%CLASSNAME</Value>
</Value>
<Value name="2">
<Value>Name</Value>
</Value>
<Value name="3">
<Value>EmailAddress</Value>
</Value>
<Value name="4">
<Value>EmailType</Value>
</Value>
</Data>
</Storage>
</Class>


<Class name="AGMPI.Alerts.AlertLog">
<Super>%Persistent</Super>
<TimeChanged>62388,57265.632704</TimeChanged>
<TimeCreated>61593,35202.293276</TimeCreated>

<Property name="AlertText">
<Type>%String</Type>
<Parameter name="MAXLEN"/>
</Property>

<Property name="AlertDateTime">
<Type>%TimeStamp</Type>
</Property>

<Storage name="Default">
<Type>%Library.CacheStorage</Type>
<DataLocation>^AGMPI.Alerts.AlertLogD</DataLocation>
<DefaultData>AlertLogDefaultData</DefaultData>
<IdLocation>^AGMPI.Alerts.AlertLogD</IdLocation>
<IndexLocation>^AGMPI.Alerts.AlertLogI</IndexLocation>
<StreamLocation>^AGMPI.Alerts.AlertLogS</StreamLocation>
<Data name="AlertLogDefaultData">
<Structure>listnode</Structure>
<Subscript/>
<Value name="1">
<Value>%%CLASSNAME</Value>
</Value>
<Value name="2">
<Value>AlertText</Value>
</Value>
<Value name="3">
<Value>AlertDateTime</Value>
</Value>
</Data>
</Storage>
</Class>


<Document name="AGMPI.MPI.HL7">
<Category name="AGMPI.MPI" base="2.4">

<MessageType name='ACK' structure='ACK'/>
<MessageType name='MFN_M05' structure='MFN_M05' returntype='base:MFK_M05'/>

<MessageStructure name='ACK' definition='base:MSH~base:MSA~[~base:ERR~]~[~base:QAK~]~[~base:PID~]~[~base:ZPD~]'/>
<MessageStructure name='MFN_M05' definition='base:MSH~base:MFI~[~{~base:MFE~}~]'/>

<SegmentStructure name='MFE' description='Master File Entry Segment'>
    <SegmentSubStructure piece='2' description='Record-Level Event Code' length='3' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='3' description='MFN Control ID' length='20' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='4' description='Effective Date/Time' length='26' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='5' description='Primary Key Value - MFE' length='200' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='6' description='Primary Key Value Type' length='3' required='O' ifrepeating='1'/>
</SegmentStructure>
<SegmentStructure name='MFI' description='Master File Identification'>
    <SegmentSubStructure piece='2' description='Master File Identfier' length='250' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='3' description='Master File Application Identifier' length='180' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='4' description='File-Level event Code' length='3' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='5' description='Entered Date/Time' length='26' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='6' description='Response Level Code' length='2' required='O' ifrepeating='1'/>
</SegmentStructure>
<SegmentStructure name='QAK' description='Patient Exact Match Query'>
    <SegmentSubStructure piece='2' description='EUID' length='15' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='3' description='Query Response Status' length='1' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='4' description='Event Type' length='3' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='5' description='Query Description' length='40' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='6' description='Hit Count Total' length='10' required='O' ifrepeating='1'/>
</SegmentStructure>
<SegmentStructure name='ZPD' description='IHS Patient Information'>
    <SegmentSubStructure piece='2' description='Tribe of Membership Code' length='3' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='3' description='Eligibility Status' length='1' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='4' description='Classification/Beneficiary Code' length='2' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='5' description='Indian Blood Quantum' length='40' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='6' description='Chart Numbers' length='40' required='O' ifrepeating='1'/>
</SegmentStructure>

</Category>
</Document>

<Document name="AGMPI.MPIAlertRouting.RUL"><routingRule host="AGMPI" name="MPIAlertRouting" effectiveBeginDateTime="" effectiveEndDateTime="" context="EnsLib.HL7.MsgRouter.RoutingEngine" doAll="false" source="Ens.Alert" msgClass="Ens.AlertRequest" docName="" docCategory="" docType="">
  <description></description>
  <reportGroup></reportGroup>
  <reportName></reportName>
  <shortDescription></shortDescription>
  <rule source="" msgClass="" docName="" docCategory="" docType="">
    <action type="send" target="EMailAlert" transform=""></action>
  </rule>
</routingRule>
</Document>

<Document name="AGMPI.MPIMessageRouting.RUL"><routingRule host="AGMPI" name="MPIMessageRouting" effectiveBeginDateTime="" effectiveEndDateTime="" context="EnsLib.HL7.MsgRouter.RoutingEngine" doAll="true" source="MPIInbound" msgClass="EnsLib.HL7.Message" docName="" docCategory="" docType="">
  <description></description>
  <reportGroup></reportGroup>
  <reportName></reportName>
  <shortDescription></shortDescription>
  <rule source="MPIInbound" msgClass="" docName="" docCategory="AGMPI.MPI" docType="MFN_M05,ACK">
    <action type="send" target="RPMSOutBound" transform=""></action>
  </rule>
</routingRule>
</Document>

<Class name="AGMPI.Operations.MPI">
<ProcedureBlock>1</ProcedureBlock>
<Super>EnsLib.HL7.Operation.TCPOperation</Super>
<TimeChanged>62069,42121.26409</TimeChanged>
<TimeCreated>61592,33257.239869</TimeCreated>

<Parameter name="ADAPTER">
<Default>EnsLib.HL7.Adapter.TCPOutboundAdapter</Default>
</Parameter>

<Parameter name="INVOCATION">
<Default>Queue</Default>
</Parameter>

<Method name="OnMessage">
<FormalSpec>pRequest:EnsLib.HL7.Message,*pResponse:EnsLib.HL7.Message</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
        // Disable journaling for this process to save journal space.
        do DISABLE^%NOJRN

        quit ##super(pRequest,.pResponse)
]]></Implementation>
</Method>
</Class>


<Class name="AGMPI.Operations.RPMS">
<Description>
The outbound operation that communicates with the RPMS system</Description>
<ProcedureBlock>1</ProcedureBlock>
<Super>EnsLib.HL7.Operation.Standard</Super>
<TimeChanged>62069,42348.539179</TimeChanged>
<TimeCreated>61592,33675.577319</TimeCreated>

<Parameter name="ADAPTER">
<Default>AGMPI.Adapters.HLOGlobalOutbound</Default>
</Parameter>

<Parameter name="INVOCATION">
<Default>Queue</Default>
</Parameter>

<Method name="OnMessage">
<FormalSpec>pRequest:EnsLib.HL7.Message,*pResponse:EnsLib.HL7.Message</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
   do DISABLE^%NOJRN
   set tSC=..Adapter.FileMessage(pRequest)
   quit tSC
]]></Implementation>
</Method>
</Class>


<Class name="AGMPI.PatientRegistration">
<ProcedureBlock>1</ProcedureBlock>
<Super>Ens.Production</Super>
<TimeChanged>62444,67033.65878</TimeChanged>
<TimeCreated>61579,45861.079022</TimeCreated>

<XData name="ProductionDefinition">
<Data><![CDATA[
<Production Name="AGMPI.PatientRegistration" TestingEnabled="true" LogGeneralTraceEvents="true">
  <Description>This production transports messages between RPMS Patient Registration and the central IHS MPI </Description>
  <ActorPoolSize>2</ActorPoolSize>
  <Setting Target="Production" Name="ShutdownTimeout">120</Setting>
  <Setting Target="Production" Name="UpdateTimeout">10</Setting>
  <Item Name="Ens.Alert" Category="MPI" ClassName="AGMPI.Process.AlertProcess" PoolSize="1" Enabled="true" Foreground="false" InactivityTimeout="0" Comment="This handles Alert routing logic." LogTraceEvents="true" Schedule="">
    <Setting Target="Host" Name="ReplyCodeActions"></Setting>
    <Setting Target="Host" Name="RetryInterval">5</Setting>
    <Setting Target="Host" Name="AlertRetryGracePeriod">0</Setting>
    <Setting Target="Host" Name="FailureTimeout">15</Setting>
    <Setting Target="Host" Name="AlertOnError">0</Setting>
  </Item>
  <Item Name="BadMessage" Category="MPI" ClassName="EnsLib.HL7.Operation.FileOperation" PoolSize="1" Enabled="true" Foreground="false" InactivityTimeout="0" Comment="Bad messages are sent to this operation." LogTraceEvents="true" Schedule="">
    <Setting Target="Host" Name="Filename">MPIBadMessageFile</Setting>
    <Setting Target="Host" Name="AutoBatchParentSegs">0</Setting>
    <Setting Target="Host" Name="Separators"><![CDATA[^~|\&]]]]><![CDATA[></Setting>
    <Setting Target="Host" Name="SearchTableClass"></Setting>
    <Setting Target="Host" Name="DefCharEncoding">Latin1</Setting>
    <Setting Target="Host" Name="ReplyCodeActions"></Setting>
    <Setting Target="Host" Name="RetryInterval">5</Setting>
    <Setting Target="Host" Name="AlertRetryGracePeriod">5</Setting>
    <Setting Target="Host" Name="FailureTimeout">-1</Setting>
    <Setting Target="Host" Name="AlertOnError">1</Setting>
    <Setting Target="Host" Name="ArchiveIO">0</Setting>
    <Setting Target="Host" Name="Framing">AsciiLF</Setting>
    <Setting Target="Adapter" Name="FilePath">c:\HLOTEST\BADMSG</Setting>
    <Setting Target="Adapter" Name="Overwrite">0</Setting>
    <Setting Target="Adapter" Name="Charset">Default</Setting>
    <Setting Target="Adapter" Name="OpenTimeout">5</Setting>
  </Item>
  <Item Name="RPMSInBound" Category="MPI" ClassName="AGMPI.Services.RPMS" PoolSize="1" Enabled="true" Foreground="false" InactivityTimeout="0" Comment="Retrieve messages from the HLA and HLB globals" LogTraceEvents="true" Schedule="">
    <Setting Target="Host" Name="TargetConfigNames">AGMPI.RPMSMessageRouting</Setting>
    <Setting Target="Host" Name="SearchTableClass">EnsLib.HL7.SearchTable</Setting>
    <Setting Target="Host" Name="LocalFacilityApplication">ISC:EnsembleHL7</Setting>
    <Setting Target="Host" Name="Framing">Flexible</Setting>
    <Setting Target="Host" Name="AckMode">Never</Setting>
    <Setting Target="Host" Name="UseAckCommitCodes">0</Setting>
    <Setting Target="Host" Name="IgnoreInboundAck">0</Setting>
    <Setting Target="Host" Name="AddNackERR">0</Setting>
    <Setting Target="Host" Name="NackErrorCode">ContentE</Setting>
    <Setting Target="Host" Name="BatchHandling">1Session</Setting>
    <Setting Target="Host" Name="MessageSchemaCategory">AGMPI.RPMS</Setting>
    <Setting Target="Host" Name="DefCharEncoding">Latin1</Setting>
    <Setting Target="Host" Name="AlertGracePeriod">5</Setting>
    <Setting Target="Host" Name="AlertOnError">1</Setting>
    <Setting Target="Host" Name="ArchiveIO">0</Setting>
    <Setting Target="Adapter" Name="ReceivingFacilityName">MPI</Setting>
    <Setting Target="Adapter" Name="MaxNmbrMsgs">60</Setting>
    <Setting Target="Adapter" Name="Throttle">475</Setting>
    <Setting Target="Adapter" Name="SiteID"></Setting>
    <Setting Target="Adapter" Name="CallInterval">5</Setting>
  </Item>
  <Item Name="AGMPI.RPMSMessageRouting" Category="MPI" ClassName="EnsLib.HL7.MsgRouter.RoutingEngine" PoolSize="1" Enabled="true" Foreground="false" InactivityTimeout="0" Comment="Routes messages received from the rpms system" LogTraceEvents="true" Schedule="">
    <Setting Target="Host" Name="LocalFacilityApplication">ISC:EnsembleHL7</Setting>
    <Setting Target="Host" Name="AckType">Application</Setting>
    <Setting Target="Host" Name="NackCode">Error</Setting>
    <Setting Target="Host" Name="AddNackERR">0</Setting>
    <Setting Target="Host" Name="Validation">dm-z</Setting>
    <Setting Target="Host" Name="BusinessRuleName">AGMPI.RPMSMessageRouting</Setting>
    <Setting Target="Host" Name="AlertOnBadMessage">1</Setting>
    <Setting Target="Host" Name="BadMessageHandler">BadMessage</Setting>
    <Setting Target="Host" Name="ResponseFrom">MPIOutBound</Setting>
    <Setting Target="Host" Name="ResponseTargetConfigNames">RPMSOutBound</Setting>
    <Setting Target="Host" Name="ResponseTimeout">-1</Setting>
    <Setting Target="Host" Name="ForceSyncSend">0</Setting>
    <Setting Target="Host" Name="ReplyCodeActions"></Setting>
    <Setting Target="Host" Name="RetryInterval">5</Setting>
    <Setting Target="Host" Name="AlertRetryGracePeriod">0</Setting>
    <Setting Target="Host" Name="FailureTimeout">15</Setting>
    <Setting Target="Host" Name="AlertOnError">1</Setting>
  </Item>
  <Item Name="MPIInbound" Category="MPI" ClassName="EnsLib.HL7.Service.TCPService" PoolSize="1" Enabled="true" Foreground="false" InactivityTimeout="0" Comment="Accept Messages from the MPI system via TCP" LogTraceEvents="true" Schedule="">
    <Setting Target="Host" Name="TargetConfigNames">AGMPI.MPIMessageRouting</Setting>
    <Setting Target="Host" Name="SearchTableClass">EnsLib.HL7.SearchTable</Setting>
    <Setting Target="Host" Name="LocalFacilityApplication">ISC:EnsembleHL7</Setting>
    <Setting Target="Host" Name="Framing">MLLP</Setting>
    <Setting Target="Host" Name="AckMode">Msh</Setting>
    <Setting Target="Host" Name="UseAckCommitCodes">0</Setting>
    <Setting Target="Host" Name="IgnoreInboundAck">0</Setting>
    <Setting Target="Host" Name="AddNackERR">1</Setting>
    <Setting Target="Host" Name="NackErrorCode">ContentE</Setting>
    <Setting Target="Host" Name="BatchHandling">1Session</Setting>
    <Setting Target="Host" Name="MessageSchemaCategory">AGMPI.MPI</Setting>
    <Setting Target="Host" Name="DefCharEncoding">Latin1</Setting>
    <Setting Target="Host" Name="AlertGracePeriod">30</Setting>
    <Setting Target="Host" Name="AlertOnError">1</Setting>
    <Setting Target="Host" Name="ArchiveIO">0</Setting>
    <Setting Target="Adapter" Name="JobPerConnection">0</Setting>
    <Setting Target="Adapter" Name="AllowedIPAddresses"></Setting>
    <Setting Target="Adapter" Name="QSize">0</Setting>
    <Setting Target="Adapter" Name="CallInterval">5</Setting>
    <Setting Target="Adapter" Name="Port">5201</Setting>
    <Setting Target="Adapter" Name="StayConnected">60</Setting>
    <Setting Target="Adapter" Name="ReadTimeout">30</Setting>
    <Setting Target="Adapter" Name="SSLConfig"></Setting>
  </Item>
  <Item Name="AGMPI.MPIMessageRouting" Category="MPI" ClassName="EnsLib.HL7.MsgRouter.RoutingEngine" PoolSize="1" Enabled="true" Foreground="false" InactivityTimeout="0" Comment="Routes messages received from the MPI system" LogTraceEvents="true" Schedule="">
    <Setting Target="Host" Name="LocalFacilityApplication">ISC:EnsembleHL7</Setting>
    <Setting Target="Host" Name="AckType"></Setting>
    <Setting Target="Host" Name="NackCode"></Setting>
    <Setting Target="Host" Name="AddNackERR">0</Setting>
    <Setting Target="Host" Name="Validation">dm-z</Setting>
    <Setting Target="Host" Name="BusinessRuleName">AGMPI.MPIMessageRouting</Setting>
    <Setting Target="Host" Name="AlertOnBadMessage">1</Setting>
    <Setting Target="Host" Name="BadMessageHandler">BadMessage</Setting>
    <Setting Target="Host" Name="ResponseFrom"></Setting>
    <Setting Target="Host" Name="ResponseTargetConfigNames"></Setting>
    <Setting Target="Host" Name="ResponseTimeout">-1</Setting>
    <Setting Target="Host" Name="ForceSyncSend">0</Setting>
    <Setting Target="Host" Name="ReplyCodeActions"></Setting>
    <Setting Target="Host" Name="RetryInterval">5</Setting>
    <Setting Target="Host" Name="AlertRetryGracePeriod">0</Setting>
    <Setting Target="Host" Name="FailureTimeout">15</Setting>
    <Setting Target="Host" Name="AlertOnError">1</Setting>
  </Item>
  <Item Name="RPMSOutBound" Category="MPI" ClassName="AGMPI.Operations.RPMS" PoolSize="1" Enabled="true" Foreground="false" InactivityTimeout="0" Comment="Place the HL7 message into HLA and HLB globals" LogTraceEvents="true" Schedule="">
    <Setting Target="Host" Name="Separators"><![CDATA[^~|\&]]]]><![CDATA[></Setting>
    <Setting Target="Host" Name="SearchTableClass"></Setting>
    <Setting Target="Host" Name="DefCharEncoding">Latin1</Setting>
    <Setting Target="Host" Name="ReplyCodeActions"></Setting>
    <Setting Target="Host" Name="RetryInterval">5</Setting>
    <Setting Target="Host" Name="AlertRetryGracePeriod">5</Setting>
    <Setting Target="Host" Name="FailureTimeout">-1</Setting>
    <Setting Target="Host" Name="AlertOnError">1</Setting>
    <Setting Target="Host" Name="ArchiveIO">0</Setting>
    <Setting Target="Host" Name="Framing">MLLP</Setting>
    <Setting Target="Adapter" Name="SiteID"></Setting>
    <Setting Target="Adapter" Name="LLink">RPMS-MPI</Setting>
  </Item>
  <Item Name="MPIOutBound" Category="MPI" ClassName="EnsLib.HL7.Operation.TCPOperation" PoolSize="1" Enabled="true" Foreground="false" InactivityTimeout="0" Comment="Send the HL7 messages to the MPI system via TCP/IP" LogTraceEvents="true" Schedule="">
    <Setting Target="Host" Name="ReplyCodeActions"></Setting>
    <Setting Target="Host" Name="NoFailWhileDisconnected">0</Setting>
    <Setting Target="Host" Name="Separators"><![CDATA[^~|\&]]]]><![CDATA[></Setting>
    <Setting Target="Host" Name="SearchTableClass"></Setting>
    <Setting Target="Host" Name="DefCharEncoding">Latin1</Setting>
    <Setting Target="Host" Name="RetryInterval">5</Setting>
    <Setting Target="Host" Name="AlertRetryGracePeriod">30</Setting>
    <Setting Target="Host" Name="FailureTimeout">-1</Setting>
    <Setting Target="Host" Name="AlertOnError">1</Setting>
    <Setting Target="Host" Name="ArchiveIO">0</Setting>
    <Setting Target="Host" Name="Framing">MLLP</Setting>
    <Setting Target="Adapter" Name="IPAddress"></Setting>
    <Setting Target="Adapter" Name="Port">5200</Setting>
    <Setting Target="Adapter" Name="ResponseTimeout">30</Setting>
    <Setting Target="Adapter" Name="StayConnected">60</Setting>
    <Setting Target="Adapter" Name="ConnectTimeout">30</Setting>
    <Setting Target="Adapter" Name="ReconnectRetry">5</Setting>
    <Setting Target="Adapter" Name="GetReply">1</Setting>
    <Setting Target="Adapter" Name="ReadTimeout">30</Setting>
    <Setting Target="Adapter" Name="SSLConfig"></Setting>
  </Item>
  <Item Name="EmailAlert" Category="MPI" ClassName="EnsLib.EMail.AlertOperation" PoolSize="1" Enabled="false" Foreground="false" InactivityTimeout="0" Comment="Send alerts via email" LogTraceEvents="true" Schedule="">
    <Setting Target="Host" Name="ReplyCodeActions"></Setting>
    <Setting Target="Host" Name="RetryInterval">5</Setting>
    <Setting Target="Host" Name="AlertRetryGracePeriod">5</Setting>
    <Setting Target="Host" Name="FailureTimeout">25</Setting>
    <Setting Target="Host" Name="AlertOnError">0</Setting>
    <Setting Target="Host" Name="ArchiveIO">0</Setting>
    <Setting Target="Adapter" Name="SMTPServer"></Setting>
    <Setting Target="Adapter" Name="SMTPPort">25</Setting>
    <Setting Target="Adapter" Name="Credentials"></Setting>
    <Setting Target="Adapter" Name="Recipient">ryan.hulslander@vangent.com</Setting>
    <Setting Target="Adapter" Name="Cc"></Setting>
    <Setting Target="Adapter" Name="From">badaboom@badabing.com</Setting>
  </Item>
</Production>
]]></Data>
</XData>
</Class>


<Class name="AGMPI.Process.AlertProcess">
<ClassType>persistent</ClassType>
<Super>Ens.BusinessProcessBPL</Super>
<TimeChanged>62384,38614.783852</TimeChanged>
<TimeCreated>61592,35734.428636</TimeCreated>

<XData name="BPL">
<Description>
BPL Definition</Description>
<XMLNamespace>http://www.intersystems.com/bpl</XMLNamespace>
<Data><![CDATA[
<process language='objectscript' request='Ens.Request' response='Ens.Response' height='2000' width='2000' >
<context>
<property name='LastAlertDateTime' type='%TimeStamp' />
<property name='LastAlertHorolog' type='%String' />
<property name='TimeDiff' type='%Integer' />
<property name='AlertInterval' type='%Integer' initialexpression='900' />
<property name='AlertHorolog' type='%String' initialexpression='$H' />
<property name='AlertLog' type='AGMPI.Alerts.AlertLog' />
</context>
<sequence xend='550' yend='1200' >
<scope name='scope3' xpos='550' ypos='200' xend='550' yend='1100' >
<sql name='Get Last Alert Date/Time' xpos='550' ypos='300' >
<![CDATA[SELECT TOP 1 AlertDateTime INTO :context.LastAlertDateTime 
FROM AGMPI_Alerts.AlertLog
ORDER BY AlertDateTime DESC]]]]><![CDATA[>
</sql>
<code name='Calculate Time Diff' xpos='550' ypos='400' >
<![CDATA[	// If there is no previous alert, set the time difference greater than the interval.
	do DISABLE^%NOJRN
	if context.LastAlertDateTime="" {
		set context.TimeDiff=context.AlertInterval+1
	}
	// Otherwise, calculate the time difference in seconds.
	else {
		set context.LastAlertHorolog=$zdth(context.LastAlertDateTime,5,,,,,,,,"")
		set context.TimeDiff=(context.AlertHorolog-context.LastAlertHorolog*86400)+$p(context.AlertHorolog,",",2)-$p(context.LastAlertHorolog,",",2)
	}
	]]]]><![CDATA[>
</code>
<if name='Time Diff &gt; Alert Int' condition='context.TimeDiff&gt;context.AlertInterval' xpos='550' ypos='500' xend='550' yend='850' >
<true>
<code name='Log the Alert' xpos='685' ypos='650' >
<![CDATA[	// Log the alert
    do DISABLE^%NOJRN
	set context.AlertLog=##class(AGMPI.Alerts.AlertLog).%New()
	set context.AlertLog.AlertText=request.AlertText
	set context.AlertLog.AlertDateTime=$zdt(context.AlertHorolog,3,1)
	do context.AlertLog.%Save()
	]]]]><![CDATA[>
</code>
<call name='E-mail the Alert' target='EmailAlert' async='1' xpos='685' ypos='750' >
<request type='Ens.AlertRequest' >
<assign property='callrequest' value='request' action='set' />
</request>
</call>
</true>
</if>
<faulthandlers>
<catchall xpos='550' ypos='950' xend='550' yend='300' >
<trace name='Error in Alert Process' value='"Error in Alert Process: "_$System.Status.GetErrorCodes(..%Context.%LastError)_" : "_$System.Status.GetOneStatusText(..%Context.%LastError)' xpos='550' ypos='200' />
</catchall>
</faulthandlers>
</scope>
</sequence>
</process>
]]></Data>
</XData>

<Storage name="Default">
<Type>%Library.CacheStorage</Type>
</Storage>
</Class>


<Class name="AGMPI.Process.AlertProcess.Context">
<ClassType>persistent</ClassType>
<CompileAfter>AGMPI.Process.AlertProcess</CompileAfter>
<IncludeCode/>
<ProcedureBlock>1</ProcedureBlock>
<Super>Ens.BP.Context</Super>
<TimeChanged>62388,57269.194926</TimeChanged>
<TimeCreated>61592,52279.721373</TimeCreated>

<Property name="AlertHorolog">
<Type>%String</Type>
<InitialExpression>$H</InitialExpression>
</Property>

<Property name="AlertInterval">
<Type>%Integer</Type>
<InitialExpression>900</InitialExpression>
</Property>

<Property name="AlertLog">
<Type>AGMPI.Alerts.AlertLog</Type>
</Property>

<Property name="LastAlertDateTime">
<Type>%TimeStamp</Type>
</Property>

<Property name="LastAlertHorolog">
<Type>%String</Type>
</Property>

<Property name="TimeDiff">
<Type>%Integer</Type>
</Property>

<Storage name="Default">
<Type>%Library.CacheStorage</Type>
<DefaultData>ContextDefaultData1</DefaultData>
<Data name="ContextDefaultData1">
<Structure>listnode</Structure>
<Subscript>"Context"</Subscript>
<Value name="1">
<Value>AlertHorolog</Value>
</Value>
<Value name="2">
<Value>AlertInterval</Value>
</Value>
<Value name="3">
<Value>AlertLog</Value>
</Value>
<Value name="4">
<Value>LastAlertDateTime</Value>
</Value>
<Value name="5">
<Value>LastAlertHorolog</Value>
</Value>
<Value name="6">
<Value>TimeDiff</Value>
</Value>
</Data>
</Storage>
</Class>


<Class name="AGMPI.Process.AlertProcess.Thread1">
<ClassType>persistent</ClassType>
<CompileAfter>AGMPI.Process.AlertProcess</CompileAfter>
<IncludeCode/>
<ProcedureBlock>1</ProcedureBlock>
<Super>Ens.BP.Thread</Super>
<TimeChanged>62388,57270.404856</TimeChanged>
<TimeCreated>62388,57268.977522</TimeCreated>

<Method name="S1">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 #; Establish a state for the Scope beginning
 Set ..%NextState="S2"
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S1") Goto Exit
]]></Implementation>
</Method>

<Method name="S2">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 #; Establish fault handler
 $$$Push("S3",..%HandlerStack)
 &SQL(
SELECT TOP 1 AlertDateTime INTO :context.LastAlertDateTime 
FROM AGMPI_Alerts.AlertLog
ORDER BY AlertDateTime DESC
 )
 Do {
	// If there is no previous alert, set the time difference greater than the interval.
	do DISABLE^%NOJRN
	if context.LastAlertDateTime="" {
		set context.TimeDiff=context.AlertInterval+1
	}
	// Otherwise, calculate the time difference in seconds.
	else {
		set context.LastAlertHorolog=$zdth(context.LastAlertDateTime,5,,,,,,,,"")
		set context.TimeDiff=(context.AlertHorolog-context.LastAlertHorolog*86400)+$p(context.AlertHorolog,",",2)-$p(context.LastAlertHorolog,",",2)
	}
	
 } while (0)
 If $$$ISERR(status) Quit
 If (context.TimeDiff>context.AlertInterval) {
 Set ..%NextState="S5"
 } else {
 Set ..%NextState="S4"
 }
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S2") Goto Exit
]]></Implementation>
</Method>

<Method name="S3">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 If (0) {
 Set ..%NextState="S7"
 } else {
 Set ..%NextState="S8"
 }
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S3") Goto Exit
]]></Implementation>
</Method>

<Method name="S4">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 Set ..%NextState="S6"
 #; Remove this scopes fault handler
 $$$Pop(..%HandlerStack)
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S4") Goto Exit
]]></Implementation>
</Method>

<Method name="S5">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 Do {
	// Log the alert
    do DISABLE^%NOJRN
	set context.AlertLog=##class(AGMPI.Alerts.AlertLog).%New()
	set context.AlertLog.AlertText=request.AlertText
	set context.AlertLog.AlertDateTime=$zdt(context.AlertHorolog,3,1)
	do context.AlertLog.%Save()
	
 } while (0)
 If $$$ISERR(status) Quit
 #; --- Begin Call E-mail the Alert ---
 #; --- Begin Request ---
 Set callrequest=##class(Ens.AlertRequest).%New()
 If '$IsObject(callrequest) Set status=%objlasterror Quit
 Set callrequest=request
 Set status=..MakeAsyncCall("","EmailAlert",callrequest,"E-mail the Alert",0,0,"E-mail the Alert")
 If $$$ISERR(status) Quit
 Kill callrequest
 #; --- End Request ---
 #; --- End Call E-mail the Alert ---
 Set ..%NextState="S4"
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S5") Goto Exit
]]></Implementation>
</Method>

<Method name="S6">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 Do process.ClearAllPendingResponses()
 Set ..%NextState="Stop"
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S6") Goto Exit
]]></Implementation>
</Method>

<Method name="S7">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 Set ..%NextState="S6"
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S7") Goto Exit
]]></Implementation>
</Method>

<Method name="S8">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 Do ##class(Ens.Util.Trace).WriteTrace("user","AGMPI.Process.AlertProcess","S8","Error in Alert Process: "_$System.Status.GetErrorCodes(..%Context.%LastError)_" : "_$System.Status.GetOneStatusText(..%Context.%LastError))
 Set ..%NextState="S7"
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S8") Goto Exit
]]></Implementation>
</Method>

<Storage name="Default">
<Type>%Library.CacheStorage</Type>
</Storage>
</Class>


<Class name="AGMPI.Process.AlertProcessContext">
<ClassType>persistent</ClassType>
<CompileAfter>AGMPI.Process.AlertProcess</CompileAfter>
<ProcedureBlock>1</ProcedureBlock>
<Super>Ens.BP.Context</Super>
<TimeChanged>61824,37523.370219</TimeChanged>
<TimeCreated>61592,51469.207187</TimeCreated>

<Property name="AlertHorolog">
<Type>%String</Type>
<InitialExpression>$H</InitialExpression>
</Property>

<Property name="AlertInterval">
<Type>%Integer</Type>
<InitialExpression>900</InitialExpression>
</Property>

<Property name="AlertLog">
</Property>

<Property name="LastAlertDateTime">
<Type>%TimeStamp</Type>
</Property>

<Property name="LastAlertHorolog">
<Type>%String</Type>
</Property>

<Property name="TimeDiff">
<Type>%Integer</Type>
</Property>

<Storage name="Default">
<Type>%Library.CacheStorage</Type>
<DefaultData>AlertProcessContextDefaultData</DefaultData>
<Data name="AlertProcessContextDefaultData">
<Structure>listnode</Structure>
<Subscript>"AlertProcessContext"</Subscript>
<Value name="1">
<Value>AlertHorolog</Value>
</Value>
<Value name="2">
<Value>AlertInterval</Value>
</Value>
<Value name="3">
<Value>AlertLog</Value>
</Value>
<Value name="4">
<Value>LastAlertDateTime</Value>
</Value>
<Value name="5">
<Value>LastAlertHorolog</Value>
</Value>
<Value name="6">
<Value>TimeDiff</Value>
</Value>
</Data>
</Storage>
</Class>


<Class name="AGMPI.Process.AlertProcessThread1">
<ClassType>persistent</ClassType>
<CompileAfter>AGMPI.Process.AlertProcess</CompileAfter>
<ProcedureBlock>1</ProcedureBlock>
<Super>Ens.BP.Thread</Super>
<TimeChanged>61824,37755.797124</TimeChanged>
<TimeCreated>61592,52260.890995</TimeCreated>

<Method name="S1">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 #; Establish a state for the Scope beginning
 Set ..%NextState="S2"
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S1") Goto Exit
]]></Implementation>
</Method>

<Method name="S2">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 #; Establish fault handler
 $$$Push("S3",..%HandlerStack)
 &SQL(
SELECT TOP 1 AlertDateTime INTO :context.LastAlertDateTime 
FROM AGMPI_Alerts.AlertLog
ORDER BY AlertDateTime
 )
 Do {
	// If there is no previous alert, set the time difference greater than the interval.
	if context.LastAlertDateTime="" {
		set context.TimeDiff=context.AlertInterval+1
	}
	// Otherwise, calculate the time difference in seconds.
	else {
		set context.LastAlertHorolog=$zdth(context.LastAlertDateTime,5,,,,,,,,"")
		set context.TimeDiff=(context.AlertHorolog-context.LastAlertHorolog*86400)+$p(context.AlertHorolog,",",2)-$p(context.LastAlertHorolog,",",2)
	}
	
 } while (0)
 If $$$ISERR(status) Quit
 If (context.TimeDiff>context.AlertInterval) {
 Set ..%NextState="S5"
 } else {
 Set ..%NextState="S4"
 }
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S2") Goto Exit
]]></Implementation>
</Method>

<Method name="S3">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 If (0) {
 Set ..%NextState="S7"
 } else {
 Set ..%NextState="S8"
 }
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S3") Goto Exit
]]></Implementation>
</Method>

<Method name="S4">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 Set ..%NextState="S6"
 #; Remove this scopes fault handler
 $$$Pop(..%HandlerStack)
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S4") Goto Exit
]]></Implementation>
</Method>

<Method name="S5">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 Do {
	// Log the alert
	set context.AlertLog=##class(AGMPI.Alerts.AlertLog).%New()
	set context.AlertLog.AlertText=request.AlertText
	set context.AlertLog.AlertDateTime=$zdt(context.AlertHorolog,3,1)
	do context.AlertLog.%Save()
	
 } while (0)
 If $$$ISERR(status) Quit
 #; --- Begin Call E-mail the Alert ---
 #; --- Begin Request ---
 Set callrequest=##class(Ens.AlertRequest).%New()
 If '$IsObject(callrequest) Set status=%objlasterror Quit
 Set callrequest=request
 Set status=..MakeAsyncCall("","EmailAlert",callrequest,"E-mail the Alert",0,0,"E-mail the Alert")
 If $$$ISERR(status) Quit
 Kill callrequest
 #; --- End Request ---
 #; --- End Call E-mail the Alert ---
 Set ..%NextState="S4"
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S5") Goto Exit
]]></Implementation>
</Method>

<Method name="S6">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 Do process.ClearAllPendingResponses()
 Set ..%NextState="Stop"
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S6") Goto Exit
]]></Implementation>
</Method>

<Method name="S7">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 Set ..%NextState="S6"
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S7") Goto Exit
]]></Implementation>
</Method>

<Method name="S8">
<FormalSpec>process:Ens.BusinessProcess,context:Ens.BP.Context,synctimedout:%Boolean,syncresponses:%ArrayOfObjects(ELEMENTTYPE="%Library.Persistent"),request:%Library.Persistent,response:%Library.Persistent</FormalSpec>
<Language>cache</Language>
<PublicList>process,context</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
 Set $ZT="Trap",status=$$$OK do {
 Do ##class(Ens.Util.Trace).WriteTrace("user","AGMPI.Processes.AlertProcess","S8","Error in Alert Process: "_$System.Status.GetErrorCodes(..%Context.%LastError)_" : "_$System.Status.GetOneStatusText(..%Context.%LastError))
 Set ..%NextState="S7"
 } while (0)
Exit Quit ..ManageState(status)
Trap Set $ZT="",status=..ManageStatus(status,"S8") Goto Exit
]]></Implementation>
</Method>

<Storage name="Default">
<Type>%Library.CacheStorage</Type>
</Storage>
</Class>


<Document name="AGMPI.RPMS.HL7">
<Category name="AGMPI.RPMS" base="2.4">

<MessageType name='ACK' structure='ACK'/>
<MessageType name='ADT_A01' structure='ADT_A01' returntype='base:ACK_A01'/>
<MessageType name='ADT_A03' structure='ADT_A03' returntype='base:ACK_A03'/>
<MessageType name='ADT_A08' structure='ADT_A08' returntype='base:ACK_A08'/>
<MessageType name='ADT_A28' structure='ADT_A28' returntype='base:ACK_A28'/>
<MessageType name='ADT_A31' structure='ADT_A31' returntype='base:ACK_A31'/>
<MessageType name='ADT_A40' structure='ADT_A40' returntype='base:ACK_A40'/>
<MessageType name='VQQ_Q02' structure='VQQ_Q02' returntype='base:ACK_VQQ'/>

<MessageStructure name='ACK' definition='base:MSH~base:MSA~[~base:ERR~]'/>
<MessageStructure name='ADT_A01' definition='base:MSH~base:EVN~base:PID~[~base:PD1~]~[~base:PV1~]~[~base:ZPD~]~[~base:NK1~]'/>
<MessageStructure name='ADT_A03' definition='base:MSH~base:EVN~base:PID~[~base:PD1~]~[~base:PV1~]~[~base:ZPD~]~[~base:NK1~]'/>
<MessageStructure name='ADT_A08' definition='base:MSH~base:EVN~base:PID~[~base:PD1~]~[~base:PV1~]~[~base:OBX~]~[~{~base:ZPD~}~]~[~{~base:NK1~}~]'/>
<MessageStructure name='ADT_A28' definition='base:MSH~base:EVN~base:PID~[~base:PD1~]~[~{~base:ZPD~}~]~[~{~base:NK1~}~]'/>
<MessageStructure name='ADT_A31' definition='base:MSH~base:EVN~base:PID~[~base:PD1~]~[~{~base:ZPD~}~]~[~{~base:NK1~}~]'/>
<MessageStructure name='ADT_A40' definition='base:MSH~base:EVN~base:PID~[~base:PD1~]~[~{~base:MRG~}~]'/>
<MessageStructure name='MFK_M05' definition='base:MSH~base:MFI~[~{~base:MFE~base:MFA~}~]'/>
<MessageStructure name='VQQ_Q02' definition='base:MSH~base:EVN~base:PID~[~base:PD1~]~[~{~base:ZPD~}~]~[~{~base:NK1~}~]'/>

<SegmentStructure name='MFA'>
    <SegmentSubStructure piece='2' description='Record-Level Event Code' length='3' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='3' description='MFN Control ID' length='20' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='4' description='Event Completion DAte/Time' length='26' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='5' description='MFN Record Level Error Return' length='200' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='6' description='Primary Key Value Type - MFA' length='3' required='O' ifrepeating='1'/>
</SegmentStructure>
<SegmentStructure name='MFE' description='Master File Entry Segment'>
    <SegmentSubStructure piece='2' description='Record-Level Event Code' length='3' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='3' description='MFN Control ID' length='20' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='4' description='Effective Date/Time' length='26' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='5' description='Primary Key Value - MFE' length='200' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='6' description='Primary Key Value Type' length='3' required='O' ifrepeating='1'/>
</SegmentStructure>
<SegmentStructure name='MFI' description='Master File Idenitification Segment'>
    <SegmentSubStructure piece='2' description='Master File Identifier' length='250' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='3' description='MF Application Identifier' length='180' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='4' description='Type of Update' length='3' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='5' description='Entered Date/Time' length='26' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='6' description='Effective Date/Time' length='26' required='O' ifrepeating='1'/>
</SegmentStructure>
<SegmentStructure name='ZPD' description='IHS Patient Information'>
    <SegmentSubStructure piece='2' description='Tribe of Membership Code' length='3' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='3' description='Eligibility Status' length='1' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='4' description='Classification/Beneficiary Code' length='2' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='5' description='Indian Blood Quantum' length='40' required='O' ifrepeating='0'/>
    <SegmentSubStructure piece='6' description='Chart Numbers' length='40' required='O' ifrepeating='1'/>
</SegmentStructure>

<DataStructure name='CT' description='chart numbers'>
    <DataSubStructure piece='1' description='ien'/>
    <DataSubStructure piece='2' description='sequence'/>
    <DataSubStructure piece='3' description='chart number'/>
    <DataSubStructure piece='4' description='date pulled'/>
</DataStructure>

</Category>
</Document>

<Document name="AGMPI.RPMSMessageRouting.RUL"><routingRule host="AGMPI" name="RPMSMessageRouting" effectiveBeginDateTime="" effectiveEndDateTime="" context="EnsLib.HL7.MsgRouter.RoutingEngine" doAll="true" source="RPMSInBound" msgClass="EnsLib.HL7.Message" docName="" docCategory="AGMPI.RPMS" docType="">
  <description></description>
  <reportGroup></reportGroup>
  <reportName></reportName>
  <shortDescription></shortDescription>
  <rule source="" msgClass="" docName="" docCategory="" docType="ACK,ADT_A08,ADT_A28,ADT_A31,ADT_A40,VQQ_Q02,ADT_A01,ADT_A03,MFK_M05">
    <condition join="AND" operator="=" op1="" op2=""></condition>
    <action type="send" target="MPIOutBound" transform=""></action>
  </rule>
</routingRule>
</Document>

<Class name="AGMPI.Services.MPI">
<Description>
The Business Service receiving messages from the MPI System.</Description>
<ProcedureBlock>1</ProcedureBlock>
<Super>EnsLib.HL7.Service.TCPService</Super>
<TimeChanged>62069,45502.677605</TimeChanged>
<TimeCreated>61592,33940.955487</TimeCreated>

<Parameter name="ADAPTER">
<Default>EnsLib.HL7.Adapter.TCPInboundAdapter</Default>
</Parameter>

<Method name="OnProcessInput">
<FormalSpec>pLine:Ens.StringContainer,*pLineLeftOver:Ens.StringContainer</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
  do DISABLE^%NOJRN
  quit ##super(pLine,.pLineLeftOver)
]]></Implementation>
</Method>
</Class>


<Class name="AGMPI.Services.RPMS">
<Description>
A Business Service that receives messages from the RPMS system via the 
HLOGlobal Inbound Adapter.</Description>
<ProcedureBlock>1</ProcedureBlock>
<Super>EnsLib.HL7.Service.Standard</Super>
<TimeChanged>62069,44965.526645</TimeChanged>
<TimeCreated>61592,34079.814283</TimeCreated>

<Parameter name="ADAPTER">
<Default>AGMPI.Adapters.HLOGlobalInbound</Default>
</Parameter>

<Method name="OnProcessInput">
<FormalSpec>InBndMsg:EnsLib.HL7.Message,pOutPut:EnsLib.HL7.Message</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
  do DISABLE^%NOJRN
  // Set the variable to true so that when we return from the adapter we will
  //  wait for the next call interval before calling the adapter again.	
  Set ..%WaitForNextCallInterval=1
  // Set a variable that we'll use to determine if we write 
  //  trace events.
  //Set tWriteTrace = +$G(^AGMPI("TRACE","MPI"))
  //Set tWriteTrace = +$G(^AGMPI("TRACE","MPI"))  station nubers
  Set tWriteTrace = +$G(^AGMPI("TRACE",14752))      //only one station number
  
  If tWriteTrace $$$TRACE("We've entered the OnProcessInput method within the RPMS service.")

  // Get the number of segments sent for the message.
  Set tSegCount = InBndMsg.SegCount
  If tWriteTrace $$$TRACE("Number of segments: "_tSegCount)
  // Get the Message Type name(ADT_A28, ADT_A31,...).
  Set tName=InBndMsg.Name
  If tWriteTrace $$$TRACE("Message Type Name: "_tName)
  // Set a temp holder for the Document Type.
  Set tDcTp=..MessageSchemaCategory_":"_tName
  If tWriteTrace $$$TRACE("Document Type: "_tDcTp)
  // Set the document type for the message.
  Set tSC = InBndMsg.DocTypeSet(tDcTp,1)
  //get msgid ;IHS/SD/TPF agmpi  v7.2 8/27/10
  //Set tmsgid= InBndMsg.getid()
  Set tmsgid= InBndMsg.OriginalDocId
  //Set tmsgid= InBndMsg.RawContent /can't do pt PI in email
  //Set tmsgid="test"
  If tWriteTrace $$$TRACE("Do we have a message id? tmsgid= "_tmsgid_" .")

  
  // What's the MessageSchemaCategory????
  Set tDocType=InBndMsg.DocType
  If tWriteTrace $$$TRACE("Message schema type: "_tDocType)
  Set tDocTypeCat=InBndMsg.DocTypeCategory
  If tWriteTrace $$$TRACE("Message schema type category: "_tDocTypeCat)
  Set tDocTypeName=InBndMsg.DocTypeName
  If tWriteTrace $$$TRACE("Message schema type Name: "_tDocTypeName)
  
  // validate the message by building the Message Map.
  Set tSC=InBndMsg.BuildMap()

  If tWriteTrace $$$TRACE("Do we have a valid message? tSC= "_tSC_" .")

  
  if $$$ISERR(tSC) {
    // We erred and need to handle it...tSC will be a one if
    //  the BuildMap method succefull mapped the message
    //  structure to the definition.
    Set tErrorText=##class(%SYSTEM.Status).GetErrorText(tSC)
	If tWriteTrace $$$TRACE(" Error in the RPMS Business Service, Creating the Message Map: ErrorText= "_tErrorText)
  } else {
	// Get the name of who this request is to be sent.
	Set tTrgtCnfgNms= ..TargetConfigNames
    // We didn't error when created the message map so the message matched
    //  our the HL7 data structure.
    // We send the message to the Target Process.  We only have one if there
    //  were multiple we'd loop above and here through them.
    Set tSC= ..SendRequestAsync(tTrgtCnfgNms,InBndMsg)
    If tWriteTrace $$$TRACE("The message has been sent to "_tTrgtCnfgNms_" with a response of "_tSC)
    if $$$ISERR(tSC) {
	  Set tErrorText=##class(%SYSTEM.Status).GetErrorText(tSC)
	  If tWriteTrace $$$TRACE(" Error in the RPMS Business Service, after sending the message to the message router: ErrorText= "_tErrorText)
    }
  }
  If tWriteTrace $$$TRACE(" After sending the message tSC= "_tSC)
  if $$$ISERR(tSC) {
  	//Do ..SendAlert(##Class(Ens.AlertRequest).%New($LB(..%ConfigName,"There was an Error in the RPMS Business Service: ErrorText= "_tErrorText, tErrorText)))
	Do ..SendAlert(##Class(Ens.AlertRequest).%New($LB(..%ConfigName,"There was an Error in the RPMS Business Service: ErrorText= "_tErrorText_ "msgid= "_tmsgid, tmsgid )))
	If tWriteTrace $$$TRACE(" Sending an Alert")
  }

  quit $$$OK
]]></Implementation>
</Method>
</Class>


<Project name="MOVE_AGMPI_HL7" LastModified="2011-10-24 15:54:04">
  <Items>
    <ProjectItem name="AGMPBC32.INT" type="MAC"/>
    <ProjectItem name="AGMPHLU1.INT" type="MAC"/>
    <ProjectItem name="AGMPI.Adapters.HLOGlobalInbound" type="CLS"/>
    <ProjectItem name="AGMPI.Adapters.HLOGlobalOutbound" type="CLS"/>
    <ProjectItem name="AGMPI.AlertEmailAddress" type="CLS"/>
    <ProjectItem name="AGMPI.Alerts.AlertLog" type="CLS"/>
    <ProjectItem name="AGMPI.MPI.HL7" type="HL7"/>
    <ProjectItem name="AGMPI.MPIAlertRouting.RUL" type="RUL"/>
    <ProjectItem name="AGMPI.MPIMessageRouting.RUL" type="RUL"/>
    <ProjectItem name="AGMPI.Operations.MPI" type="CLS"/>
    <ProjectItem name="AGMPI.Operations.RPMS" type="CLS"/>
    <ProjectItem name="AGMPI.PatientRegistration" type="CLS"/>
    <ProjectItem name="AGMPI.Process.AlertProcess" type="CLS"/>
    <ProjectItem name="AGMPI.Process.AlertProcess.Context" type="CLS"/>
    <ProjectItem name="AGMPI.Process.AlertProcess.Thread1" type="CLS"/>
    <ProjectItem name="AGMPI.Process.AlertProcessContext" type="CLS"/>
    <ProjectItem name="AGMPI.Process.AlertProcessThread1" type="CLS"/>
    <ProjectItem name="AGMPI.RPMS.HL7" type="HL7"/>
    <ProjectItem name="AGMPI.RPMSMessageRouting.RUL" type="RUL"/>
    <ProjectItem name="AGMPI.Services.MPI" type="CLS"/>
    <ProjectItem name="AGMPI.Services.RPMS" type="CLS"/>
  </Items>
</Project>
</Export>
