Compile function WM_IN_Services(@Service, @Params)
/***********************************************************************************************************************

    Name        :   WM_IN_Services

    Description :   Handler program for all WM_IN services.

    Notes       :   Application errors should be logged using the Error Services module. There are a few methodological
                    assumptions built into way errors are managed which are important to understand in order to properly
                    work with Error Services:

                    - The term 'top' refers to the originating procedure of a call stack and the term 'bottom' refers to
                      the last routine (or the current routine) within a call stack. Within the OpenInsight Debugger
                      this will appear backwards since the originating procedure always appears at the bottom of the
                      list and the current routine appears at the top of the list. We are using this orientation because
                      it is common to refer to the process of calling other procedures as 'drilling down'.

                    - The reason for defining the orientation of the call stack is because Error_Services allows for
                      multiple error conditions to be appended to an original error. In most cases this will happen when
                      a procedure at the bottom of the stack generates an error condition and then returns to its
                      calling procedure. This higher level procedure can optionally add more information relevant to
                      itself. This continues as the call stack 'bubbles' its way back to the top to where the
                      originating procedure is waiting.

                    - Native OpenInsight commands that handle errors (e.g., Set_Status, Set_FSError, Set_EventStatus)
                      preserve their error state until explicitly cleared. This can hinder the normal execution of code
                      since subsequent procedures (usually SSPs) will fail if a pre-existing error condition exists.
                      Our philosophy is that error conditions should automatically be cleared before a new procedure
                      is executed to avoid this problem. However, the nature of Basic+ does not make this easy to
                      automate for any given stored procedure. Therefore, if a stored procedure wants to conform to our
                      philosophy then it should include a call into the 'Clear' service request at the top of the
                      program. Alternatively this can be done through a common insert (see SERVICE_SETUP for example.)

                    - Service modules will use the SERVICE_SETUP insert and therefore automatically clear out any
                      error conditions that were set before.

    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)
        9/5/23    djm     Original programmer.

***********************************************************************************************************************/
#pragma precomp SRP_PreCompiler
$insert LOGICAL
$Insert SERVICE_SETUP

$Insert MSG_EQUATES
$Insert DICT_EQUATES
$Insert WM_IN_EQUATES

Declare function   PSN_Services, SRP_Rotate_Array, Datetime, Database_Services, Environment_Services, Logging_Services
Declare subroutine Database_Services, Set_Status, obj_Wo_Mat_Log, Logging_Services, Extract_Si_Keys

GoToService

Return Response or ""

//-----------------------------------------------------------------------------
// SERVICES
//-----------------------------------------------------------------------------


//----------------------------------------------------------------------------------------------------------------------
// GetComments
//
// WMINNo - [Required]
//
// Returns a delimited array of all EPP_COMMENT_NOTE, EPP_COMMENT_USER, and EPP_COMMENT_DATE
// associated with a WM_IN record. Note: Dates are returned Oconv'd.
//----------------------------------------------------------------------------------------------------------------------
Service GetComments(WMINNo)
    
    CommentArray = ''
    WMInRow          = Database_Services('ReadDataRow', 'WM_IN', WMInNo)

	CommentDates = Oconv(WMInRow<WM_IN_EPP_COMMENT_DATE$>, 'DT')
    CommentUsers = WMInRow<WM_IN_EPP_COMMENT_USER$>
    Comments = WMInRow<WM_IN_EPP_COMMENT_NOTE$>

    CommentList = CommentDates :@FM: CommentUsers :@FM: Comments
    CommentArray = SRP_Rotate_Array(CommentList)
    Response = CommentArray

End Service


//----------------------------------------------------------------------------------------------------------------------
// AddComment
//
// WMInNo - [Required]
// Comment - [Required]
//
// Adds  an EPP_COMMENT_NOTE, EPP_COMMENT_USER, and EPP_COMMENT_DATE
// to a WM_In record.
//----------------------------------------------------------------------------------------------------------------------
Service AddComment(WMInNo, Comment)
    
    WMInRow          = Database_Services('ReadDataRow', 'WM_IN', WMInNo)
    UserName		= @USER4
    CommentTime		= Datetime()

	OldDates = WMInRow<WM_IN_EPP_COMMENT_DATE$>
	OldUsers = WMInRow<WM_IN_EPP_COMMENT_USER$>
    OldComments = WMInRow<WM_IN_EPP_COMMENT_NOTE$>
       If (OldDates EQ '' AND OldUsers EQ '' AND OldComments EQ '') then
			WMInRow<WM_IN_EPP_COMMENT_DATE$> = CommentTime
			WMInRow<WM_IN_EPP_COMMENT_USER$> = UserName
			WMInRow<WM_IN_EPP_COMMENT_NOTE$> = Comment
       end else
       		WMInRow<WM_IN_EPP_COMMENT_DATE$> = CommentTime  :@VM: OldDates
			WMInRow<WM_IN_EPP_COMMENT_USER$> = UserName :@VM: OldUsers
			WMInRow<WM_IN_EPP_COMMENT_NOTE$> = Comment :@VM: OldComments
       end
	Database_Services('WriteDataRow', 'WM_IN', WMInNo, WMInRow, 1, 0, 0)
	
