Function SAP_Services(@Service, @Params)
/***********************************************************************************************************************

    This program is proprietary and is not to be used by or disclosed to others, nor is it to be copied without written
    permission from Infineon

    Name        :   SAP_Services

    Description :   Handler program for all module related services.

    Notes       :   The generic parameters should contain all the necessary information to process the services. Often
                    this will be information like the data Record and Key ID.

    Parameters  :
        Service         [in] -- Name of the service being requested
        Param1-10   [in/out] -- Additional request parameter holders
        Response       [out] -- Response to be sent back to the Controller (MCP) or requesting procedure

    Metadata    :

    History     :   (Date, Initials, Notes)
        08/08/17    dmb     Original programmer. - [EPIOI-8]

***********************************************************************************************************************/

#pragma precomp SRP_PreCompiler

$insert APP_INSERTS
$insert SERVICE_SETUP
$insert WO_MAT_EQUATES
$insert PROD_VER_EQUATES
$insert WO_LOG_EQUATES
$insert COMPANY_EQUATES
$insert SEMI_VEND_CODE_EQUATES
$insert WM_OUT_EQUATES
$Insert SAP_MU_TRANS_EQUATES
$Insert NOTIFICATION_EQUATES
$Insert EPI_PART_EQUATES

Equ Comma$ to ','
Equ new_exist$ To 0 ; * Reduce Mode 0
Equ next_cur$  To 1
Equ add_exist$ to 2

Declare subroutine  Error_Services, SAP_Services, Memory_Services, RList, Database_Services, obj_SAP, Logging_Services
Declare subroutine  ErrLog, Obj_Notes, Set_Status, Obj_Tables, Obj_Post_Log, Mona_Services, Reduce
Declare function    SRP_Array, SAP_Services, Memory_Services, Database_Services, SRP_Sort_Array, Work_Order_Services
Declare function    SRP_Math, SRP_Hash, Obj_WO_Mat, Obj_Tables, GaN_Services, Environment_Services, Logging_Services
Declare function    Date_Services, SRP_Datetime

LogPath         = Environment_Services('GetApplicationRootPath') : '\LogFiles\SAP'
LogDate         = Oconv(Date(), 'D4/')
LogTime         = Oconv(Time(), 'MTS')
LogFileName     = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' BatchConv Call Log.csv'
Headers         = 'Logging DTM' : @FM : 'WOMatKey' : @FM : 'SAPBatchNo' : @FM : 'StorLocFrom' : @FM : 'StorLocTo' : @FM : 'BatchQty'
objLogBatchConv = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, Comma$, Headers, '', False$, False$)
LoggingDTM      = LogDate : ' ' : LogTime   ; // Logging DTM

LogPath           = Environment_Services('GetApplicationRootPath') : '\LogFiles\Packaging\AddCassComp'
LogDate           = Oconv(Date(), 'D4/')
LogTime           = Oconv(Time(), 'MTS')
LogFileName       = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' Cass Comp Call Log.csv'
Headers           = 'Logging DTM' : @FM : 'WOMatKey' : @FM : 'SAPBatchNo' : @FM : 'SAPTxDTM' : @FM : 'RejectCassFlag' : @FM : 'Message'
objLogAddCassComp = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, Comma$, Headers, '', False$, False$)
LoggingDTM        = LogDate : ' ' : LogTime   ; // Logging DTM

LogPath                  = Environment_Services('GetApplicationRootPath') : '\LogFiles\Shipping\PrintSpectrumLabel'
LogDate                  = Oconv(Date(), 'D4/')
LogTime                  = Oconv(Time(), 'MTS')
LogFileName              = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' Spectrum Label Printing.csv'
Headers                  = 'Logging DTM' : @FM : 'WOMatKey' : @FM : 'Message'
objLogPrintSpectrumLabel = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, Comma$, Headers, '', False$, False$)
LoggingDTM               = LogDate : ' ' : LogTime   ; // Logging DTM

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

GoToService else
    Error_Services('Set', Service : ' is not a valid service request within the ' : ServiceModule : ' services module.')
end

Return Response else ''


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Services
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//----------------------------------------------------------------------------------------------------------------------
// AddBatchConvTransaction
//
// Adds BatchConv transaction to the outbound SAP queue.
//----------------------------------------------------------------------------------------------------------------------
Service AddBatchConvTransaction(WOMatKey)
	
	ErrorMsg = ''
	If WOMatKey NE '' then 
		WOMatRec   = Database_Services('ReadDataRow', 'WO_MAT', WOMatKey)
		If Error_Services('NoError') then
			SAPBatchNo  = WOMatRec<WO_MAT_SAP_BATCH_NO$>
			ReactorType = Xlate('WO_MAT', WOMatKey, 'REACTOR_TYPE', 'X')
			If ReactorType EQ 'EPP' then
				WMOKey    = WOMatRec<WO_MAT_WMO_KEY$>
				MakeupBox = Xlate('WM_OUT', WMOKey, WM_OUT_MAKEUP_BOX$, 'X')
			end else
				MakeupBox  = WOMatRec<WO_MAT_MAKEUP_BOX$>
			end
			If MakeupBox then
				// Moving batch from 0500 to 0400
				StorLocFrom = '0500'
				StorLocTo   = '0400'
			end else
				// Moving batch from 0400 to 0500
				StorLocFrom = '0400'
				StorLocTo   = '0500'
			end
			WONo     = Field(WOMatKey, '*', 1)
			Material = Xlate('WO_LOG', WONo, 'EPI_PART_NO', 'X') 
			BatchQty = obj_WO_Mat('CurrWaferCnt', WOMatKey:@RM:'':@RM:True$)
			obj_SAP('AddTransaction', 'BATCH_CONV':@RM:Material:@RM:SAPBatchNo:@RM:StorLocFrom:@RM:StorLocTo:@RM:BatchQty)
			
			LogMessage = ''
			ErrCode    = ''
			If Get_Status(ErrCode) then
				LogMessage = 'Error in ':Service:' service. obj_SAP("AddTransaction") call failed. Error code: ':ErrCode
				ErrorMsg   = LogMessage
			end else
				LogMessage = 'BatchConv transaction added to outbound SAP queue.'
			end
			LogData    = ''
			LogData<1> = LoggingDTM
			LogData<2> = WOMatKey
			LogData<3> = SAPBatchNo
			LogData<4> = StorLocFrom
			LogData<5> = StorLocTo
			LogData<6> = BatchQty
			LogData<7> = LogMessage
			Logging_Services('AppendLog', objLogBatchConv, LogData, @RM, @FM)
			
			If ErrorMsg NE '' then Error_Services('Add', ErrorMsg)
		end
	end else
		Error_Services('Add', 'Error in ':Service:' service. Null WOMatKey passed in!')
	end
	
