COMPILE FUNCTION obj_Post_Log(Method,Parms)
/*
	Methods for the Post Log (POST_LOG) table.
	(Input buffer for record updates that must be made
	 even if the record is locked, works like a !file)
    
	05/12/2008 JCH - Initial Coding
	04/22/2019 DJS - Added unlock service statements within POST subroutine wherever an error condition returns
	                 prematurely to prevent POST_LOG service from locking up.
	02/10/2025 DJM - Added additional logging and unlocking logic for WO_MAT records.
     
	Properties:
	
	Methods:
	
	Create(TableName,RecKey,FieldNos,Values)					;* Create new Post Log  entry
	Post(null)													;* Pass null - will attempt to post all transactions in the table
	
*/


DECLARE FUNCTION Get_Status, Msg, Utility, obj_Tables, Get_Property, obj_RDS, Database_Services, Environment_Services
DECLARE FUNCTION Logging_Services, Datetime, SRP_DateTime, GetTickCount
DECLARE SUBROUTINE  Set_Status, Msg, obj_Tables, Send_Dyn, Send_Dyn, RList, obj_WO_Log, Send_Event, obj_RDS
DECLARE SUBROUTINE obj_WO_Mat, Send_Info, obj_Notes, ErrMsg, Logging_Services, Mona_Services


$INSERT POST_LOG_EQUATES
$INSERT WO_MAT_EQUATES
$INSERT RDS_EQU
$INSERT REACT_RUN_EQUATES
$INSERT LOGICAL

EQU CRLF$  TO \0D0A\
Equ Comma$ to ','

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

IsProd = Environment_Services('IsProd')
If IsProd EQ True$ then
	MonaResource        = 'GRP_OPENINSIGHT_MES_OP_FE_OBJPOSTLOG'
	MonaInboundResource = 'GRP_OPENINSIGHT_MES_OP_FE_SAP_INBOUND'
end else
	MonaResource        = 'GRP_OPENINSIGHT_MES_OP_FE_DEV_OBJPOSTLOG'
	MonaInboundResource = 'GRP_OPENINSIGHT_MES_OP_FE_DEV_SAP_INBOUND'
end

ErrTitle = 'Error in Stored Procedure "obj_Post_Log"'
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 = 'Create'			; GOSUB Create
	CASE Method = 'Post'			; GOSUB Post
	
	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


* * * * * * *
Create:
* * * * * * *

TableName		= Parms[1,@RM]
TableKey		= Parms[COL2()+1,@RM]		;* TableKey
FieldNos		= Parms[COL2()+1,@RM]		;* @VM'd list of field numbers to update
FieldDataVals	= Parms[COL2()+1,@RM]		;* @VM'd list of data values
FieldAddMVby	= Parms[COL2()+1,@RM]		;* AR, AL, TOP, or BOT  - insert new data into MV'd field 

IF TableName = ''			THEN ErrorMsg = 'Null parameter "TableName" passed to routine. (':Method:')'
IF TableKey = ''			THEN ErrorMsg = 'Null parameter "TableKey" passed to routine. (':Method:')'
IF FieldNos = ''			THEN ErrorMsg = 'Null parameter "FieldNos" passed to routine. (':Method:')'
IF FieldDataVals = ''		THEN ErrorMsg = 'Null parameter "FieldDataVals" passed to routine. (':Method:')'

IF ErrorMsg NE '' THEN RETURN

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

IF FieldDataVals = 'NULL' THEN FieldDataVals = ''

TransKey = TableName:'*':CurrDtm:'*':TableKey
TransRec = FieldNos:@FM:FieldDataVals:@FM:FieldAddMVby

PlParms = 'POST_LOG':@RM:TransKey:@RM:@RM:TransRec
obj_Tables('WriteRec',PlParms)

If ( (TableName EQ 'WO_MAT') and (FieldNos EQ WO_MAT_SAP_BATCH_NO$) ) then
    // Log SAP Batch No write request
    LogData    = ''
    LogData<1> = LoggingDTM
    LogData<2> = TableKey
    LogData<3> = FieldDataVals
    LogDate<4> = ''
    Logging_Services('AppendLog', objLog, LogData, @RM, @FM)
end

RETURN