End Service


Service SetVoidFlag(WMInKey, Username)
    
	ErrorMessage = ''
	If RowExists('WM_IN', WMInKey) then
			WMInRec = Database_Services('ReadDataRow', 'WM_IN', WMInKey, True$, 0, False$)
			If Error_Services('NoError') then
				WMInRec<WM_IN_VOID$> = True$
				Database_Services('WriteDataRow', 'WM_IN', WMInKey, WMInRec, True$, False, False$)
				If Error_Services('NoError') then
				    Set_Status(0)
					WONo = Field(WMInKey, '*', 1)
                    CassNo = Field(WMInKey, '*', 3)
                    WOMLParms = ''
                    LogFile	= 'WO_MAT'					; WOMLParms  = LogFile:@RM
                    LogDTM	= OConv(Datetime(), 'DT')	; WOMLParms := LogDTM:@RM
                    Action	= 'WM_IN_VOID'				; WOMLParms := Action:@RM
                    WhCd	= 'CR'						; WOMLParms := WhCd:@RM
                    LocCd	= 'VOID'					; WOMLParms := LocCd:@RM
                    WONos	= WONo						; WOMLParms := WONos:@RM
                    CassNos	= CassNo					; WOMLParms := CassNos:@RM
                    UserID	= Username					; WOMLParms := UserID:@RM
                    Tags	= ''						; WOMLParms := Tags:@RM
                    ToolID	= ''						; WOMLParms := ToolID:@RM
                    WOMLParms := ''
                    obj_WO_Mat_Log('Create',WOMLParms)
                    IF Get_Status(errCode) THEN
                        ErrorMessage = 'Error writing inventory transactions'
                    end
				end else
				    ErrorMessage = 'Failed to write to the WM_IN record ' : WMInKey : ' while attempting to set void status.'
				end
			end else
				ErrorMessage = 'Failed to read WM_IN record ' : WMInKey : ' while attempting to set void status.'
			end
	end else
		ErrorMessage = 'Invalid WM_IN Key ' : WMInKey : ' passed to SetVoidFlag routine.'
	end
	If ErrorMessage NE '' then
		Error_Services('Add', ErrorMessage)
	end
	
end service


Service VerifyWoStepWMIKeyIndex(WMIKey)
    
    LogPath            = Environment_Services('GetApplicationRootPath') : '\LogFiles\WM_IN'
    LogDate            = Oconv(Date(), 'D4/')
    LogTime            = Oconv(Time(), 'MTS')
    LogFileName        = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' !WM_IN WO_STEP{WM_IN_KEY} Log.csv'
    Headers            = 'Logging DTM':@FM:'WMIKey':@FM:'WOStep':@FM:'Result'
    objVerifyWMIKeyLog = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, COMMA$, Headers, '', False$, False$)
    LoggingDTM         = LogDate : ' ' : LogTime   ; // Logging DTM    
    
    LogData    = ''
    LogData<1> = LoggingDtm
    LogData<2> = WMIKey
    LogData<4> = 'Begin ':Service
    Logging_Services('AppendLog', objVerifyWMIKeyLog, LogData, @RM, @FM)
    
    ErrorMsg = ''
    If WMIKey NE '' then
        If RowExists('WM_IN', WMIKey) then
            WOStepKey = Field(WMIKey, '*', 1, 2)
            If WOStepKey NE '' then
                WOStepWMIKeys = Xlate('WO_STEP', WOStepKey, 'WM_IN_KEYS', 'X')
                LogData<3>    = WOStepKey
                Logging_Services('AppendLog', objVerifyWMIKeyLog, LogData, @RM, @FM)
                Locate WMIKey in WOStepWMIKeys using @VM setting vPos else
                    LogData<4>          = 'WMIKey missing from WO_STEP record. Generating index transaction.'
                    Logging_Services('AppendLog', objVerifyWMIKeyLog, LogData, @RM, @FM)     
                    // Add index transaction to update WM_IN_KEYS relational index (target WO_STEP table)
                    IndexTransactionRow = 'WO_STEP*WM_IN_KEYS*AR':@FM:WMIKey:@FM:"":@FM:WOStepKey:@FM
                    Open "!WM_IN" to BangTable then
                        Lock BangTable, 0 then
                            Read PendingTrans from BangTable, 0 else PendingTrans = '0':@FM
                            PendingTrans := IndexTransactionRow
                            Write PendingTrans on BangTable, 0 then
                                LogData<4> = 'Index transaction successfully added.'
                                Logging_Services('AppendLog', objVerifyWMIKeyLog, LogData, @RM, @FM)     
                            end else
                                ErrorMsg = 'Unable to write index transaction to !WM_IN. ':WMIKey
                            end
                            Unlock BangTable, 0 else ErrorMsg = 'Unable to Open !WM_IN to add index transaction. ':WMIKey
                        end else
                            ErrorMsg = 'Unable to Lock !WM_IN to add index transaction. ':WMIKey
                        end
                    end else
                        ErrorMsg = 'Unable to Open !WM_IN to add index transaction. ':WMIKey
                    end
                end
            end else
                LogData<4> = 'WO_STEP key for WM_IN ':WMIKey:' is null. Nothing to update.'
                Logging_Services('AppendLog', objVerifyWMIKeyLog, LogData, @RM, @FM)                    
            end
        end
    end
    
    If ErrorMsg NE '' then
        LogData<4> = ErrorMsg
        Logging_Services('AppendLog', objVerifyWMIKeyLog, LogData, @RM, @FM)
    end
    
    LogData<4> = 'End ':Service
    Logging_Services('AppendLog', objVerifyWMIKeyLog, LogData, @RM, @FM)
    
    If ErrorMsg NE '' then Error_Services('Add', ErrorMsg)    
    