end service


//----------------------------------------------------------------------------------------------------------------------
// AddCassCompTransaction
//
// Add a CassComp transaction to the outbound SAP queue.
//----------------------------------------------------------------------------------------------------------------------
Service AddCassCompTransaction(WOMatKey)
    
    WOMatRec    = Database_Services('ReadDataRow', 'WO_MAT', WOMatKey)
    SAPBatchNo  = WOMatRec<WO_MAT_SAP_BATCH_NO$>
    SAPTxDTM    = WOMatRec<WO_MAT_SAP_TX_DTM$>
    RejectCass  = (SAPBatchNo[-1, 1] EQ 'R')
    
    If ( ( (SAPBatchNo EQ '') and (SAPTxDTM EQ '') ) or ( (RejectCass EQ True$) and (SAPTxDTM EQ '') ) ) then
        WONo	    = WOMatKey[1,'*']
        CassNo	    = WOMatKey[COL2()+1,'*']
        ProdOrdNo   = XLATE('WO_LOG', WONo, WO_LOG_PROD_ORD_NO$,'X')
        ReactorType = Xlate('WO_MAT', WOMatKey, 'REACTOR_TYPE', 'X')
        If ReactorType NE 'GAN' then
            GRProps = obj_WO_Mat('GetGRProps',WOMatKey:@RM:WOMatRec)
        end else
            GRProps = GaN_Services('GetGaNGRProps', WOMatKey)
        end       
        
        GRWfrQty		= GRProps[1,@FM]
        ScrapQty		= GRProps[COL2()+1,@FM]
        ProdTWQty		= GRProps[COL2()+1,@FM]
        AvailMUWfrQty	= GRProps[COL2()+1,@FM]
        MUCassIDs		= GRProps[COL2()+1,@FM]
        MUCassQtys		= GRProps[COL2()+1,@FM]
        //Gets the First MU Cass. Used
        MUCassID	= FIELD(MUCassIDs,@VM,1)
        MUCassQty	= FIELD(MUCassQtys,@VM,1)
        MUBatchNo	= XLATE('WO_MAT', MUCassID, WO_MAT_SAP_BATCH_NO$, 'X')
        //Gets all remaining MU Cass. Used
        UnTransCassIDs	= FIELD(MUCassIds, @VM, 1, 25)
        UnTransCassQtys	= FIELD(MUCassQtys, @VM, 1, 25)
        
        IF UnTransCassIDs NE '' THEN
            //Writes them to the SAP_MU_TRANS_TABLE
            otParms  = 'SAP_MU_TRANS':@RM					;* TableName
            otParms := WONo:'*':CassNo:@RM					;* TableKey
            otParms := @RM									;* TableVar
            otParms := UntransCassIDs:@FM:UntransCassQtys	;* TableRecord
            
            obj_Tables('WriteRec', otParms)
        END
        
        SupplierLotNo	= WOMatRec<WO_MAT_LOT_NO$>
        
        IF WOMatRec<WO_MAT_WMO_KEY$> = '' THEN
            CassID		= WOMatRec<WO_MAT_RDS_NO$>[-1,'B':@VM]
            MakeupFlag	= WOMatRec<WO_MAT_MAKEUP_BOX$>
            
        END ELSE
            CassID		= WOMatKey					;* WOMat Key used for WM_OUT as of 2/17/2012 JCH       
            CONVERT '*' TO '.' IN CassID        
            MakeupFlag	= XLATE('WM_OUT', WOMatRec<WO_MAT_WMO_KEY$>, WM_OUT_MAKEUP_BOX$, 'X')
        END    
        IF MakeupFlag = '' THEN MakeupFlag = 0                
        IF MakeupFlag = 1  THEN GRWfrQty   = AvailMUWfrQty   
        IF MUBatchNo NE '' THEN
            IF MakeupFlag = 0 THEN
                MakeupFlag = '-'
            END ELSE
                MakeupFlag = 2
            END
        END       
        
        ProdVerRec = XLATE('PROD_VER', WOMatRec<WO_MAT_PROD_VER_NO$>, '', 'X')
        CustNo	   = ProdVerRec<PROD_VER_CUST_NO$>    
        VendCd	   = XLATE('COMPANY', CustNo, COMPANY_VEND_CD$, 'X')	
        SubPartNo  = ProdVerRec<PROD_VER_SUB_PART_NO$>
        
        IF VendCd NE '' THEN
            SubSuppCd = VendCd
        END ELSE
            IF SubPartNo MATCHES "6N'-'1A'-'2A" THEN
                SubSuppCd = FIELD(SubPartNo,'-',3)
            END ELSE
                SubSuppCd = WOMatRec<WO_MAT_SUB_VEND_CD$>
                SubSuppCd = XLATE('SEMI_VEND_CODE',SubSuppCd,SEMI_VEND_CODE_EPI_VEND_CD$,'X')
            END
        END
        
        CustPartRev	= ProdVerRec<PROD_VER_CUST_PART_REV$>  
        CurrDTM     = ICONV(OCONV(Date(),'D4/'):' ':OCONV(Time(),'MTHS'),'DT')    
        * Getting Records with the DTM missing   
        If CurrDTM = '' Then
            CurrDTM = ICONV(OCONV(Date(),'D4/'):' ':OCONV(Time(),'MTHS'),'DT')
        END
        
        obj_Post_Log('Create','WO_MAT':@RM:WOMatKey:@RM:WO_MAT_SAP_TX_DTM$:@RM:CurrDTM)
        
        * Section for Local generation of SAP_BATCH_NO removed 8/10/2011 JCH
        atParms  = 'CASS_COMP':@RM
        atParms := ProdOrdNo:@RM
        atParms := WONo:@RM
        atParms := CassNo:@RM
        atParms := GRWfrQty:@RM
        atParms := ScrapQty:@RM
        atParms := ProdTWQty:@RM
        atParms := CassID:@RM
        atParms := SupplierLotNo:@RM
        atParms := SubSuppCd:@RM
        atParms := CustPartRev:@RM
        atParms := MakeupFlag
        
        Copy = atParms
        Swap @RM with @FM in Copy
        
        obj_SAP('AddTransaction', atParms)
        LogData    = ''
		LogData<1> = LoggingDTM
		LogData<2> = WOMatKey
		LogData<3> = SAPBatchNo
		LogData<4> = SAPTxDTM
		LogData<5> = RejectCass
		LogData<6> = 'Sent Cass Comp Transaction'
		Logging_Services('AppendLog', objLogAddCassComp, LogData, @RM, @FM)
    end else
    	ErrMsg = 'SAP Batch No already exists for this lot.'
        LogData    = ''
		LogData<1> = LoggingDTM
		LogData<2> = WOMatKey
		LogData<3> = SAPBatchNo
		LogData<4> = SAPTxDTM
		LogData<5> = RejectCass
		LogData<6> = ErrMsg
		Logging_Services('AppendLog', objLogAddCassComp, LogData, @RM, @FM)
        Error_Services('Add', ErrMsg)
    end
    
