COMPILE FUNCTION obj_SAP(Method,Parms)
#pragma precomp SRP_PreCompiler

/*
	Methods for Interfacing with SAP
    
	11/10/2010      JCH         Initial Coding
	11/20/2015      JCH & DKK   updated
	10/11/2018      djs         Additional logging added to SendRecord subroutine
    01/30/2019      djs         SendRecord logging updated to record outbound files in respective directories
    04/03/2024      djs         Updated code to use psftp instead of ftp.
     
    Properties:
     
    Methods:
    
    GetOrder()						;* GetOrder from buffer
    
*/


DECLARE FUNCTION    Get_Status, Msg, Utility, obj_Tables, Dialog_Box, obj_WO_Log, NextKey, obj_Shipment, obj_WO_Mat
Declare function    Error_Services, Environment_Services, Logging_Services, GetCurrentProcessID
DECLARE SUBROUTINE  Set_Status, Msg, obj_Tables, ErrMsg, Set_Property, obj_Order, Yield, Clear_Table, RList, obj_Notes
DECLARE SUBROUTINE  Send_Info, Send_Event, Post_Event, obj_Notes, SetInitDirOptions, Send_Info, obj_Shipment, obj_Post_Log
DECLARE SUBROUTINE  Srp_Run_Command, Error_Services, Logging_Services, FTP_Services, Mona_Services

$INSERT MSG_EQUATES
$INSERT NOTIFICATION_EQU
$INSERT WO_LOG_EQUATES
$INSERT WO_MAT_EQUATES
$INSERT COMPANY_EQUATES
$INSERT SAP_BATCH_EQUATES
$INSERT EPI_PART_EQUATES
$INSERT RLIST_EQUATES
$INSERT SAP_COMM_LOG_EQUATES
$INSERT LOGICAL

Equ CRCRLF$ TO \0D0D0A\
Equ CRLF$   TO \0D0A\
Equ LF$     TO \0A\
Equ TAB$    TO \09\

LogDate    = Oconv(Date(), 'D4/')
LogTime    = Oconv(Time(), 'MTS')
LoggingDTM = LogDate : ' ' : LogTime   ; // Logging DTM

LogPath     = Environment_Services('GetApplicationRootPath') : '\LogFiles\ScrapIn'
LogFileName = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' ScrapIn.csv'
Headers     = 'Logging DTM' : @FM : 'User' :@FM: 'WoMatKey' :@FM: 'SAPBatchNo' :@FM: 'TransQty'
objLog      = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, Comma$, Headers, '', False$, False$)

LogPath         = Environment_Services('GetApplicationRootPath') : '\LogFiles\WO_LOG'
LogFileName     = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' Work Order Create Performance Log.csv'
Headers         = 'Logging DTM':@FM:'Filename':@FM:'Duration'
objSAPCreateLog = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, COMMA$, Headers, '', False$, False$)

LogPath               = Environment_Services('GetApplicationRootPath') : '\LogFiles\SAP'
LogFileName           = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' Outbound SFTP Log.csv'
Headers               = 'Logging DTM' : @FM : 'Notes'
objSapOutboundSftpLog = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, Comma$, Headers, '', False$, False$, True$)

LogPath              = Environment_Services('GetApplicationRootPath') : '\LogFiles\SAP'
LogFileName          = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' Inbound SFTP Log.csv'
Headers              = 'Logging DTM' : @FM : 'Notes'
objSapInboundSftpLog = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, Comma$, Headers, '', False$, False$, True$)

IsProd = Environment_Services('IsProd')
If IsProd EQ True$ then
	MonaInboundResource  = 'GRP_OPENINSIGHT_MES_OP_FE_SAP_INBOUND'
	MonaOutboundResource = 'GRP_OPENINSIGHT_MES_OP_FE_SAP_OUTBOUND'
end else
	MonaInboundResource  = 'GRP_OPENINSIGHT_MES_OP_FE_DEV_SAP_INBOUND'
	MonaOutboundResource = 'GRP_OPENINSIGHT_MES_OP_FE_DEV_SAP_OUTBOUND'
end

Main:

    RepoID     = ''
    SAPEnviron = Environment_Services('GetSAPPath')

    BEGIN CASE
        CASE SAPEnviron = 'PRD'
            TransFilePathIn		= Environment_Services('GetFTPRootPath') : '\FTP_IN'
            TransFilePathOut	= Environment_Services('GetFTPRootPath') : '\FTP_OUT'
            FTPScriptPath		= Environment_Services('GetFTPRootPath') : '\FTPScript\'
            FTPServerIP			= '172.23.28.185'	;* This is the new EU server (sappnfs.eu.infineon.com)
            FTPUser				= 'prdopeni'
            FTPPassWord			= 'sapprdopeni'
            FTPCapturePath      = Environment_Services('GetApplicationRootPath') : '\SAP\FTPFiles\'

        CASE SAPEnviron = 'QA'
            TransFilePathIn		= Environment_Services('GetFTPRootPath') : '\FTP_IN_TEST'
            TransFilePathOut	= Environment_Services('GetFTPRootPath') : '\FTP_OUT_TEST'
            FTPScriptPath		= Environment_Services('GetFTPRootPath') : '\FTPScript_Test\'
            FTPServerIP			= '172.28.150.80'		;* IFX EU FTP Server IP address or URL
            FTPUser				= 'qasopeni'
            FTPPassWord			= 'sapqasopeni'
            FTPCapturePath      = Environment_Services('GetApplicationRootPath') : '\SAP\FTPFiles\'
            
        CASE 1
            ErrMsg('Invalid SAPEnviron variable in obj_SAP')
            RETURN
    END CASE

    BaseFromSAPScript = 'lcd ':TransFilePathIn:CRLF$		;* Change local directory to C:\FTP_IN

    FromSAPScriptName = FTPScriptPath:'FromSAP.txt'

    BaseToSAPScript	= 'lcd ':TransFilePathOut:CRLF$		;* Change local directory to C:\FTP_OUT

    ToSAPScriptName = FTPScriptPath:'ToSAP.txt'
     
    ErrTitle = 'Error in Stored Procedure "obj_SAP"'
    ErrorMsg = ''

    IF NOT(ASSIGNED(Method))	THEN ErrorMsg = 'Unassigned parameter "Method" passed to subroutine'
    IF NOT(ASSIGNED(Parms))		THEN Parms = ''

    IF ErrorMsg NE '' THEN
        Set_Status(-1,ErrTitle:@SVM:ErrorMsg)
        RETURN ''
    END

    Result = ''

    BEGIN CASE
        CASE Method = 'GetInbound'		; GOSUB GetInbound
        CASE Method = 'AddTransaction'	; GOSUB AddTransaction
        CASE Method = 'SendOutbound'	; GOSUB SendOutbound
        CASE Method = 'SendReconcile'	; GOSUB SendReconcile
        
        CASE 1
            ErrorMsg = 'Unknown Method ':QUOTE(Method):' passed to routine.'

    END CASE

    IF ErrorMsg NE '' THEN
        Set_Status(-1,ErrTitle:@SVM:ErrorMsg)
        RETURN ''
    END

RETURN Result


* * * * * * *