end service


Service VerifyWOLogWMIKeyIndex(WMIKey)
    
    LogPath                = Environment_Services('GetApplicationRootPath') : '\LogFiles\WM_IN'
    LogDate                = Oconv(Date(), 'D4/')
    LogTime                = Oconv(Time(), 'MTS')
    LogFileName            = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' !WM_IN WM_IN{WO_NO} Log.csv'
    Headers                = 'Logging DTM':@FM:'WMIKey':@FM:'WOStep':@FM:'Result'
    objVerifyWMIWoIndexLog = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, COMMA$, Headers, '', False$, False$)
    LoggingDTM             = LogDate : ' ' : LogTime   ; // Logging DTM    
    
    LogData    = ''
    LogData<1> = LoggingDtm
    LogData<2> = WMIKey
    LogData<4> = 'Begin ':Service
    Logging_Services('AppendLog', objVerifyWMIWoIndexLog, LogData, @RM, @FM)
    
    ErrorMsg = ''
    If WMIKey NE '' then
        If RowExists('WM_IN', WMIKey) then
            WONo = Field(WMIKey, '*', 1, 1)
            If WONo NE '' then
                WOLogRDSKeys = ''
                Extract_Si_Keys('WM_IN', 'WO_NO', WONo, WOLogRDSKeys)
                LogData<3>   = WONo
                Logging_Services('AppendLog', objVerifyWMIWoIndexLog, LogData, @RM, @FM)
                Locate WMIKey in WOLogRDSKeys using @VM setting vPos else
                    LogData<4>          = 'WMIKey missing from Btree index. Generating index transaction.'
                    Logging_Services('AppendLog', objVerifyWMIWoIndexLog, LogData, @RM, @FM)     
                    // Add index transaction to update WO_NO btree index
                    IndexTransactionRow = 'WO_NO':@FM:WMIKey:@FM:"":@FM:WONo:@FM
                    Open "!WM_IN" to BangTable then
                        Lock BangTable, 0 then
                            Read PendingTrans from BangTable, 0 else PendingTrans = '0':@FM
                            PendingTrans := IndexTransactionRow
                            Write PendingTrans on BangTable, 0 then
                                LogData<4> = 'Index transaction successfully added.'
                                Logging_Services('AppendLog', objVerifyWMIWoIndexLog, LogData, @RM, @FM)     
                            end else
                                ErrorMsg = 'Error in ':Service:' service. Unable to write index transaction to !WM_IN. ':WMIKey
                            end
                            Unlock BangTable, 0 else ErrorMsg = 'Error in ':Service:' service. Unable to Open !WM_IN to add index transaction. ':WMIKey
                        end else
                            ErrorMsg = 'Error in ':Service:' service. Unable to Lock !WM_IN to add index transaction. ':WMIKey
                        end
                    end else
                        ErrorMsg = 'Error in ':Service:' service. Unable to Open !WM_IN to add index transaction. ':WMIKey
                    end
                end
            end else
                LogData<4> = 'WONo for WM_IN ':WMIKey:' is null. Nothing to update.'
                Logging_Services('AppendLog', objVerifyWMIWoIndexLog, LogData, @RM, @FM)                    
            end
        end
    end else
        ErrorMsg = 'Error in ':Service:' service. Null WMIKey passed in.'
    end
    
    If ErrorMsg NE '' then
        LogData<4> = ErrorMsg
        Logging_Services('AppendLog', objVerifyWMIWoIndexLog, LogData, @RM, @FM)
    end
    
    LogData<4> = 'End ':Service
    Logging_Services('AppendLog', objVerifyWMIWoIndexLog, LogData, @RM, @FM)
    
    If ErrorMsg NE '' then Error_Services('Add', ErrorMsg)
    