end service


//----------------------------------------------------------------------------------------------------------------------
// SetInboundPending
//
// Calculates and stores the current inbound pending count for SAP.
//----------------------------------------------------------------------------------------------------------------------
Service SetInboundPending()
    
    hSysLists   = Database_Services('GetTableHandle', 'SYSLISTS')
    Lock hSysLists, ServiceKeyID then
        
        rv       = Set_Status(0)
        LookBack = 15 /* Days */
        
        KeyList   = SAP_Services('GetInboundWOMatKeys', Date() - Lookback)

        RowCount   = DCount(KeyList, @FM)
        StatusCode = ''
        If Get_Status(StatusCode) Then
            Null
        end else
            OutboundPending = SAP_Services('GetOutboundPending')
            InboundPending  = RowCount - OutboundPending
            If InboundPending < 0 then InboundPending = 0
            Database_Services('WriteDataRow', 'APP_INFO', 'INBOUND_PENDING', InboundPending, True$)
            Mona_Services('PostAverageMetric', MonaInboundResource, 'InboundPending', InboundPending)
        end
        ClearSelect 0
        Unlock hSysLists, ServiceKeyID else Null
    end

end service


//----------------------------------------------------------------------------------------------------------------------
// GetInboundPending
//
// Gets the current inbound pending count for SAP.
//----------------------------------------------------------------------------------------------------------------------
Service GetInboundPending()
    
    hSysLists = Database_Services('GetTableHandle', 'SYSLISTS')
    Lock hSysLists, ServiceKeyID then
        InboundPending = Database_Services('ReadDataRow', 'APP_INFO', 'INBOUND_PENDING')
        Response = InboundPending
        Unlock hSysLists, ServiceKeyID else Null
    end
    
end service


//----------------------------------------------------------------------------------------------------------------------
// MonitorSAPOutboundQueue
//
// Monitor each SAP outbound transactions pending and report the current outbound pending count for MonA
//----------------------------------------------------------------------------------------------------------------------
Service MonitorSAPOutboundQueue()
    
    hSysLists = Database_Services('GetTableHandle', 'SYSLISTS')
    Lock hSysLists, ServiceKeyID then
        hSAPComm = Database_Services('GetTableHandle', 'SAP_COMM')
        If Error_Services('NoError') then
            rv = Set_Status(0)
            SelectStatement = 'SELECT SAP_COMM'
            RList(SelectStatement, 5)
            If Get_Status(StatusCode) Then
                Null
            end else
                OutboundPendingScrapIn          = 0
                OutboundPendingInventoryMove    = 0
                OutboundPendingCassetteComplete = 0
                OutboundPendingLotOnHold        = 0
                OutboundPendingLotOffHold       = 0
                OutboundPendingWorkOrderStart   = 0
                EOF = False$
                Loop
                    Readnext SAPCommID else EOF = True$
                Until EOF
                    Read SAPCommRow from hSAPComm, SAPCommID then
                        TransactionType = SAPCommRow<1>
                        Begin Case
                            Case TransactionType _EQC 'SCRAP_IN'
                                OutboundPendingScrapIn += 1
                            Case TransactionType _EQC 'BATCHMOVE_IN'
                                OutboundPendingInventoryMove += 1
                            Case TransactionType _EQC 'CASS_COMP'
                                OutboundPendingCassetteComplete += 1
                            Case TransactionType _EQC 'ON_HOLD'
                                OutboundPendingLotOnHold += 1
                            Case TransactionType _EQC 'OFF_HOLD'
                                OutboundPendingLotOffHold += 1
                            Case TransactionType _EQC 'WO_START'
                                OutboundPendingWorkOrderStart += 1
                        End Case
                    end
                Repeat
                // Output to MonA
                OSFile  = 'SCRAP_IN: '     : OutboundPendingScrapIn            :CRLF$
                OSFile := 'BATCHMOVE_IN: ' : OutboundPendingInventoryMove      :CRLF$
                OSFile := 'CASS_COMP: '    : OutboundPendingCassetteComplete   :CRLF$
                OSFile := 'ON_HOLD: '      : OutboundPendingLotOnHold          :CRLF$
                OSFile := 'OFF_HOLD: '     : OutboundPendingLotOffHold         :CRLF$
                OSFile := 'WO_START: '     : OutboundPendingWorkOrderStart     
                OSWrite OSFile to Environment_Services('GetApplicationRootPath') : '\LogFiles\SAP Outbound Service\Queue.txt'
            end
        end
        ClearSelect 0
        Unlock hSysLists, ServiceKeyID else Null
    end
    
end service