SendReconcile:
* * * * * * *

    IF SAPEnviron NE 'PRD' THEN RETURN  ;* Belt and suspenders for production system

    OPEN 'WO_LOG' TO WOTable ELSE
        ErrorMsg = 'Unable to open WO_LOG table in obj_SAP'
        RETURN
    END

    Yesterday		= OCONV(Date()-1,'D4/')
    CurrTime		= OCONV(Time(),'MTS')
    YesterdayDTM	= Yesterday:' ':CurrTime

    Set_Status(0)

    SelectSent  = 'SELECT WO_LOG WITH PROD_ORD_NO NE "" '

    RList(SelectSent,TARGET_ACTIVELIST$,'','','')
    errCode = ''
    IF Get_Status(errCode) THEN
        RETURN
    END

    SelectSent = 'SELECT WO_LOG WITH WO_STOP_DTM = "" OR WITH WO_STOP_DTM >= ':Quote(YesterdayDTM):' BY WO'

    RList(SelectSent,TARGET_ACTIVELIST$,'','','')
    IF Get_Status(errCode) THEN
        RETURN
    END

    TextOut = ''	;* Results go into this data structure

    Done = 0
    LOOP
        READNEXT WONo ELSE Done = 1
    UNTIL Done
        READ WORec FROM WOTable,WONo THEN
            Line = ''
            CurrStatus = obj_WO_Log('CurrStatus',WONo:@RM:WORec)
            
            Line<1> = WORec<WO_LOG_PROD_ORD_NO$>									;* ZAUFNR
            Line<2> = WORec<WO_LOG_PROD_ORD_NO$>									;* ZCHARG 
            
            BEGIN CASE
                CASE WORec<WO_LOG_WO_STOP_DTM$> NE ''	; Line<3> = 'COMP'				;* ZSTTXT
                CASE CurrStatus = 'NORD'				; Line<3> = 'NORD'				;* ZSTTXT
                CASE CurrStatus = 'NEW'					; Line<3> = 'NEW'
                CASE CurrStatus = 'ASN'					; Line<3> = 'ASN'
                CASE CurrStatus = 'AWM'					; Line<3> = 'AWM'
                CASE CurrStatus = 'RTP'					; Line<3> = 'RTP'	
                CASE CurrStatus = 'AWR'					; Line<3> = 'AWR'	
                CASE CurrStatus = 'RX'					; Line<3> = 'RX'
                CASE CurrStatus = 'INPR'				; Line<3> = 'INPR'
                CASE CurrStatus = 'RTS'					; Line<3> = 'RTS'
                CASE CurrStatus = 'SHIP'				; Line<3> = 'SHIP'			
                CASE CurrStatus = 'COMP'				; Line<3> = 'CL'			;* Changed from "COMP" to "CL" -dkk 3/21/14
                CASE CurrStatus = 'CANC'				; Line<3> = 'CANC'
                CASE CurrStatus = 'CL'					; Line<3> = 'CL'
                CASE CurrStatus = 'INC'					; Line<3> = 'INC'
                CASE 1									; Line<3> = 'INC'
            END CASE
            
            EPIPn = WORec<WO_LOG_EPI_PART_NO$>
            
            SpecType	= XLATE('EPI_PART',EpiPN,EPI_PART_SPEC_TYPE$,'X')
            CustCaptive = XLATE('COMPANY',WORec<WO_LOG_CUST_NO$>,COMPANY_CAPTIVE$,'X')
            
            BEGIN CASE
                CASE CustCaptive = '1'					; Line<4> = 'ZP01'			;* ZAUART - Captive
                CASE WORec<WO_LOG_PROD_VER_NO$> NE ''	; Line<4> = 'ZP04'			;* ZAUART - Merchant
                CASE 1									; Line<4> = 'ZP00'			;* ZAUART - Rx'd from SAP
            END CASE
            
            WOStartDt	= WORec<WO_LOG_WO_START_DTM$>[1,'.']
            WOStopDt	= WORec<WO_LOG_PROMISE_SHIP_DT$>[1,'.']
            
            IF WOStartDt = '' THEN
                Line<5> = '00000000'
            END ELSE
                Line<5>	= OCONV(WOStartDt,'[SAP_DT_FORMAT]')						;* GSTRP
            END
            
            Line<6> = OCONV(WOStopDt,'[SAP_DT_FORMAT]')								;* GLTRP	;******* Promise Ship Dt *******************
            
            Line<7> = EpiPN															;* MATNR
            Line<8> = FMT(WORec<WO_LOG_WO_QTY$>,"R(0)#9")							;* GAMNG    ;******* Total Good Wafers Completed  ******
                    
            
            AllWOMatKeys		= WORec<WO_LOG_WO_MAT_KEY$>
            RawBatch_WOMatKeys	= XLATE('WO_MAT',AllWOMatKeys,WO_MAT_SAP_BATCH_NO$,'X')
            
            CompWOMatKeys = ''
            
            WOMatCnt = COUNT(AllWOMatKeys,@VM) + (AllWOMatKeys NE '')
            
            FOR I = 1 TO WOMatCnt
                IF RawBatch_WOMatKeys<1,I> NE '' THEN
                    CompWOMatKeys<1,-1> = AllWOMatKeys<1,I>
                END
            NEXT I
            
            CassCompCnt = COUNT(CompWOMatKeys,@VM) + (CompWOMatKeys NE '')
            
            IF CassCompCnt > 0 THEN Line<9> = '0020'	;* VORNR
            
            OrderQty = WORec<WO_LOG_WO_QTY$>
            
            TotCompQty   = 0
            TotScrapQty  = 0
            TotProdTWQty = 0
            TotMUWfrQty	 = 0
            
            FOR I = 1 TO CassCompCnt
                WOMatKey = CompWOMatKeys<1,I>
                
                GRProps = obj_WO_Mat('GetGRProps',WOMatKey:@RM:'')
                
                GRWfrQty	= GRProps[1,@FM]
                ScrapQty	= GRProps[COL2()+1,@FM]
                ProdTWQty	= GRProps[COL2()+1,@FM]
                MUWfrQty	= GRProps[COL2()+1,@FM]
                
                TotCompQty		+= GRWfrQty
                TotScrapQty		+= ScrapQty
                TotProdTWQty	+= ProdTWQty
                TotMUWfrQty		+= MUWfrQty
            NEXT I
            
            IF OrderQty <= 0 THEN
                Line<10> = FMT('0',"R(0)#9")
            END ELSE
                Line<10> = FMT(TotCompQty,"R(0)#9")									;* MGVRG
            END
             
            Line<11> = FMT(TotScrapQty + TotProdTWQty,"R(0)#9")						;* XMNGA		
            
            CurrDate	= OCONV(Date(),'D4/')
            CurrTime	= OCONV(Time(),'MTS')
            CurrDTM		= ICONV(CurrDate:' ':CurrTime,'DT')

            TimeStamp = OCONV(CurrDTM,'[SAP_DTM_FORMAT]')

            Line<12> = TimeStamp													;* ZEXTDTE
            
            Line<13> = '1210'														;* ZMESYSS
            
        END	;* End of WORec read
        
        CONVERT @FM TO '~' IN Line
        TextOut<-1> = Line
    REPEAT
    
    OutRec = TextOut
    SWAP @FM WITH CRLF$ IN OutRec

    CurrDate	= OCONV(Date(),'D4/')
    CurrTime	= OCONV(Time(),'MTS')
    CurrDTM		= ICONV(CurrDate:' ':CurrTime,'DT')

    TimeStamp = OCONV(CurrDTM,'[SAP_DTM_FORMAT]')

    TransFileName	= 'RECON_1210_':TimeStamp:'.txt'

    * This is the ftp code here
        
    ToSAPScript  = 'open 172.28.150.80':CRLF$
    ToSAPScript := 'user':CRLF$

    BEGIN CASE
        
        CASE SAPEnviron = 'PRD'
            DosTable = Environment_Services('GetFTPRootPath') : '\FTP_OUT\':TransFileName
            ToSAPScript := 'prdwiprcn':CRLF$
            ToSAPScript := 'sapprdrcn':CRLF$
            ToSAPScript	:= 'lcd ' : Environment_Services('GetFTPRootPath') : '\FTP_OUT':CRLF$
        
        CASE  SAPEnviron = 'QA'
            DosTable = Environment_Services('GetFTPRootPath') : '\FTP_OUT_TEST\':TransFileName
            ToSAPScript := 'qaswiprcn':CRLF$
            ToSAPScript := 'sapqasrcn':CRLF$
            ToSAPScript	:= 'lcd ' : Environment_Services('GetFTPRootPath') : '\FTP_OUT_TEST':CRLF$
        
        CASE SAPEnviron = 'DEV' 
            DosTable = Environment_Services('GetFTPRootPath') : '\FTP_OUT_TEST\':TransFileName
            ToSAPScript := 'devwiprcn':CRLF$
            ToSAPScript := 'sapdevrcn':CRLF$
            ToSAPScript	:= 'lcd ' : Environment_Services('GetFTPRootPath') : '\FTP_OUT_TEST':CRLF$
            
        CASE 1
            NULL
        
    END CASE

    // Logging Added - 10/11/18
    // To do: Update logging to save files in their respective directories in the event that the files
    //        need to be retransmitted.
    ExternalDate = OConv(Date(), 'D')
    Swap ' ' with '_' in ExternalDate
    ExternalTime = OConv(Time(), 'MTHS')
    Swap ':' with '_' in ExternalTime
    RepoFileName = ExternalDate:'_':ExternalTime:'_':TransFileName
    RepoDir = Environment_Services('GetFTPRootPath') : '\FTP_OUT_REPOSITORY\':RepoFileName
    OSWrite OutRec ON RepoDir
    //

    OSWRITE OutRec ON DosTable

    ToSAPScript := 'cd inbound':CRLF$
    ToSAPScript := 'put ':DosTable:CRLF$
    ToSAPScript := 'get ':TransFileName:' WipVerify.txt':CRLF$
    ToSAPScript := 'bye':CRLF$


    OSWrite ToSAPScript ON Environment_Services('GetFTPRootPath') : '\ToSAP.scr'

    StartTime = Time()

    stat = "VAR"
    
    FTPCommand = "psftp ":FTPUser:"@":FTPServerIP:" -pw ":FTPPassword:" -b ":Environment_Services('GetFTPRootPath') : "\ToSAP.scr":" -batch"
    SRP_Run_Command(FTPCommand, stat, '', '')
    
    LogData    = ''
    LogData<1> = LoggingDtm
    LogData<2> = stat
    Logging_Services('AppendLog', objSapOutboundSftpLog, LogData, @RM, @FM)
    
    GoSub CheckForErrors
    
    If SftpError then
    	// Send Email to FI_SUPPORT group
		Recipients   = ''
		SentFrom     = 'System'
		Subject      = 'Outbound SFTP error in obj_SAP'
		Message      = 'SFTP output: ':CRLF$:stat
		AttachWindow = ''
		AttachKey    = ''   
		SendToGroup  = 'FI_SUPPORT'
		Parms = Recipients:@RM:SentFrom:@RM:Subject:@RM:Message:@RM:AttachWindow:@RM:AttachKey:@RM:SendToGroup
		obj_Notes('Create',Parms)    	
    	Mona_Services('PostStatus', MonaOutboundResource, 'SFTP-Interface-Outbound', 'critical')
    end else
    	Mona_Services('PostStatus', MonaOutboundResource, 'SFTP-Interface-Outbound', 'ok')
    end
    
    StopTime = Time()

    IF StopTime - StartTime > 30 THEN
        ErrorMsg = 'FTP method "SendRecord" Execution Time > 30 seconds'
        ClearFlag = 0
        RETURN
    END

    OSRead VerifyTxt FROM Environment_Services('GetFTPRootPath') : '\FTP_OUT\verify.txt' THEN
        IF VerifyTxt = OutRec THEN
            ClearFlag = 1
        END ELSE
            ClearFlag = 0
        END
    END ELSE
        VerifyTxt = ''
        ClearFlag = 0
    END

    OSDelete DosTable		;* Removes table from C: drive 