end service


Service VerifyWOMatWMIKeyIndex(WMIKey)
    
    LogPath           = Environment_Services('GetApplicationRootPath') : '\LogFiles\WM_IN'
    LogDate           = Oconv(Date(), 'D4/')
    LogTime           = Oconv(Time(), 'MTS')
    LogFileName       = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' !WM_IN WO_MAT{WMI_KEY} Log.csv'
    Headers           = 'Logging DTM':@FM:'WMIKey':@FM:'WOMatKey':@FM:'Result'
    objVerifyWoMatWmiKeyLog = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, COMMA$, Headers, '', False$, False$)
    LoggingDTM        = LogDate : ' ' : LogTime   ; // Logging DTM    
    
    LogData    = ''
    LogData<1> = LoggingDtm
    LogData<2> = WMIKey
    LogData<4> = 'Begin ':Service
    Logging_Services('AppendLog', objVerifyWoMatWmiKeyLog, LogData, @RM, @FM)
    
    ErrorMsg = ''
    If WMIKey NE '' then
        If RowExists('WM_IN', WMIKey) then
            WOMatKey = Field(WMIKey, '*', 1, 1):'*':Field(WMIKey, '*', 3, 1)
            If WOMatKey NE '' then
                WOMatWMIKey = Xlate('WO_MAT', WOMatKey, 'WMI_KEY', 'X')
                LogData<3> = WOMatKey
                Logging_Services('AppendLog', objVerifyWoMatWmiKeyLog, LogData, @RM, @FM)               
                If WOMatWMIKey EQ '' then
                    LogData<4>          = 'WMIKey missing from WO_MAT record. Generating index transaction.'
                    Logging_Services('AppendLog', objVerifyWoMatWmiKeyLog, LogData, @RM, @FM)     
                    // Add index transaction to update WMI_KEY relational index (target WO_MAT table)
                    IndexTransactionRow = 'WO_MAT*WMI_KEY*TOP':@FM:WMIKey:@FM:"":@FM:WOMatKey:@FM
                    Open "!WM_IN" to BangTable then
                        Lock BangTable, 0 then
                            Read PendingTrans from BangTable, 0 else PendingTrans = '0':@FM
                            PendingTrans := IndexTransactionRow
                            Write PendingTrans on BangTable, 0 then
                                LogData<4> = 'Index transaction successfully added.'
                                Logging_Services('AppendLog', objVerifyWoMatWmiKeyLog, LogData, @RM, @FM)     
                            end else
                                ErrorMsg = 'Unable to write index transaction to !WM_IN. ':WMIKey
                            end
                            Unlock BangTable, 0 else ErrorMsg = 'Unable to Open !WM_IN to add index transaction. ':WMIKey
                        end else
                            ErrorMsg = 'Unable to Lock !WM_IN to add index transaction. ':WMIKey
                        end
                    end else
                        ErrorMsg = 'Unable to Open !WM_IN to add index transaction. ':WMIKey
                    end                        
                end
            end else
                LogData<4> = 'WO_MAT key for WM_IN ':WMIKey:' is null. Nothing to update.'
                Logging_Services('AppendLog', objVerifyWoMatWmiKeyLog, LogData, @RM, @FM)                    
            end
        end
    end
    
    If ErrorMsg NE '' then
        LogData<4> = ErrorMsg
        Logging_Services('AppendLog', objVerifyWoMatWmiKeyLog, LogData, @RM, @FM)
    end
    
    LogData<4> = 'End ':Service
    Logging_Services('AppendLog', objVerifyWoMatWmiKeyLog, LogData, @RM, @FM)
    
    If ErrorMsg NE '' then Error_Services('Add', ErrorMsg)
    
end service