//----------------------------------------------------------------------------------------------------------------------
// SetOutboundPending
//
// Calculates and stores the current outbound pending count for SAP.
//----------------------------------------------------------------------------------------------------------------------
Service SetOutboundPending()
    
    hSysLists = Database_Services('GetTableHandle', 'SYSLISTS')
    Lock hSysLists, ServiceKeyID then
        hSAPComm = Database_Services('GetTableHandle', 'SAP_COMM')
        If Error_Services('NoError') then
            rv = Set_Status(0)
            SelectStatement = 'SELECT SAP_COMM'
            RList(SelectStatement, 5)
            If Get_Status(StatusCode) Then
                Null
            end else
                OutboundPending = 0
                EOF = False$
                Loop
                    Readnext SAPCommID else EOF = True$
                Until EOF
                    Read SAPCommRow from hSAPComm, SAPCommID then
                        TransactionType = SAPCommRow<1>
                        If TransactionType _EQC 'CASS_COMP' then
                            OutboundPending += 1
                        end
                    end
                Repeat
                Database_Services('WriteDataRow', 'APP_INFO', 'OUTBOUND_PENDING', OutboundPending, True$)
                Mona_Services('PostAverageMetric', MonaOutboundResource, 'OutboundPending', OutboundPending)
            end
        end
        ClearSelect 0
        Unlock hSysLists, ServiceKeyID else Null
    end
    
end service


//----------------------------------------------------------------------------------------------------------------------
// GetOutboundPending
//
// Gets the current outbound pending count for SAP.
//----------------------------------------------------------------------------------------------------------------------
Service GetOutboundPending()
    
    hSysLists = Database_Services('GetTableHandle', 'SYSLISTS')
    Lock hSysLists, ServiceKeyID then
        OutboundPending = Database_Services('ReadDataRow', 'APP_INFO', 'OUTBOUND_PENDING')
        Response = OutboundPending
        Unlock hSysLists, ServiceKeyID else Null
    end
    
end service


//----------------------------------------------------------------------------------------------------------------------
// GetInboundTransactions
//
// Gets the incoming SAP transactions and processes them.
//----------------------------------------------------------------------------------------------------------------------
Service GetInboundTransactions()
    
    hSysLists   = Database_Services('GetTableHandle', 'SYSLISTS')
    Lock hSysLists, ServiceKeyID then
        SAPHoldStartDateTime    = SAP_Services('GetSAPHoldStartDateTime')
        SAPHoldStopDateTime     = SAP_Services('GetSAPHoldStopDateTime')
        If (SAPHoldStartDateTime NE '') AND (SAPHoldStopDateTime NE '') AND (SAPHoldStopDateTime GT SAPHoldStartDateTime) then
            CurrentDateTime     = Iconv(Oconv(Date(), 'D4/') : ' ' : Oconv(Time(), 'MTS'), 'DT')
            If (CurrentDateTime GT SAPHoldStartDateTime) AND (CurrentDateTime LT SAPHoldStopDateTime) then
                SAP_Services('SetSAPOutageFlag', 1)
            end else
                SAP_Services('SetSAPOutageFlag', 0)
            end
        end else
            SAP_Services('SetSAPOutageFlag', 0)
        end
        
        SAPOutage   = SAP_Services('GetSAPOutageFlag')
        If Not(SAPOutage) then
            TransLogOn  = SAP_Services('GetTransactionLoggingFlag')
            obj_SAP('GetInbound', TransLogOn)
            If Get_Status(errCode) then
                ErrLog(errCode)			;* ErrLog clears status
                Recipients		= Xlate('NOTIFICATION','SAP_COMM',NOTIFICATION_USER_ID$,'X')
                SentFrom		= 'SAP Comm Server'
                Subject			= 'SAP Communications Server Errors'
                Message			= "Communications Errors logged during 'Get_Inbound' on the SAP Communications Server"
                AttachWindow	= ''
                AttachKey		= ''
                SendToGroup		= ''
                Parms           = Recipients:@RM:SentFrom:@RM:Subject:@RM:Message:@RM:AttachWindow:@RM:AttachKey:@RM:SendToGroup
                obj_Notes('Create',Parms)
                If Get_Status(errCode) then ErrLog(errCode)
            end
        end
        Unlock hSysLists, ServiceKeyID else Null
    end
    
end service


//----------------------------------------------------------------------------------------------------------------------
// SendOutboundTransactions
//
// Sends transactions to the SAP system.
//----------------------------------------------------------------------------------------------------------------------
Service SendOutboundTransactions()
    
    hSysLists   = Database_Services('GetTableHandle', 'SYSLISTS')
    Lock hSysLists, ServiceKeyID then
        
        SAPHoldStartDateTime    = SAP_Services('GetSAPHoldStartDateTime')
        SAPHoldStopDateTime     = SAP_Services('GetSAPHoldStopDateTime')
        If (SAPHoldStartDateTime NE '') AND (SAPHoldStopDateTime NE '') AND (SAPHoldStopDateTime GT SAPHoldStartDateTime) then
            CurrentDateTime     = Iconv(Oconv(Date(), 'D4/') : ' ' : Oconv(Time(), 'MTS'), 'DT')
            If (CurrentDateTime GT SAPHoldStartDateTime) AND (CurrentDateTime LT SAPHoldStopDateTime) then
                SAP_Services('SetSAPOutageFlag', 1)
            end else
                SAP_Services('SetSAPOutageFlag', 0)
            end
        end else
            SAP_Services('SetSAPOutageFlag', 0)
        end
        
        SAPOutage   = SAP_Services('GetSAPOutageFlag')
        If Not(SAPOutage) then
            TransLogOn  = SAP_Services('GetTransactionLoggingFlag')
            TransQty    = SAP_Services('GetSAPTransactionLimit')
            obj_SAP('SendOutbound',TransLogOn:@RM:TransQty)		;* Transmit transactions to the SAP system
            If Get_Status(errCode) then
                ErrLog(errCode)			;* ErrLog clears status
                Recipients		= Xlate('NOTIFICATION','ORDER_ENTRY',NOTIFICATION_USER_ID$,'X')
                SentFrom		= 'SAP Comm Server'
                Subject			= 'SAP Communications Server Errors'
                Message			= "Communications Errors logged during 'SendOutbound' on the SAP Communications Server"
                AttachWindow	= ''
                AttachKey		= ''
                SendToGroup		= ''
                Parms           = Recipients:@RM:SentFrom:@RM:Subject:@RM:Message:@RM:AttachWindow:@RM:AttachKey:@RM:SendToGroup
                obj_Notes('Create', Parms)
                If Get_Status(errCode) then ErrLog(errCode)                
            end
        end
        HeartbeatDTM = SRP_Datetime('Now')
        Database_Services('WriteDataRow', 'APP_INFO', 'SAP_HEARTBEAT_DTM', HeartbeatDTM, True$, False%, True$)
        Unlock hSysLists, ServiceKeyID else Null
    end
    