* * * * * * *
Post:
* * * * * * *
	
	StartTick = GetTickCount()
    MetricName = 'Post'
	
    hSysLists       = Database_Services('GetTableHandle', 'SYSLISTS')
    ServiceKeyID    = 'Obj_Post_Log*Post'
    Lock hSysLists, ServiceKeyID then

        OPEN 'POST_LOG' TO FileIn ELSE
            ErrorMsg = 'Unable to Open POST_LOG table for Posting.'
            // 4/22/19 Added unlock statement to prevent POST_LOG service from locking up
            Unlock hSysLists, ServiceKeyID else Null
            RETURN
        END

        CursorVar = ''
        SELECT 'POST_LOG' BY 'CREATE_DTM' SETTING CursorVar ELSE
            Status = Set_FSError()
            // 4/22/19 Added unlock statement to prevent POST_LOG service from locking up
            Unlock hSysLists, ServiceKeyID else Null
            RETURN
        END
        
        If @RecCount EQ 0 then Mona_Services('PostStatus', MonaInboundResource, 'SetSAPBatchQueue', 'ok')
        Done = 0
        LOOP
            READNEXT PostLogKey USING CursorVar ELSE Done = 1
        UNTIL Done
            PlParms = 'POST_LOG':@RM:PostLogKey
            PostLogRec = obj_Tables('ReadRec',PlParms)
            
            Send_Info('POST_LOG ':PostLogKey)
            
            LogFile 		= PostLogKey[1,'*']
            thisTransDTM	= PostLogKey[COL2()+1,'*']
            RecKey			= FIELD(PostLogKey,'*',3,99)
            
            IF RowExists(LogFile,RecKey) THEN
                errCode = ''
                UFParms = LogFile:@RM:RecKey:@RM:@RM
                UpdateRec = obj_Tables('ReadRec',UFParms)
                IF Get_Status(errCode) THEN
                    
                    If (Field(PostLogKey, '*', 1) EQ 'WO_MAT') AND ((PostLogRec<POST_LOG_FIELD_NO$, 1> EQ WO_MAT_SAP_BATCH_NO$) OR (PostLogRec<POST_LOG_FIELD_NO$, 1> EQ WO_MAT_SAP_TX_DTM$)) then
                        AllowedTime = SRP_DateTime("AddMinutes", DateTime(), -5)
                        If (Field(PostLogKey, '*', 2)) LT AllowedTime then
                            Resp  = Database_Services('UnlockKeyID', 'WO_MAT', PostLogRec<POST_LOG_REC_KEY1$>)
                            If Resp NE False$ then
                                Mona_Services('PostStatus', MonaInboundResource, 'SetSAPBatchQueue', 'ok')
                            end else
                                Mona_Services('PostStatus', MonaInboundResource, 'SetSAPBatchQueue', 'critical')
                                LogData    = ''
                                LogData<1> = LoggingDTM
                                LogData<2> = TableKey
                                LogData<3> = FieldDataVals
                                LogData<4> = 'Record failed to unlock.'
                                Logging_Services('AppendLog', objLog, LogData, @RM, @FM)
                            end
                        end
                    end
                    Set_Status(0)	;* Cant't get the lock or other problem reading the log rec so just bail
                    obj_Tables('UnlockRec',PlParms)
                END ELSE
                
                    FieldCnt = COUNT(PostLogRec<POST_LOG_FIELD_NO$>,@VM) + (PostLogRec<POST_LOG_FIELD_NO$> NE '')
                    FOR I = 1 TO FieldCnt
                        FieldNo			= PostLogRec<POST_LOG_FIELD_NO$,I>
                        FieldAddMVBy 	= PostLogRec<POST_LOG_FIELD_ADD_MV_BY$,I>
                        
                        IF FieldAddMVBy = '' THEN
                            UpdateRec<FieldNo> = PostLogRec<POST_LOG_FIELD_VALUE$,I>
                        END ELSE
                            NewValue = PostLogRec<POST_LOG_FIELD_VALUE$,I>
                            
                            BEGIN CASE
                                CASE FieldAddMVBy = 'BOT'
                                    
                                    UpdateRec = INSERT(UpdateRec,FieldNo,-1,0,NewValue)
                                    
                                CASE FieldAddMVBy = 'TOP'
                                
                                    UpdateRec = INSERT(UpdateRec,FieldNo,1,0,NewValue)
                                    
                                CASE FieldAddMVBy = 'AR' OR FieldAddMVBy = 'DR' OR FieldAddMVBy = 'AL' OR FieldAddMVBy = 'DL'
                                    
                                    LOCATE NewValue IN UpdateRec<FieldNo> BY FieldAddMVBy USING @VM SETTING Pos ELSE
                                        UpdateRec = INSERT(UpdateRec,FieldNo,Pos,0,NewValue)
                                    END
                                
                            END CASE										
                        END
                    NEXT I
                
                    UFParms = FIELDSTORE(UFParms,@RM,4,0,UpdateRec)
                    obj_Tables('WriteRec',UFParms)
                
                    IF Get_Status(errCode) THEN
                        Set_Status(0)
                        obj_Tables('UnlockRec',PlParms)
                        obj_Tables('UnlockRec',UFParms)
                        ClearSelect CursorVar
                        // 4/22/19 Added unlock statement to prevent POST_LOG service from locking up
                        Unlock hSysLists, ServiceKeyID else Null
                        RETURN
                    END ELSE
                        obj_Tables('DeleteRec',PlParms)
                    END
                END
            END ELSE
                obj_Tables('DeleteRec',PlParms)
            END

        REPEAT
        
        Unlock hSysLists, ServiceKeyID else Null
    end
    
    EndTick = GetTickCount()
    Mona_Services('QueueLatencyAndCountMetrics', MonaResource, MetricName, StartTick, EndTick)

RETURN