RETURN


* * * * * * *
AddTransaction:
* * * * * * * 

    TransAction = Parms[1,@RM]

    IF TransAction = '' THEN RETURN

    BEGIN CASE

        CASE Transaction = 'WO_MAT_HOLD'
        
            SAPBatchNo	= Parms[COL2()+1,@RM]						;* SAP Batch No
            SLoc		= Parms[COL2()+1,@RM]						;* Storage Location in SAP
            Flag		= Parms[COL2()+1,@RM]						;* Flag
            
            IF Flag = '' THEN Flag = 0
            
            TransRec = TransAction:@FM:SAPBatchNo:@FM:SLoc:@FM:Flag
         
        CASE TransAction = 'WO_HOLD'								;* * *  Lot Hold, Lot off Hold, Start Lot, Lot Complete PP-I-423/524 * * *	
            
            ProdOrdNo	= Parms[COL2()+1,@RM]						;* Prod Order No
            Flag 		= Parms[COL2()+1,@RM]						;* Flag (might use a word instead)
            
            IF Flag = '' THEN Flag = 0
            
            IF Flag = 1	THEN
                SAP_Parm = 'ON_HOLD'
            END ELSE
                SAP_Parm = 'OFF_HOLD'
            END
            
            TransRec = TransAction:@FM:ProdOrdNo:@FM:SAP_Parm		;* 
            
        CASE TransAction = 'WO_START' OR TransAction = 'WO_STOP'	;* Function Spec : PP-I-521
        
            ProdOrdNo = Parms[COL2()+1,@RM]							;* Prod Order No
            TransDate = Parms[COL2()+1,@RM]							;* Start or Stop Date
            
            TransDate = OCONV(TransDate,'D4/')
            
            TransRec = TransAction:@FM:ProdOrdNo:@FM:TransDate		;* First Cassette into CleanRoom is start, Last Cassette out is stop
            
        CASE TransAction = 'PROMISE_DT'								;* * *  Change Scheduled CLOSE  (Propmise) Date PP-I-526  * * *
        
            ProdOrdNo 		= Parms[COL2()+1,@RM]					;* Prod Order Number
            OrgPromiseDt	= Parms[COL2()+1,@RM]					;* Original Scheduled Close (Promise) Date 
            NewPromiseDt	= Parms[COL2()+1,@RM]					;* New Scheduled Close (Promise) Date
            
            TransOrgPromiseDt = OCONV(OrgPromiseDt,'D4/')
            TransNewPromiseDt = OCONV(NewPromiseDt,'D4/')
            
            TransRec = Transaction:@FM:ProdOrdNo:@FM:TransOrgPromiseDt:@FM:TransNewPromiseDt
                 
        CASE TransAction = 'CASS_COMP'							;* Packages the Cassette Complete Transaction_Final QA Triggered -dkk 7/28/14
        
            ProdOrdNo 	= Parms[COL2()+1,@RM]		; ParmList 		= ProdOrdNo			;* Production Order Number
            WorkOrdNo	= Parms[COL2()+1,@RM]		; ParmList<2>	= WorkOrdNo			;* Work Order No
            CassNo		= Parms[COL2()+1,@RM]		; ParmList<3>	= CassNo			;* Cass No 
            GRWfrQty	= Parms[COL2()+1,@RM]		; ParmList<4>	= GrWfrQty			;* Good Wafers NOT INCLUDING MAKEUPS
            ScrapQty	= Parms[COL2()+1,@RM]		; ParmList<5>	= ScrapQty			;* Scrap (NCR'd wafers)
            ProdTWQty	= Parms[COL2()+1,@RM]		; ParmList<6>	= ProdTWQty			;* Product Test Wafers
            CassID		= Parms[COL2()+1,@RM]		; ParmList<7>	= CassID			;* Cass ID
            VendorLotNo	= Parms[COL2()+1,@RM]		; ParmList<8>	= VendorLotNo		;* Vendor Lot Number on substrate
            SubSupplier = Parms[COL2()+1,@RM]		; ParmList<9>	= SubSupplier		;* Vendor Code SubSupplier
            CustPartRev	= Parms[COL2()+1,@RM]		; ParmList<10>	= CustPartRev		;* Cust Part Revision
            MakeupFlag	= Parms[COL2()+1,@RM]		; ParmList<11>	= MakeupFlag		;* Makeup Flag
            MUBatchNo	= Parms[COL2()+1,@RM]		; ParmList<12>	= MUBatchNo			;* Request MU to pull from in SLoc 0400 -dkk 7/28/14
            MUBatchQty	= Parms[COL2()+1,@RM]		; ParmList<13>	= MUBatchQty		;* Request MU Qty to pull from MU batch located in SLoc 0400 -dkk 7/28/14
            
            TransRec = TransAction:@FM:ParmList
            
        Case TransAction = 'SCRAP_IN'

            WorkOrdNo	= Parms[COL2()+1,@RM]					            ;* Work Order No
            CassNo		= Parms[COL2()+1,@RM]					            ;* Cass No
            TransQty	= Parms[COL2()+1,@RM]		                        ;* Scrap (NCR'd wafers) Transaction Quantity		
            WoMatKey    = WorkOrdNo:'*':CassNo
            
            Plant       = 1210                                              ;* Plant is always 1210 - MESA Site
            Material    = Xlate('WO_LOG', WorkOrdNo, 'EPI_PART_NO', 'X')    ;* Epi part number
            SAPBatchID  = Xlate('WO_MAT', WoMatKey, 'SAP_BATCH_NO', 'X')
            
            ParmList    = Plant
            ParmList<2> = Material
            ParmList<3> = SAPBatchID
            ParmList<4> = TransQty
            
            TransRec = TransAction:@FM:ParmList
            LogData    = @USER4
            LogData<2> = WoMatKey
            LogData<3> = SAPBatchID
            LogData<4> = TransQty
            Logging_Services('AppendLog', ObjLog, LogData, @RM, @FM, True$)
            
        Case TransAction = 'BATCHMOVE_IN'
            
            Plant        = 1210
            Material     = Parms[COL2()+1,@RM]           
            BatchFrom    = Parms[COL2()+1,@RM]
            BatchTo      = Parms[COL2()+1,@RM]
            StoreLocFrom = Parms[COL2()+1,@RM] 
            StoreLocTo   = Parms[COL2()+1,@RM]
            TransQty     = Parms[COL2()+1,@RM]            
                                                                      ;* Plant is always 1210 - MESA Site
            ParmList    = Plant
            ParmList<2> = Material
            ParmList<3> = BatchFrom             
            ParmList<4> = StoreLocFrom
            ParmList<5> = BatchTo
            ParmList<6> = StoreLocTo
            ParmList<7> = TransQty

            TransRec = TransAction:@FM:ParmList
            
        Case TransAction = 'BATCH_CONV'
		
			ParmList    = 1210				  ; // Plant
			ParmList<2> = Parms[COL2()+1,@RM] ; // Material
			ParmList<3> = Parms[COL2()+1,@RM] ; // SAPBatchNo
			ParmList<4> = Parms[COL2()+1,@RM] ; // StoreLocFrom
			ParmList<5> = Parms[COL2()+1,@RM] ; // StoreLocTo
			ParmList<6> = Parms[COL2()+1,@RM] ; // BatchQty
		
			TransRec = TransAction:@FM:ParmList

        CASE 1
            
            ErrorMsg = 'Unknown TransAction ':QUOTE(TransAction):' passed to routine. (':METHOD:')'
            RETURN
            
    END CASE

    NextTransNo = NextKey('SAP_COMM')
    OtParms     = 'SAP_COMM':@RM:NextTransNo:@RM:@RM:TransRec
    obj_Tables('WriteRec',OtParms)
    ErrCode     = ''
    IF Get_Status(ErrCode) then
        ErrorMsg = ErrCode
    end 

RETURN


* * * * * * *
GetInbound:
* * * * * * *

    *  Start of SAP inbound code  JCH
    FTPRootPath = Environment_Services('GetFTPRootPath')
    TransLogOn  = Parms[1,@RM]		;* Added 12/12/2011 Flag to turn on transaction logging

    IF TransLogOn = 1 THEN
        OPEN 'SAP_COMM_LOG' TO LogFile ELSE NULL
    END

    GOSUB ReadInbound				;* Copies files on FTP server FromSAP\ProdOrdRel directory into C:\FTP_IN directory

    IF ErrorMsg NE '' THEN RETURN	;* Had problem with ftp process

    ******* Production Order Releases Inbound  *******

    InboundPath = TransFilePathIn:'\ProdOrdRel\'	

    InitDir InboundPath:'*.tsv'
    FileList = DirList()

    FileNames = ''
    LOOP
        FileName = FileList[1,@FM]
        FileList[1,Col2()] = ""
        
        LOCATE FileName IN FileNames BY 'AR' USING @FM SETTING Pos ELSE
            FileNames = INSERT(FileNames,Pos,0,0,FileName)
        END
        
    UNTIL FileList = ""
    REPEAT

    IF FileNames[-1,1] = @FM THEN FileNames[-1,1] = ''
    Test = ''
    FileCnt = COUNT(FileNames,@FM) + (FileNames NE '')


    FOR N = 1 TO FileCnt        
        
        Send_Info('Processing ':N:' of ':FileCnt)
        FileName = FileNames<N>
        StartTime = Time()
        
        OSREAD FileIn FROM InboundPath:FileName THEN
            
            OrigFileIn = FileIn
            SWAP LF$ WITH CRLF$ IN OrigFileIn
            
            /************************ Log inbound file **************************/
            RepoDir = FTPRootPath : '\FTP_IN_REPOSITORY\ProdOrdRel\':FileName
            OSWrite OrigFileIn on RepoDir           
            /********************************************************************/
        
            IF TransLogOn = 1 THEN
                LTType	= 'RX'
                Trans	= 'ProdOrdRel'
                GOSUB LogTrans				;* Added 12/12/2011 JCH for transaction logging
            END	

            SWAP TAB$  WITH @VM IN FileIn
            SWAP '|'   WITH @VM IN FileIn		;* Incorrect delimiter
            SWAP CRLF$ WITH @FM IN FileIn
            SWAP LF$   WITH @FM IN FileIn
            
            LOOP
                LastChar = FileIn[-1,1]
            UNTIL LastChar NE @FM
                FileIn[-1,1] = ''
            REPEAT
            
            RetVal = obj_WO_LOG('SAPCreate',FileIn)
            
            OSDELETE InboundPath:Filename		;* Deletes local copy of inbound file
            
            SubDirectory = 'ProdOrdRel'
            GOSUB ClearInbound					;* Deletes file on FTP server FromSAP\ProdOrdRel directory * * * * * * * * * * * * * * 
                
        END
        
        StopTime = Time()
        Duration = StopTime - StartTime
        
        LogData       = ''
        LogData<1>    = Oconv(Date(), 'D4/') : ' ' : Oconv(Time(), 'MTS')
        LogData<2>    = Filename
        LogData<3>    = Duration
        Logging_Services('AppendLog', objSAPCreateLog, LogData, @RM, @FM)
        
        
    NEXT N

    * * * * * * *  Cassette Batch Numbers Inbound  * * * * * * *

    InboundPath	= TransFilePathIn:'\Batch\'			;* Get any inbound batch releases

    InitDir InboundPath:'*.tsv'
    FileList = DirList()

    FileNames = ''
    LOOP
        FileName = FileList[1,@FM]
        FileList[1,Col2()] = ""
        
        LOCATE FileName IN FileNames BY 'AR' USING @FM SETTING Pos ELSE
            FileNames = INSERT(FileNames,Pos,0,0,FileName)
        END
        
    UNTIL FileList = ""
    REPEAT
    
    IF FileNames[-1,1] = @FM THEN FileNames[-1,1] = ''
    Test = ''
    FileCnt = COUNT(FileNames,@FM) + (FileNames NE '')


    FOR N = 1 TO FileCnt
        Send_Info('Processing ':N:' of ':FileCnt)
        FileName = FileNames<N>
        StartTime = Time()
        
        
        OSREAD FileIn FROM InboundPath:FileName THEN
            
            OrigFileIn = FileIn
            SWAP LF$ WITH CRLF$ IN OrigFileIn
            
            /************************ Log inbound file **************************/
            RepoDir    = FTPRootPath : '\FTP_IN_REPOSITORY\Batch\':FileName
            OSWrite OrigFileIn on RepoDir           
            /********************************************************************/
            
            IF TransLogOn = 1 THEN
                LTType = 'RX'
                Trans	= 'SetBatch'
                GOSUB LogTrans				;* Added 12/12/2011 JCH for transaction logging
            END	
        
            SWAP TAB$    WITH @VM IN FileIn
            SWAP CRCRLF$ WITH @FM IN FileIn
            SWAP LF$     WITH @FM IN FileIn
            
            LOOP
                LastChar = FileIn[-1,1]
            UNTIL LastChar NE @FM
                FileIn[-1,1] = ''
            REPEAT
            
            RetVal = obj_WO_Mat('SetSAPBatch',FileIn)
            
            IF RetVal = 1 THEN
            
                OSDELETE InboundPath:Filename		;* Deletes local copy of inbound file
                
                SubDirectory = 'Batch'
                GOSUB ClearInbound							;* Deletes file on FTP server FromSAP\Batch directory
                
            END	;* End of check for successful WO_LOG create
        END
    NEXT N

    * * * * * * *  Shipment Releases Inbound  * * * * * * *
    InboundPath	= TransFilePathIn:'\ShipRel\'			;* Get any inbound Product Order Releases

    InitDir InboundPath:'*.tsv'
    FileList = DirList()

    FileNames = ''
    LOOP
        FileName = FileList[1,@FM]
        FileList[1,Col2()] = ""
        
        LOCATE FileName IN FileNames BY 'AR' USING @FM SETTING Pos ELSE
            FileNames = INSERT(FileNames,Pos,0,0,FileName)
        END
        
    UNTIL FileList = ""
    REPEAT
    
    IF FileNames[-1,1] = @FM THEN FileNames[-1,1] = ''
    Test = ''
    FileCnt = COUNT(FileNames,@FM) + (FileNames NE '')

    FOR N = 1 TO FileCnt
        Send_Info('Processing ':N:' of ':FileCnt)
        FileName = FileNames<N>
        StartTime = Time()
        OSREAD FileIn FROM InboundPath:FileName THEN
            
            OrigFileIn  = FileIn
            SWAP LF$ WITH CRLF$ IN OrigFileIn
            /************************ Log inbound file **************************/
            RepoDir = FTPRootPath : '\FTP_IN_REPOSITORY\ShipRel\':FileName
            OSWrite OrigFileIn on RepoDir           
            /********************************************************************/
            
            SWAP TAB$    WITH @VM IN FileIn
            SWAP CRCRLF$ WITH @FM IN FileIn
            SWAP CRLF$   WITH @FM IN FileIn
            SWAP LF$     WITH @FM IN FileIn
            
            LOOP
                LastChar = FileIn[-1,1]
            UNTIL LastChar NE @FM
                FileIn[-1,1] = ''
            REPEAT
            
            Error_Services('Clear')
            RetVal = obj_Shipment('SAPCreate',FileIn)

            OSWrite OrigFileIn to FTPCapturePath : FileName
            
            IF RetVal = 1 THEN
            
                OSDELETE InboundPath:Filename		;* Deletes local copy of inbound file
                
                SubDirectory = 'ShipRel'
                GOSUB ClearInbound					;* Deletes file on FTP server FromSAP\ProdOrdRel directory
                
            END	;* End of check for successful WO_LOG create
        END
    NEXT N

RETURN


* * * * * * *
SendOutbound:
* * * * * * *

    TransLogOn = Parms[1,@RM]		;* Added 12/12/2011 Flag to turn on transaction logging
    TransLimit = Parms[COL2()+1,@RM]

    IF TransLogOn = 1 THEN
        OPEN 'SAP_COMM_LOG' TO LogFile ELSE NULL
    END
    
    OPEN 'SAP_COMM' TO Buffer THEN
        Cursor = ''
        SELECT 'SAP_COMM' BY 'SEQ' SETTING Cursor ELSE
            ErrMsg("Select failure in obj_SAP('SendOutBound'...")
            RETURN
        END
        
        Done = 0
        TransQty = 0
        LOOP
            READNEXT TxSeqNo USING Cursor ELSE Done = 1
        UNTIL Done Or TransQty = TransLimit
            ClearFlag = 0
            TransQty += 1
            READ Transaction FROM Buffer,TxSeqNo THEN
                TransType = Transaction<1>
                Transaction = DELETE(Transaction,1,0,0)
                
                BEGIN CASE
                
                    CASE TransType = 'CASS_COMP'
                        OutBoundDir = 'CassComp'
                        
                        OutRec = Transaction
                                               
                        ProdOrdNo = Transaction[1,@FM]
                        RepoID    = ProdOrdNo
                                               
                        CONVERT @FM TO TAB$ IN OutRec
                        
                        OutRec := CRLF$
                        
                        GOSUB SendRecord

                    CASE TransType = 'CUST_TW' OR TransType = 'MU_WFR'
                    
                        OutBoundDir = 'InvMove'
                        
                        IF TransType = 'CUST_TW' THEN
                        
                            ProdOrdNo		= Transaction[1,@FM]
                            CustTWPartNo	= Transaction[COL2()+1,@FM]
                            WfrQty			= Transaction[COL2()+1,@FM] 
                            IF CustTWPartNo = '' THEN CustTWPartNo = '{Cust TW Part No}'
                        
                            OutRec = 'CUST_TW':TAB$:ProdOrdNo:TAB$:CustTWPartNo:TAB$:WfrQty:CRLF$
                        END
                        
                        IF TransType = 'MU_WFR' THEN							  
                        
                            ProdOrdNo	= Transaction[1,@FM]
                            MUProdOrdNo = Transaction[COL2()+1,@FM]
                            WfrQty		= Transaction[COL2()+1,@FM] 
                    
                            OutRec = 'MU_WFR':TAB$:ProdOrdNo:TAB$:MUProdOrdNo:TAB$:WfrQty:CRLF$
                        END
                        
                        RepoID    = ProdOrdNo
                        
                        GOSUB SendRecord
                        
                    
                    CASE TransType = 'PROD_TW' OR TransType = 'WFR_REJECT'
                    
                        OutBoundDir = 'Scrap'
                        
                        ProdOrdNo	= Transaction[1,@FM]
                        WfrQty		= Transaction[COL2()+1,@FM] 
                        
                        IF TransType = 'PROD_TW' THEN
                            OutRec = 'PROD_TW':TAB$:ProdOrdNo:TAB$:WfrQty:CRLF$
                        END
                        
                        IF TransType = 'WFR_REJECT' THEN                           
                            OutRec = 'WFR_REJECT':TAB$:ProdOrdNo:TAB$:WfrQty:CRLF$
                        END
                        
                        RepoID  = ProdOrdNo
                        
                        GOSUB SendRecord
                    
                    CASE TransType = 'WO_HOLD'
                        
                        ! These transactions are obsolete
                        ProdOrdNo	= Transaction[1,@FM]
                        HoldOnOff	= Transaction[COL2()+1,@FM]
                        
                        IF HoldOnOff = 'ON_HOLD' THEN
                            OutBoundDir	= 'WOHoldOn'
                            OutRec		= ProdOrdNo:TAB$:'1':CRLF$
                        END
                        
                        IF HoldOnOff = 'OFF_HOLD' THEN
                            OutBoundDir	= 'WOHoldOff'
                            OutRec 		= ProdOrdNo:TAB$:'1':CRLF$
                        END
                        
                        RepoID = ProdOrdNo
            
                        GOSUB SendRecord
                        
                        
                    CASE TransType = 'WO_START'
                    
                        OutBoundDir = 'WOStart'
						ProdOrdNo	= Transaction[1,@FM]
                        StartDt		= Transaction[COL2()+1,@FM]
                        OutRec		= ProdOrdNo:TAB$:StartDt:CRLF$
                        
                        RepoID = ProdOrdNo
                        
                        GOSUB SendRecord
  
                    CASE TransType = 'WO_STOP'
                    
                        OutBoundDir = 'WOStop'
                        
                        ProdOrdNo	= Transaction[1,@FM]
                        StopDt		= Transaction[COL2()+1,@FM]
                        
                        OutRec		= ProdOrdNo:TAB$:StopDt:CRLF$
                        
                        RepoID = ProdOrdNo
                        
                        GOSUB SendRecord
                        
                        
                    
                    CASE TransType = 'PROMISE_DT'								
                        
                        OutBoundDir = 'PromiseDt'
                        
                        ProdOrdNo		= Transaction[1,@FM]
                        OrgPromiseDt	= Transaction[COL2()+1,@FM]
                        NewPromiseDt	= Transaction[COL2()+1,@FM]
                        
                        OutRec = ProdOrdNo:TAB$:OrgPromiseDt:TAB$:NewPromiseDt:CRLF$
                        
                        RepoID = ProdOrdNo
            
                        GOSUB SendRecord
                        
                        
                    CASE TransType = 'SET_MU_BOX'								
                        // 01/30/2019   djs     Appears to be no longer in production.
                        OutBoundDir = 'MUCass'
                    
                        ProdOrdNo		= Transaction[1,@FM]
                        CassNo			= Transaction[COL2()+1,@FM]
                        Flag			= Transaction[COL2()+1,@FM]
                    
                        OutRec = ProdOrdNo:TAB$:CassNo:TAB$:Flag:CRLF$
        
                        GOSUB SendRecord
                        
                        
                    CASE TransType = 'WO_MAT_HOLD'
                        
                        OutBoundDir = 'LotHold'
                        
                        SAPBatchNo	= Transaction[1,@FM]						;* SAP Batch No
                        SLoc		= Transaction[COL2()+1,@FM]					;* Storage Location in SAP
                        Flag		= Transaction[COL2()+1,@FM]					;* Flag
                        
                        OutRec = SAPBatchNo:TAB$:SLoc:TAB$:Flag:CRLF$
                        
                        RepoID = SAPBatchNo
                        
                        GOSUB SendRecord
                        
                    CASE TransType = 'SCRAP_IN'

                        OutBoundDir = 'Scrap'
                        Plant       = Transaction[1,@FM]	 
                        Material    = Transaction[COL2()+1,@FM]
                        SAPBatchID  = Transaction[COL2()+1,@FM]
                        TransQty    = Transaction[COL2()+1,@FM] 
                                                                                                                
                        OutRec = Plant:TAB$:Material:TAB$:SAPBatchID:TAB$:TransQty:CRLF$
                        
                        RepoID = SAPBatchID
                        
                        GOSUB SendRecord
                        
                    CASE TransType = 'BATCHMOVE_IN'
                                                   
                        OutBoundDir = 'BatchMove'

                        Plant        = Transaction[1,@FM]
                        Material     = Transaction[COL2()+1,@FM]
                        BatchFrom    = Transaction[COL2()+1,@FM]
                        BatchTo      = Transaction[COL2()+1,@FM]
                        StoreLocFrom = Transaction[COL2()+1,@FM]
                        StoreLocTo   = Transaction[COL2()+1,@FM]
                        TransQty     = Transaction[COL2()+1,@FM]
                        
                        OutRec = Plant:TAB$:Material:TAB$:BatchFrom:TAB$:BatchTo:TAB$:StoreLocFrom:TAB$:StoreLocTo:TAB$:TransQty:CRLF$
                                               
                        RepoID = BatchTo
                        
                        GoSub SendRecord
                        
                    CASE TransType EQ 'BATCH_CONV'
                    	
                    	OutBoundDir = 'BatchConv'
                    	
                        Plant        = Transaction[1,@FM]
                        Material     = Transaction[COL2()+1,@FM]
                        SAPBatchNo   = Transaction[COL2()+1,@FM]
                        StoreLocFrom = Transaction[COL2()+1,@FM]
                        StoreLocTo   = Transaction[COL2()+1,@FM]
                        TransQty     = Transaction[COL2()+1,@FM]                    	
                    	
                    	OutRec = Plant:TAB$:Material:TAB$:SAPBatchNo:TAB$:StoreLocFrom:TAB$:StoreLocTo:TAB$:TransQty:CRLF$
                    	
                    	RepoID = SAPBatchNo
                    	
                    	GoSub SendRecord
                        
                    CASE 1
                    
                END CASE
                
                IF ErrorMsg NE '' THEN RETURN	;* Set by SendRecord if there is a problem

                IF ClearFlag = 1 THEN
                    DELETE Buffer,TxSeqNo ELSE Null
                END
            END
            
        REPEAT
        
        * * *  Added 10/20/2015  JCH  * * * 
        
        If Not(Done) Then
            ClearSelect Cursor		;* Clear remaining SELECT list if READNEXT loop doesn't finish
        End
        
    END ELSE
        ErrorMsg = 'Unable to open "VISION_COMM" for transmission'
        RETURN
    END

RETURN


* * * * * * * * * * * * * * * * * * * * * * *
* Private Methods
* * * * * * * * * * * * * * * * * * * * * * *

* * * * * * *
SendRecord:
* * * * * * * 

    GOSUB DirNextSeq

    IF ErrorMsg NE '' THEN RETURN

    TransFileName	= 'TX':FMT(DirNextSeqNo,"R(0)#6"):'.tsv'
    TempFileName    = TransFileName[1, 'F.']
    TempFileName   := '.tmp'
    TempDosTable    = TransFilePathOut:'\':TempFileName
    DosTable        = TransFilePathOut:'\':TransFileName
    FTPRootPath     = Environment_Services('GetFTPRootPath')

    IF TransLogOn = 1 THEN
        LTType = 'TX'      
        GOSUB LogTrans				;* Added 12/12/2011 JCH for transaction logging
    END

    ExternalDate = OConv(Date(), 'D')
    Swap ' ' with '_' in ExternalDate
    ExternalTime = OConv(Time(), 'MTS')
    Swap ':' with '_' in ExternalTime
    RepoFileName = ExternalDate:'_':ExternalTime:'_':RepoID:'_':TransFileName
    RepoDir = FTPRootPath : '\FTP_OUT_REPOSITORY\':OutBoundDir:'\':RepoFileName
    OSWrite OutRec ON RepoDir
    OSWrite OutRec on DosTable
    OSWrite OutRec on TempDosTable 

    ToSAPScript  = BaseToSAPScript
    ToSAPScript := 'cd ToSAP':CRLF$
    ToSAPScript := 'cd ':OutBoundDir:CRLF$
    ToSAPScript := 'put ':TempDosTable:CRLF$
    // Added on 02/11/19 to save a copy of SAP files that we place on the ftp server for verfication purposes
    ToSAPScript := 'lcd ':FTPRootPath:'\FTP_OUT_VERIFY\':OutBoundDir:CRLF$
    ToSAPScript := 'get ':TempFileName:' ':RepoFileName:CRLF$
    // Added on 4/2/19 to work with SAP's tmp filename convention
    ToSAPScript := 'ren ':TempFileName:' ':TransFileName:CRLF$
    // ------------------------------------------------------------------------------------------------------ 
    ToSAPScript := 'bye':CRLF$

    OSWrite ToSAPScript ON ToSAPScriptName
    StartTime = Time()
    DELETE Buffer,TxSeqNo ELSE Null
    Stat    = 'VAR'
    
    FTPCommand = "psftp ":FTPUser:"@":FTPServerIP:" -pw ":FTPPassword:" -b ":ToSAPScriptName:" -batch"
    SRP_Run_Command(FTPCommand, stat, '', '')
    
    LogData    = ''
    LogData<1> = LoggingDtm
    LogData<2> = stat
    Logging_Services('AppendLog', objSapOutboundSftpLog, LogData, @RM, @FM)
    
    GoSub CheckForErrors
    
    If SftpError then
    	// Send Email to FI_SUPPORT group
		Recipients   = ''
		SentFrom     = 'System'
		Subject      = 'Outbound SFTP error in obj_SAP'
		Message      = 'SFTP output: ':CRLF$:stat
		AttachWindow = ''
		AttachKey    = ''   
		SendToGroup  = 'FI_SUPPORT'
		Parms = Recipients:@RM:SentFrom:@RM:Subject:@RM:Message:@RM:AttachWindow:@RM:AttachKey:@RM:SendToGroup
		obj_Notes('Create',Parms)    	
    	Mona_Services('PostStatus', MonaOutboundResource, 'SFTP-Interface-Outbound', 'critical')
    end else
    	Mona_Services('PostStatus', MonaOutboundResource, 'SFTP-Interface-Outbound', 'ok')
    end    
    
    StopTime = Time()
    ClearFlag = 1
    OSDelete DosTable		;* Removes table from C: drive 

RETURN


* * * * * * *
ReadInbound:
* * * * * * * 

* * * * * *   Production Orders Released -> Create Work Orders   * * * * * *

    FromSAPScript  = BaseFromSAPScript
    FromSAPScript := 'lcd ProdOrdRel':CRLF$		;* Change local directory to EnvPath:ProdOrdRel
    FromSAPScript := 'cd FromSAP':CRLF$			;* Change remote directory to FromSAP
    FromSAPScript := 'cd ProdOrdRel':CRLF$		;* Change remote directory to FromSAP\ProdOrdRel
    FromSAPScript := 'mget *.tsv':CRLF$			;* Copy files from remote to local directory
    FromSAPScript := CRLF$						;* FTP expects a CRLF for each file transferred
    FromSAPScript := CRLF$
    FromSAPScript := 'bye':CRLF$
    
    OSWrite FromSAPScript ON FromSAPScriptName

    StartTime = Time()

    stat       = "VAR"
    
    FTPCommand = "psftp ":FTPUser:"@":FTPServerIP:" -pw ":FTPPassword:" -b ":FromSAPScriptName:" -batch"
    SRP_Run_Command(FTPCommand, stat, '', '')
    
    LogData    = ''
    LogData<1> = LoggingDtm
    LogData<2> = stat
    Logging_Services('AppendLog', objSapInboundSftpLog, LogData, @RM, @FM)    
    
    GoSub CheckForErrors
    
    If SftpError then
    	// Send Email to FI_SUPPORT group
		Recipients   = ''
		SentFrom     = 'System'
		Subject      = 'Inbound SFTP error in obj_SAP'
		Message      = 'SFTP output: ':CRLF$:stat
		AttachWindow = ''
		AttachKey    = ''   
		SendToGroup  = 'FI_SUPPORT'
		Parms = Recipients:@RM:SentFrom:@RM:Subject:@RM:Message:@RM:AttachWindow:@RM:AttachKey:@RM:SendToGroup
		obj_Notes('Create',Parms)    	
    	Mona_Services('PostStatus', MonaInboundResource, 'SFTP-Interface-Inbound', 'critical')
    end else
    	Mona_Services('PostStatus', MonaInboundResource, 'SFTP-Interface-Inbound', 'ok')
    end    
    
    StopTime = Time()

    IF StopTime - StartTime > 60 Then
        ErrorMsg = 'FTP method "ReadInbound" Execution Time > 60 seconds'	
    END

    * * * * *   SAP Batch Numbers returned  * * * * *

    FromSAPScript    = BaseFromSAPScript
    FromSAPScript	:= 'lcd Batch':CRLF$			;* Change local directory to \Batch subdirectory
    FromSAPScript	:= 'cd FromSAP':CRLF$			;* Change remote directory to FromSAP
    FromSAPScript	:= 'cd Batch':CRLF$				;* Change remote directory to FromSAP\Batch
    FromSAPScript	:= 'mget *.tsv':CRLF$			;* Copy files from remote to local directory
    FromSAPScript	:= CRLF$						;* FTP expects a CRLF for each file transferred
    FromSAPScript	:= CRLF$
    FromSAPScript	:= 'bye':CRLF$

    OSWrite FromSAPScript ON FromSAPScriptName

    StartTime = Time()

    stat = "VAR"
    
    FTPCommand = "psftp ":FTPUser:"@":FTPServerIP:" -pw ":FTPPassword:" -b ":FromSAPScriptName:" -batch"
    SRP_Run_Command(FTPCommand, stat, '', '')
    
    LogData    = ''
    LogData<1> = LoggingDtm
    LogData<2> = stat
    Logging_Services('AppendLog', objSapInboundSftpLog, LogData, @RM, @FM)  
    
    GoSub CheckForErrors
    
    If SftpError then
    	// Send Email to FI_SUPPORT group
		Recipients   = ''
		SentFrom     = 'System'
		Subject      = 'Inbound SFTP error in obj_SAP'
		Message      = 'SFTP output: ':CRLF$:stat
		AttachWindow = ''
		AttachKey    = ''   
		SendToGroup  = 'FI_SUPPORT'
		Parms = Recipients:@RM:SentFrom:@RM:Subject:@RM:Message:@RM:AttachWindow:@RM:AttachKey:@RM:SendToGroup
		obj_Notes('Create',Parms)    	
    	Mona_Services('PostStatus', MonaInboundResource, 'SFTP-Interface-Inbound', 'critical')
    end else
    	Mona_Services('PostStatus', MonaInboundResource, 'SFTP-Interface-Inbound', 'ok')
    end    
    
    StopTime = Time()

    IF StopTime - StartTime > 60 Then
        ErrorMsg = 'FTP method "ReadInbound" Execution Time > 60 seconds'	
    END

    * * * * * *   Shipment Release   * * * * * * *

    FromSAPScript  = BaseFromSAPScript
    FromSAPScript := 'lcd ShipRel':CRLF$		;* Change local directory to C:\FTP_IN\ShipRel
    FromSAPScript := 'cd FromSAP':CRLF$			;* Change remote directory to FromSAP
    FromSAPScript := 'cd ShipRel':CRLF$			;* Change remote direcotry to FromSAP\ShipRel
    FromSAPScript := 'mget *.tsv':CRLF$			;* Copy files from remote to local directory
    FromSAPScript := 'bye':CRLF$

    OSWrite FromSAPScript ON FromSAPScriptName

    StartTime = Time()
    
    stat = "VAR"
    
    FTPCommand = "psftp ":FTPUser:"@":FTPServerIP:" -pw ":FTPPassword:" -b ":FromSAPScriptName:" -batch"
    SRP_Run_Command(FTPCommand, stat, '', '')
    
    LogData    = ''
    LogData<1> = LoggingDtm
    LogData<2> = stat
    Logging_Services('AppendLog', objSapInboundSftpLog, LogData, @RM, @FM)      
    
    GoSub CheckForErrors
    
    If SftpError then
    	// Send Email to FI_SUPPORT group
		Recipients   = ''
		SentFrom     = 'System'
		Subject      = 'Inbound SFTP error in obj_SAP'
		Message      = 'SFTP output: ':CRLF$:stat
		AttachWindow = ''
		AttachKey    = ''   
		SendToGroup  = 'FI_SUPPORT'
		Parms = Recipients:@RM:SentFrom:@RM:Subject:@RM:Message:@RM:AttachWindow:@RM:AttachKey:@RM:SendToGroup
		obj_Notes('Create',Parms)    	
    	Mona_Services('PostStatus', MonaInboundResource, 'SFTP-Interface-Inbound', 'critical')
    end else
    	Mona_Services('PostStatus', MonaInboundResource, 'SFTP-Interface-Inbound', 'ok')
    end    
    
    StopTime = Time()

    IF StopTime - StartTime > 60 Then
        ErrorMsg = 'FTP method "ReadInbound" Execution Time > 60 seconds'	
    END

RETURN


* * * * * * *
ClearInbound:
* * * * * * *

    FromSAPScript  = BaseFromSAPScript
    FromSAPScript := 'lcd ':SubDirectory:CRLF$
    FromSAPScript := 'cd FromSAP':CRLF$
    FromSAPScript := 'cd ':SubDirectory:CRLF$
    FromSAPScript := 'delete ':Filename:CRLF$
    FromSAPScript := 'bye':CRLF$


    OSWrite FromSAPScript ON FromSAPScriptName
    OSWrite FromSAPScript ON FTPScriptPath:'InboundDelScript.TXT'

    StartTime = Time()

    stat = "VAR"
    
    FTPCommand = "psftp ":FTPUser:"@":FTPServerIP:" -pw ":FTPPassword:" -b ":FromSAPScriptName:" -batch"
    SRP_Run_Command(FTPCommand, stat, '', '')
    
    LogData    = ''
    LogData<1> = LoggingDtm
    LogData<2> = stat
    Logging_Services('AppendLog', objSapInboundSftpLog, LogData, @RM, @FM)    
    
    GoSub CheckForErrors
    
    If SftpError then
    	// Send Email to FI_SUPPORT group
		Recipients   = ''
		SentFrom     = 'System'
		Subject      = 'Inbound SFTP error in obj_SAP'
		Message      = 'SFTP output: ':CRLF$:stat
		AttachWindow = ''
		AttachKey    = ''   
		SendToGroup  = 'FI_SUPPORT'
		Parms = Recipients:@RM:SentFrom:@RM:Subject:@RM:Message:@RM:AttachWindow:@RM:AttachKey:@RM:SendToGroup
		obj_Notes('Create',Parms)    	
    	Mona_Services('PostStatus', MonaInboundResource, 'SFTP-Interface-Inbound', 'critical')
    end else
    	Mona_Services('PostStatus', MonaInboundResource, 'SFTP-Interface-Inbound', 'ok')
    end    
    
    StopTime = Time()

    IF StopTime - StartTime > 180 THEN
        ErrorMsg = 'FTP Process Exceeded 10 seconds in ClearInbound'
        RETURN
    END

RETURN


* * * * * * *
DirNextSeq:
* * * * * * * 

    * Expects Variable 'OutBoundDir' to be set

    ToSAPScript  = BaseToSAPScript
    ToSAPScript	:= 'lcd ':TransFilePathOut:CRLF$
    ToSAPScript := 'cd ToSAP':CRLF$
    ToSAPScript := 'cd ':OutBoundDir:CRLF$
    ToSAPScript := 'ls *.tsv':CRLF$
    ToSAPScript := 'bye':CRLF$

    OSWrite ToSAPScript ON ToSAPScriptName

    StartTime = Time()

    stat = "VAR"
    
    FTPCommand = "psftp ":FTPUser:"@":FTPServerIP:" -pw ":FTPPassword:" -b ":ToSAPScriptName:" -batch"
    SRP_Run_Command(FTPCommand, stat, '', '')
    
    LogData    = ''
    LogData<1> = LoggingDtm
    LogData<2> = stat
    Logging_Services('AppendLog', objSapOutboundSftpLog, LogData, @RM, @FM)    
    
    GoSub CheckForErrors
    
    If SftpError then
    	// Send Email to FI_SUPPORT group
		Recipients   = ''
		SentFrom     = 'System'
		Subject      = 'Outbound SFTP error in obj_SAP'
		Message      = 'SFTP output: ':CRLF$:stat
		AttachWindow = ''
		AttachKey    = ''   
		SendToGroup  = 'FI_SUPPORT'
		Parms = Recipients:@RM:SentFrom:@RM:Subject:@RM:Message:@RM:AttachWindow:@RM:AttachKey:@RM:SendToGroup
		obj_Notes('Create',Parms)    	
    	Mona_Services('PostStatus', MonaOutboundResource, 'SFTP-Interface-Outbound', 'critical')
    end else
    	Mona_Services('PostStatus', MonaOutboundResource, 'SFTP-Interface-Outbound', 'ok')
    end    
    
    StopTime = Time()

    IF StopTime - StartTime > 30 THEN
        ErrorMsg = 'FTP Process Exceeded 30 seconds in DirNextSeq'
        RETURN
    END

	OSWrite stat on TransFilePathOut:'\OutDir.txt'

    OSRead FileNames FROM TransFilePathOut:'\OutDir.txt' THEN
     
		// Swap Carriage Return + Line feed with @FM
		SWAP \0D0A\ WITH @FM IN FileNames	

        // Delete the verbose lines (e.g., using user ..., changing directory)
        For LineNo = 1 to 7
        	FileNames = Delete(FileNames, 1, 0, 0)
        Next LineNo
        
        FileNames[-1,1] = ''					;* Trailing delimiter
        LastSeq         = ''
        For each Line in FileNames using @FM setting fPos
        	FileName = Line[-1, 'B ']
            IF FileName[1,8] MATCHES "'TX'0N" THEN
                SeqNo = ABS(FileName[3,'.'])
                IF SeqNo > LastSeq THEN
                    LastSeq = SeqNo
                END
            END        	
        Next Line
        
        DirNextSeqNo = LastSeq + 1
    END ELSE
        DirNextSeqNo = 1
    END

RETURN


* * * * * * *
LogTrans:
* * * * * * *

    LTKey = NextKey('SAP_COMM_LOG')

    LogRec = ''

    LogRec<SAP_COMM_LOG_LOG_DTM$>   = ICONV(OCONV(Date(),'D4/'):' ':OCONV(Time(),'MTS'),'DT')

    IF LTType = 'TX' THEN
        LogRec<SAP_COMM_LOG_TYPE$>		= LTType
        LogRec<SAP_COMM_LOG_DOS_PATH$>	= DOSTable
        LogRec<SAP_COMM_LOG_FILENAME$>	= TransFileName
        
        LogDosFile = OutRec
        CONVERT 'CRLF$' TO '' IN LogDosFile
        
        LogRec<SAP_COMM_LOG_DOS_FILE$>	= LogDosFile
        LogRec<SAP_COMM_LOG_TRANS$>		= TransType
    END ELSE
        LogRec<SAP_COMM_LOG_TYPE$>		= LTType
        LogRec<SAP_COMM_LOG_DOS_PATH$>	= InboundPath
        LogRec<SAP_COMM_LOG_FILENAME$>	= FileName
        
        LogDosFile = FileIn
        CONVERT 'CRLF$' TO '' IN LogDosFile
        
        LogRec<SAP_COMM_LOG_DOS_FILE$>	= LogDosFile
        LogRec<SAP_COMM_LOG_TRANS$>		= Trans
    END

    WRITE LogRec ON LogFile,LTKey ELSE NULL

RETURN


* * * * * * * *
CheckForErrors:
* * * * * * * *

	// Expects "stat" to be populated with output from psftp call via SRP_Run_Command
	// Looking for keywords from a list of errors in psftp's (i.e., Putty) documentation.
	// See https://documentation.help/PuTTY/errors.html
	
	Begin Case
		Case IndexC(stat, "host key", 1)
			SftpError = True$
		Case IndexC(stat, "WARNING", 1)
			SftpError = True$
		Case IndexC(stat, "SSH protocol", 1)
			SftpError = True$
		Case IndexC(stat, "cipher", 1)
			SftpError = True$
		Case IndexC(stat, "disconnect", 1)
			SftpError = True$
		Case IndexC(stat, "memory", 1)
			SftpError = True$
		Case IndexC(stat, "Unable to use", 1)
			SftpError = True$
		Case IndexC(stat, "Server refused", 1)
			SftpError = True$
		Case IndexC(stat, "Access denied", 1)
			SftpError = True$
		Case IndexC(stat, "No Supported authentication", 1)
			SftpError = True$
		Case IndexC(stat, "Incorrect CRC", 1)
			SftpError = True$
		Case IndexC(stat, "garbled", 1)
			SftpError = True$
		Case IndexC(stat, "proxy", 1)
			SftpError = True$
		Case IndexC(stat, "error", 1)
			SftpError = True$
		Case IndexC(stat, "unknown command", 1)
			SftpError = True$
		Case Otherwise$
			SftpError = False$
	End Case

return 