end service


//----------------------------------------------------------------------------------------------------------------------
// SendReconcile
//
// Sends reconcile transactions to the SAP system.
//----------------------------------------------------------------------------------------------------------------------
Service SendReconcile()
    
    obj_SAP('SendReconcile')
    
end service


//----------------------------------------------------------------------------------------------------------------------
// SetTransactionLoggingFlag
//
// Sets the transaction logging flag for SAP transactions.
//----------------------------------------------------------------------------------------------------------------------
Service SetTransactionLoggingFlag(TransactionLoggingFlag)
    
    If TransactionLoggingFlag NE '' then
        Database_Services('WriteDataRow', 'APP_INFO', 'TRANSACTION_LOGGING_FLAG', TransactionLoggingFlag)
    end else
        Error_Services('Add', 'TransactionLoggingFlag argument was missing in the ' : Service : '. service.')
    end
    
end service


//----------------------------------------------------------------------------------------------------------------------
// GetTransactionLoggingFlag
//
// Gets the transaction logging flag for SAP transactions.
//----------------------------------------------------------------------------------------------------------------------
Service GetTransactionLoggingFlag()
    
    TransactionLoggingFlag = Database_Services('ReadDataRow', 'APP_INFO', 'TRANSACTION_LOGGING_FLAG')
    Response = TransactionLoggingFlag
    
end service


//----------------------------------------------------------------------------------------------------------------------
// SetSAPOutageFlag
//
// Sets the SAP outage flag.
//----------------------------------------------------------------------------------------------------------------------
Service SetSAPOutageFlag(SAPOutageFlag)
    
    If SAPOutageFlag NE '' then
        Database_Services('WriteDataRow', 'APP_INFO', 'SAP_OUTAGE_FLAG', SAPOutageFlag)
    end else
        Error_Services('Add', 'SAPOutageFlag argument was missing in the ' : Service : '. service.')
    end
    
end service


//----------------------------------------------------------------------------------------------------------------------
// GetSAPOutageFlag
//
// Gets the SAP outage flag.
//----------------------------------------------------------------------------------------------------------------------
Service GetSAPOutageFlag()
    
    SAPOutageFlag = Database_Services('ReadDataRow', 'APP_INFO', 'SAP_OUTAGE_FLAG')
    Response = SAPOutageFlag
    
end service


//----------------------------------------------------------------------------------------------------------------------
// SetSAPTransactionLimit
//
// Sets the SAP transaction limit.
//----------------------------------------------------------------------------------------------------------------------
Service SetSAPTransactionLimit(SAPTransactionLimit)
    
    If SAPTransactionLimit NE '' then
        Database_Services('WriteDataRow', 'APP_INFO', 'SAP_TRANSACTION_LIMIT', SAPTransactionLimit)
    end else
        Error_Services('Add', 'SAPTransactionLimit argument was missing in the ' : Service : '. service.')
    end
    
end service


//----------------------------------------------------------------------------------------------------------------------
// GetSAPTransactionLimit
//
// Gets the SAP transaction limit.
//----------------------------------------------------------------------------------------------------------------------
Service GetSAPTransactionLimit()
    
    SAPTransactionLimit = Database_Services('ReadDataRow', 'APP_INFO', 'SAP_TRANSACTION_LIMIT')
    Response = SAPTransactionLimit
    
end service


//----------------------------------------------------------------------------------------------------------------------
// SetSAPHoldStartDateTime
//
// Sets the SAP hold start date and time.
//----------------------------------------------------------------------------------------------------------------------
Service SetSAPHoldStartDateTime(SAPHoldStartDateTime)
    
    Database_Services('WriteDataRow', 'APP_INFO', 'SAP_HOLD_START_DATE_TIME', SAPHoldStartDateTime)
    
end service


//----------------------------------------------------------------------------------------------------------------------
// GetSAPHoldStartDateTime
//
// Gets the SAP hold start date and time.
//----------------------------------------------------------------------------------------------------------------------
Service GetSAPHoldStartDateTime()
    
    SAPHoldStartDateTime = Database_Services('ReadDataRow', 'APP_INFO', 'SAP_HOLD_START_DATE_TIME')
    Response = SAPHoldStartDateTime
    
end service


//----------------------------------------------------------------------------------------------------------------------
// SetSAPHoldStopDateTime
//
// Sets the SAP hold stop date and time.
//----------------------------------------------------------------------------------------------------------------------
Service SetSAPHoldStopDateTime(SAPHoldStopDateTime)
    
    Database_Services('WriteDataRow', 'APP_INFO', 'SAP_HOLD_STOP_DATE_TIME', SAPHoldStopDateTime)
    
end service


//----------------------------------------------------------------------------------------------------------------------
// GetSAPHoldStopDateTime
//
// Gets the SAP hold stop date and time.
//----------------------------------------------------------------------------------------------------------------------
Service GetSAPHoldStopDateTime()
    
    SAPHoldStopDateTime = Database_Services('ReadDataRow', 'APP_INFO', 'SAP_HOLD_STOP_DATE_TIME')
    Response = SAPHoldStopDateTime
    
end service


Service PrintSpectrumLabel(WONo,StepNo,CassNo)
    EQU SIK_FIXED_DATA$      To 1
    EQU SIK_P_BNR$           TO 2
    EQU SIK_GRVP$            TO 3
    EQU SIK_I_GRVP$          TO 4
    EQU SIK_M_QUANTITY$      TO 5
    EQU SIK_M_QUANTITY1$     TO 6
    EQU SIK_M_LOTNO$         TO 7
    EQU SIK_DATECODE$        TO 8
    EQU SIK_LOTCOUNT$        TO 9
    EQU SIK_SERIALNO$        TO 10
    EQU SIK_M_CODE$          TO 11
    EQU SIK_M_COA$           TO 12
    EQU SIK_P_TEXT2_3$       TO 13
    EQU SIK_P_SALES_PRODUCT$ TO 14
    EQU SIK_BLANK_LINE$      TO 15
    EQU SIK_FIXED_DATA_2$    TO 16
    EQU SIK_LABEL_ID$        TO 17
    EQU SIK_PRT_PORT$        TO 18
    If WONo NE '' AND CassNo NE '' then
        WoMatKey   = WONo : '*' : CassNo
        WOMatRec   = Database_Services('ReadDataRow', 'WO_MAT', WoMatKey)
        SAPBatchNo = WOMatRec<WO_MAT_SAP_BATCH_NO$>
        IF SAPBatchNo NE '' then
        	CurrTime = Time()
            WOLogKey           = WONo
            EpiPartNo          = XLATE('WO_LOG', WOLogKey, WO_LOG_EPI_PART_NO$, 'X')
            ReshipEpiPartNo		= XLATE('WO_MAT', WoMatKey, WO_MAT_RESHIP_CUST_EPI_PART_NO$, 'X')
            IF ReshipEpiPartNo EQ '' then
                EpiPartToUse = EpiPartNo
            end else
                EpiPartToUse = ReshipEpiPartNo
            end
            ZPVMMatNum = XLATE('EPI_PART', EpiPartToUse, EPI_PART_VARM_PART_NO$, 'X')
            If ZPVMMatNum EQ '' then
                ZPVMMatNum = EpiPartToUse
            end
            ZPVMPartDesc = XLATE('EPI_PART', EpiPartToUse, EPI_PART_VARM_DESCRIPTION$ , 'X')
            If ZPVMPartDesc EQ '' then
                ZPVMPartDesc = XLATE('EPI_PART', EpiPartToUse, EPI_PART_EPI_PART_DESC$ , 'X')
            end
            
            ShipDate           = XLATE('WO_MAT', WoMatKey, WO_MAT_SAP_TX_DTM$, 'X')
            ShipYear           = SRP_Datetime('Year', ShipDate)
            ShipYear           = ShipYear[3,4]
            ShipWW             = Date_Services('GetWeekNum', ShipDate)
            ShipDtCd           = ShipYear : ShipWW
            SpectrumFileName   = SAPBatchNo : '-' :CurrTime : '.sik'
            SpectrumDirectory  = XLATE('APP_INFO', 'SPECTRUM_FILE_PATH', 1, 'X')
            SpectrumExportPath = SpectrumDirectory : SpectrumFileName
            CurrWaferCnt        = XLATE('WO_MAT', WoMatKey, 'CURR_WFR_CNT', 'X')

            SikData                       = ''
            SikData<SIK_FIXED_DATA$>      = 'POKE EBSOFTLD.SYSTEM POOL'
            SikData<SIK_P_BNR$>           = 'P_BNR' : Tab$ : ZPVMMatNum
            SikData<SIK_GRVP$>            = 'GRVP' : Tab$ : 1; *Default
            SikData<SIK_I_GRVP$>          = 'I_GRVP' : Tab$ : CurrWaferCnt
            SikData<SIK_M_QUANTITY$>      = 'M_QUANTITY' : Tab$ : CurrWaferCnt
            SikData<SIK_M_QUANTITY1$>     = 'M_QUANTITY1' : Tab$ : CurrWaferCnt
            SikData<SIK_M_LOTNO$>         = 'M_LOTNO' : Tab$ : SAPBatchNo
            SikData<SIK_DATECODE$>        = 'M_DATECODE' : Tab$ : ShipDtCd
            SikData<SIK_LOTCOUNT$>        = 'LOTCOUNT' : Tab$ : 1; *Default
            SikData<SIK_SERIALNO$>        = 'SERIALNO' : Tab$ : 00001; *Default
            SikData<SIK_M_CODE$>          = 'M_COD' : Tab$ : 'US'; *Default
            SikData<SIK_M_COA$>           = 'M_COA' : Tab$ : ''
            SikData<SIK_P_TEXT2_3$>       = 'P_TEXT2_3' : Tab$ : ZPVMPartDesc;
            SikData<SIK_P_SALES_PRODUCT$> = 'P_SALES_PRODUCT' : Tab$ : ZPVMPartDesc;
            SikData<SIK_BLANK_LINE$>      = '';*Intentionally left blank. Example file has a blank line here.
            SikData<SIK_FIXED_DATA_2$>    = 'EXECUTE EBSOFTLD.SYSTEM PRINT'
            SikData<SIK_LABEL_ID$>        = 'LABEL_ID' : Tab$ : 'BPL_CYSC'; *Default
            SikData<SIK_PRT_PORT$>        = 'PRT_PORT' : Tab$ : 'MESOPCNOVP604LBL003';
            swap @FM with CRLF$ in SikData
            Status() = 0
            OSWrite SikData to SpectrumExportPath
            StatusCode = Status()
            If StatusCode EQ 0 then
                SuccessMsg = 'Successfully sent sik file to the spectrum system.' 
                LogData    = ''
                LogData<1> = LoggingDTM
                LogData<2> = WOMatKey
                LogData<3> = SuccessMsg
                Logging_Services('AppendLog', objLogPrintSpectrumLabel, LogData, @RM, @FM)
            end else
                ErrorMsg = ''
                Begin Case
                    Case StatusCode EQ 1
                        ErrorMsg = 'Bad OS filename.'
                    Case StatusCode EQ 2
                        ErrorMsg = 'Access denied by operating system.'
                    Case StatusCode EQ 3
                        ErrorMsg = 'Disk or directory full.'
                    Case StatusCode EQ 4
                        ErrorMsg = 'File does not exist.'
                    Case StatusCode EQ 5
                        ErrorMsg = 'Unknown error.'
                    Case StatusCode EQ 6
                        ErrorMsg = 'Attempt to write to a read-only file.'
                End Case
                LogData    = ''
                LogData<1> = LoggingDTM
                LogData<2> = WOMatKey
                LogData<3> = ErrorMsg
                Logging_Services('AppendLog', objLogPrintSpectrumLabel, LogData, @RM, @FM)
                Error_Services('Add', ErrorMsg)
            end
        end else
            ErrorMsg = 'Error in ':Service:' service. SAP Batch number for WOMat Record ' : WoMatKey : ' does not exist.'
			LogData    = ''
			LogData<1> = LoggingDTM
			LogData<2> = WOMatKey
			LogData<3> = ErrorMsg
			Logging_Services('AppendLog', objLogPrintSpectrumLabel, LogData, @RM, @FM)
            Error_Services('Add', ErrorMsg)
        end
    end else
        ErrorMsg = 'Error in ':Service:' service. WO No or Cass No not provided.'
		LogData    = ''
		LogData<1> = LoggingDTM
		LogData<2> = WOMatKey
		LogData<3> = ErrorMsg
		Logging_Services('AppendLog', objLogPrintSpectrumLabel, LogData, @RM, @FM)
        Error_Services('Add', ErrorMsg)
    end
end service


//----------------------------------------------------------------------------------------------------------------------
// ProcessOutboundHolds
//
// Checks to see if SAP transactions are ready to transmit. This is currently used when an SAP batch number is not yet
// assigned to a work order when the outbound SAP transaction is created. 
//----------------------------------------------------------------------------------------------------------------------
Service ProcessOutboundHolds()
    
    hSysLists = Database_Services('GetTableHandle', 'SYSLISTS')
    Lock hSysLists, ServiceKeyID then
        hSAPHold = Database_Services('GetTableHandle', 'SAP_HOLD')
        If Error_Services('NoError') then
            rv = Set_Status(0)
            SelectStatement = 'SELECT SAP_HOLD BY TRANS_DTM'
            RList(SelectStatement, 5)
            If Get_Status(StatusCode) Then
                Null
            end else
                EOF = False$
                Loop
                    Readnext SAPHoldID else EOF = True$
                Until EOF
                    Read SAPHoldRow from hSAPHold, SAPHoldID then
                        WOMatKey   = SAPHoldRow<2>
                        SAPBatchNo = Xlate('WO_MAT', WOMatKey, 'SAP_BATCH_NO', 'X')
                        If SAPBatchNo NE '' then
                            TransAction    = SAPHoldRow<1>
                            Sloc           = SAPHoldRow<3>
                            NewMatHoldFlag = SAPHoldRow<4>
                            Set_Status(0)
                            obj_SAP('AddTransaction',TransAction:@RM:SAPBatchNo:@RM:Sloc:@RM:NewMatHoldFlag)
                            ErrorCode = ''
                            If Get_Status(ErrorCode) then
                                ErrorMsg = 'Error calling Obj_SAP in the ':Service:' service. Error code: ':ErrorCode
                                Error_Services('Add', ErrorMsg)
                            end else
                                Delete hSAPHold, SAPHoldID else
                                    ErrorMsg = 'Error deleting SAPHold: ':SAPHoldID:' in the ':Service' service.'
                                    Error_Services('Add', ErrorMsg)
                                end
                            end
                        end
                    end
                Repeat                
            end           
        end
        ClearSelect 0
        Unlock hSysLists, ServiceKeyID else Null
    end
    
end service


//----------------------------------------------------------------------------------------------------------------------
// RetransmitCassComp
//
// Input:
//  WOMatKey - [Required]
//
// Retransmits CASS_COMP transactions to SAP. This can be used in the event that a CASS_COMP transaction failed to post
// to SAP.
//----------------------------------------------------------------------------------------------------------------------
Service RetransmitCassComp(WOMatKey)
    
    WONo	    = WOMatKey[1,'*']
    CassNo	    = WOMatKey[COL2()+1,'*']
    
    ProdOrdNo	= XLATE('WO_LOG', WONo, WO_LOG_PROD_ORD_NO$, 'X')
    WOMatRec    = Database_Services('ReadDataRow', 'WO_MAT', WOMatKey)
    
    GRProps = obj_WO_Mat('GetGRProps',WOMatKey:@RM:WOMatRec)
    
    GRWfrQty		= GRProps[1,@FM]
    ScrapQty		= GRProps[COL2()+1,@FM]
    ProdTWQty		= GRProps[COL2()+1,@FM]
    AvailMUWfrQty	= GRProps[COL2()+1,@FM]
    MUCassIDs		= GRProps[COL2()+1,@FM]
    MUCassQtys		= GRProps[COL2()+1,@FM]
    
    MUCassID	= FIELD(MUCassIDs,@VM,1)
    MUCassQty	= FIELD(MUCassQtys,@VM,1)
    MUBatchNo	= XLATE('WO_MAT',MUCassID,WO_MAT_SAP_BATCH_NO$,'X')
    
    UnTransCassIDs	= FIELD(MUCassIds,@VM,2,25)
    UnTransCassQtys	= FIELD(MUCassQtys,@VM,2,25)
    
    IF UnTransCassIDs NE '' THEN
        
        otParms  = 'SAP_MU_TRANS':@RM					;* TableName
        otParms := WONo:'*':CassNo:@RM					;* TableKey
        otParms := @RM									;* TableVar
        otParms := UntransCassIDs:@FM:UntransCassQtys	;* TableRecord
        
        obj_Tables('WriteRec',otParms)
    END
    
    SupplierLotNo	= WOMatRec<WO_MAT_LOT_NO$>
    
    IF WOMatRec<WO_MAT_WMO_KEY$> = '' THEN
        CassID		= WOMatRec<WO_MAT_RDS_NO$>[-1,'B':@VM]
        MakeupFlag	= WOMatRec<WO_MAT_MAKEUP_BOX$>
        
    END ELSE
        CassID		= WOMatKey					;* WOMat Key used for WM_OUT as of 2/17/2012 JCH
        
        CONVERT '*' TO '.' IN CassID
        
        MakeupFlag	= XLATE('WM_OUT',WOMatRec<WO_MAT_WMO_KEY$>,WM_OUT_MAKEUP_BOX$,'X')
    END
    
    IF MakeupFlag = '' THEN MakeupFlag = 0
    
    IF MakeupFlag = 1 THEN GRWfrQty = AvailMUWfrQty
    
    IF MUBatchNo NE '' THEN
        IF MakeupFlag = 0 THEN
            MakeupFlag = '-'
        END ELSE
            MakeupFlag = 2
        END
    END
    
    
    ProdVerRec	= XLATE('PROD_VER',WOMatRec<WO_MAT_PROD_VER_NO$>,'','X')
    CustNo		= ProdVerRec<PROD_VER_CUST_NO$>
    
    VendCd		= XLATE('COMPANY',CustNo,COMPANY_VEND_CD$,'X')	
    
    SubPartNo = ProdVerRec<PROD_VER_SUB_PART_NO$>
    
    IF VendCd NE '' THEN
        SubSuppCd = VendCd
    END ELSE
        IF SubPartNo MATCHES "6N'-'1A'-'2A" THEN
            SubSuppCd = FIELD(SubPartNo,'-',3)
        END ELSE
            SubSuppCd = WOMatRec<WO_MAT_SUB_VEND_CD$>
            SubSuppCd = XLATE('SEMI_VEND_CODE',SubSuppCd,SEMI_VEND_CODE_EPI_VEND_CD$,'X')
        END
    END
    
    CustPartRev	= ProdVerRec<PROD_VER_CUST_PART_REV$>
    
    CurrDTM = ICONV(OCONV(Date(),'D4/'):' ':OCONV(Time(),'MTHS'),'DT')
    
    * Getting Records with the DTM missing
    
    If CurrDTM = '' Then
        CurrDTM = ICONV(OCONV(Date(),'D4/'):' ':OCONV(Time(),'MTHS'),'DT')
    END
    
    oPLParms  = 'WO_MAT':@RM
    oPLParms := WOMatKey:@RM
    oPLParms := WO_MAT_SAP_TX_DTM$:@RM
    oPLParms := CurrDTM
    
    obj_Post_Log('Create',oPLParms)
    
    * Section for Local generation of SAP_BATCH_NO removed 8/10/2011 JCH
    
    atParms  = 'CASS_COMP':@RM
    atParms := ProdOrdNo:@RM
    atParms := WONo:@RM
    atParms := CassNo:@RM
    atParms := GRWfrQty:@RM
    atParms := ScrapQty:@RM
    atParms := ProdTWQty:@RM
    atParms := CassID:@RM
    atParms := SupplierLotNo:@RM
    atParms := SubSuppCd:@RM
    atParms := CustPartRev:@RM
    atParms := MakeupFlag:@RM
    atParms := MUBatchNo:@RM
    atParms := MUCassQty
    
    obj_SAP('AddTransaction',atParms)
    
end service


Service SendUnTransMU(WOMatKey, BatchNo, MUBox)
    
    //First: Get a list of untransacted MU wafers
    UnTransRec = Database_Services('ReadDataRow', 'SAP_MU_TRANS', WOMatKey)
    If UnTransRec<1> NE '' then
        for each MUCass in UnTransRec<SAP_MU_TRANS_MU_CASS_ID$> using @VM setting mPos
            WONo      = Field(WOMatKey, '*', 1)
            Material  = Xlate('WO_LOG', WONo, 'EPI_PART_NO', 'X') 
            BatchFrom = Xlate('WO_MAT', MUCass, 'SAP_BATCH_NO', 'X')
            BatchTo   = BatchNo
            MakeupBox = MUBox
            TransQty  = UnTransRec<SAP_MU_TRANS_MU_CASS_QTY$, mPos>
            If MakeupBox EQ True$ then
                // Current box is a makeup box and new box is a makeup box. We want to update
                // the batch number in SAP.
                SAPSLocFrom     = '0400'
                SAPSLocTo       = '0400'
            end else
                SAPSLocFrom     = '0400'
                SAPSLocTo       = '0500'
            end
            obj_SAP('AddTransaction','BATCHMOVE_IN':@RM:Material:@RM:BatchFrom:@RM:BatchTo:@RM:SAPSLocFrom:@RM:SAPSLocTo:@RM:TransQty)
            ErrCode = ''
            IF NOT(Get_Status(ErrCode)) then
                Database_Services('DeleteDataRow', 'SAP_MU_TRANS', WOMatKey)
            end else
                LogPath       = Environment_Services('GetApplicationRootPath') : '\LogFiles\SAP'
                LogDate       = Oconv(Date(), 'D4/')
                LogTime       = Oconv(Time(), 'MTS')
                LogFileName   = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' SendMUTrans.csv'
                Headers       = 'Logging DTM' : @FM : 'WOMatKey' : @FM : 'BatchFrom' : @FM : 'BatchTo'
                objMuTransLog = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, Comma$, Headers, '', False$, False$)
                LoggingDTM    = LogDate : ' ' : LogTime   ; // Logging DTM
                
                LogData    = ''
                LogData<1> = LoggingDTM
                LogData<2> = WOMatKey
                LogData<3> = BatchFrom
                LogData<4> = BatchTo
                Logging_Services('AppendLog', objMuTransLog, LogData, @RM, @FM)
            end
        Next MUCass
    end
    
end service


Service GetInboundWOMatKeys(LookbackDate)
    
    Set_Status(0)
    If Num(LookbackDate) then LookbackDate = OConv(LookbackDate, 'D4/')
    RowCount  = 0
    KeyList   = ''
    TableName = "WO_MAT"
    Flag      = ""
    Done      = False$
    CursorVar = ""
    
    GoSub ClearCursors
    
    SortList     = "SAP_TX_DT"
    ReduceScript = "WITH {SAP_BATCH_NO} EQ '' AND WITH {SAP_TX_DT} GE '":LookbackDate:"'"
    Mode         = NEXT_CUR$
    
    Reduce(ReduceScript, SortList, Mode, TableName, CursorVar, Flag)
    If Flag then
        Select TableName By SortList Using Cursorvar then
            Loop
                ReadNext key Using Cursorvar By AT Else Done = TRUE$
            Until Done
                KeyList<-1> = Key
            Repeat
        end
    End
    Response = KeyList
    
end service


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Internal GoSubs
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

ClearCursors:
    
    For Counter = 0 To 8
        ClearSelect Counter
    Next Counter
    
return

