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

    Name        :   Lock_Services

    Description :   Handler program for all Lock 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)
        3/18/24    djm     Original programmer.

***********************************************************************************************************************/
#pragma precomp SRP_PreCompiler
$insert LOGICAL
$Insert SERVICE_SETUP
$Insert UNLOCK_REQUESTS_EQUATES
$Insert REACT_RUN_EQUATES
$Insert WO_MAT_EQUATES
$Insert WM_OUT_EQUATES
$Insert RDS_EQUATES
$Insert RDS_LAYER_EQUATES

Declare function Database_Services, Oi_Wizard_Services, Memberof, Lock_Services, SRP_Json, List_Volume_Sub, Datetime
Declare subroutine SRP_Json, Database_Services


GoToService

Return Response or ""

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


//----------------------------------------------------------------------------------------------------------------------
// GetLockPermissions
//
// CurrUser - [Required]
//
// Returns LockPermissionLevel 0 - No lock access, 1 - Lock access to unprotected tables, or 2 - Lock access to all tables.
//
//----------------------------------------------------------------------------------------------------------------------
Service GetLockPermissions(CurrUser)
	
	LockPermissionLevel = 0
	OIAdmin = Memberof(CurrUser, 'OI_ADMIN')
	SupervisorLead = MemberOf(CurrUser, 'LEAD') OR MemberOf(CurrUser, 'SUPERVISOR')
	If OIAdmin then
		LockPermissionLevel = 2
	end else
		If SupervisorLead then
			LockPermissionLevel = 1
		end
	end
	Response = LockPermissionLevel
	
End Service


//----------------------------------------------------------------------------------------------------------------------
// GetAllowedLocks
//
// CurrUser - [Required]
//
// Returns an array of accessible locks based on user LockPermissionLevel
//
//----------------------------------------------------------------------------------------------------------------------
Service GetAllowedLocks(CurrUser)
	
	LockPermissionLevel = Lock_Services('GetLockPermissions', CurrUser)
	LockJSON = ''
	
	If LockPermissionLevel NE 0 then
		
		LockList = Database_Services('GetUserLocks')
		If Error_Services('NoError') then
			If SRP_JSON(objJSON, 'New', 'Object') then
				If SRP_JSON(LockArray, 'New', 'Array') then
					For each Row in LockList using @FM setting fPos
						If Row<0,3> = "Rev30536" then Row<0,3> = 'RDS*LSL2'
						If Field(Row<0,3>, "*", 2) EQ 'LSL2' OR LockPermissionLevel EQ 2 then
							If SRP_JSON(objRow, 'New', 'Object') then
								SRP_JSON(objRow, 'SetValue', 'ComputerName', Row<0, 1>)
								SRP_JSON(objRow, 'SetValue', 'Volume', Row<0, 2>)
								If Field(Row<0,3>, "*", 2) EQ 'LSL2' then Row<0,3> = Field(Row<0,3>, "*", 1)
								SRP_JSON(objRow, 'SetValue', 'OSFile', Row<0, 3>)
								SRP_JSON(objRow, 'SetValue', 'RecordKey', Row<0, 4>, "String")
								SRP_JSON(objRow, 'SetValue', 'Exclusive', Row<0, 5>)
								SRP_JSON(objRow, 'SetValue', 'REVFile', Row<0, 6>)
								SRP_JSON(LockArray, 'Add', objRow)
								SRP_JSON(objRow, 'Release')
							end
						End
					Next Row
					SRP_JSON(objJSON, 'Set', 'Locks', LockArray)
					SRP_JSON(LockArray, 'Release')
				end
				LockJSON = SRP_JSON(objJSON, 'Stringify', 'Styled')
				SRP_JSON(objJSON, 'Release')
			end
		end
	End
	
	Response = LockJSON
	
End Service

//----------------------------------------------------------------------------------------------------------------------
// AttemptUnlock
//
// CurrUser - [Required]
// LotType - [Required]
// Key - [Required]
//
// Returns either 1 for success, or error message
//
//----------------------------------------------------------------------------------------------------------------------

Service AttemptUnlock(CurrUser, LotType, Key)
    
	LockPermissionLevel = Lock_Services('GetLockPermissions', CurrUser)
	If LockPermissionLevel NE 0 then
		If LotType EQ 'RDS' or LotType EQ 'WM_OUT' then
			If Xlate(LotType, Key, '', 'X', '') NE '' then
				LockArray = Lock_Services('GetChildRecords', LotType, Key)
				LockCount = DCount(LockArray<1>, @VM)
				For I = 1 to LockCount
					Table = LockArray<1,I>
					KeyID = LockArray<2,I>
					Resp  = Database_Services('UnlockKeyID', Table, KeyID)
				Next I
				If Error_Services('NoError') Then
					Response = TRUE$
				end else
					Response = FALSE$
					Error_Services('Add', 'Records failed to unlock.')
				end
			end else
				Response = FALSE$
				Error_Services('Add', 'This record does not exist.')
			end
		End Else
			Response = FALSE$
			Error_Services('Add', 'LotType must be either RDS or WM_OUT.')
		end
	end else
		Response = FALSE$
		Error_Services('Add', 'User is not permitted to access this resource.')
	end
	
End Service


//----------------------------------------------------------------------------------------------------------------------
// GetChildRecords
//
// LotType - [Required]
// Key - [Required]
//
// Returns an array of associated child records for unlocking
//
//----------------------------------------------------------------------------------------------------------------------

Service GetChildRecords(LotType, Key)
	
	RecordArray = ''
	
	Begin Case
		
		Case LotType EQ 'RDS'
			RDSRec = Xlate('RDS', Key, '', 'X', '')
			If RDSRec NE '' then
				//Add RDS key
				RecordArray<1> = LotType
				RecordArray<2> = Key
				//Get REACT_RUN record
				ReactRunRec  = Xlate('REACT_RUN', Key, '', 'X', '')
				//Get and Add CLEAN_INSP keys
				CINos          = ReactRunRec<REACT_RUN_CI_NO$>
				If CINos NE '' then
					CICount = Dcount(CINos, @VM)
					For I = 1 to CICount
						If CINos<I> NE '' then
							RecordArray<1,-1> = 'CLEAN_INSP'
							RecordArray<2,-1> = CINos<I>
						end
					Next I
				end
				//Get and Add RDS_TEST keys
				RDSLayerKeys = ReactRunRec<REACT_RUN_RDS_LAYER_KEYS$>
				If RDSLayerKeys NE '' then
					LayerKeyCount = DCount(RDSLayerKeys, @VM)
					For K = 1 to LayerKeyCount
						RDSTestKeys = Xlate('RDS_LAYER', RDSLayerKeys<K>, 'RDS_TEST_KEYS', 'X', '')
						If RDSTestKeys NE '' then
							RDSTestCount = DCount(RDSTestKeys, @VM)
							For L = 1 to RDSTestCount
								If RDSTestKeys<K,L> NE '' then
									RecordArray<1,-1> = 'RDS_TEST'
									RecordArray<2,-1> = RDSTestKeys<K,L>
								end
							Next L
						end
					Next K
				end
				//Get WO_MAT key
				WONo         = RDSRec<RDS_WO$>
				CassNo       = RDSRec<RDS_CASS_NO$>
				WOMatKey     = WONo : '*' : CassNo
				//Get and Add WO_MAT_QA
				WOMatQA  = Xlate('WO_MAT_QA', WOMatKey, '', 'X', '')
				If WOMatQA NE '' then
					RecordArray<1,-1> = 'WO_MAT_QA'
					RecordArray<2,-1> = WOMatKey
				End
				//Get and Add NCR keys
				NCRKeys           = Xlate('WO_MAT', WOMatKey, 'NCR_KEYS', 'X', '')
				If NCRKeys NE '' then
					NCRCount       = Dcount(NCRKeys, @VM)
					For J = 1 to NCRCount
						If NCRKeys<J> NE '' then
							RecordArray<1,-1> = 'NCR'
							RecordArray<2,-1> = NCRKeys<J>
						end
					Next J
				end
			end else
				Error_Services('Add', 'This RDS does not exist.')
				Return
			end
			
		Case LotType EQ 'WM_OUT'
			WMOutRec = Xlate('WM_OUT', Key, '', 'X', '')
			If WMOutRec NE '' then
				//Add WM_OUT key
				RecordArray<1>    = LotType
				RecordArray<2>    = Key
				//Get and Add CLEAN_INSP keys
				CINos = WMOutRec<WM_OUT_CI_NO$>
				If CINos NE '' then
					CICount = Dcount(CINos, @VM)
					For I = 1 to CICount
						If CINos<I> NE '' then
							RecordArray<1,-1> = 'CLEAN_INSP'
							RecordArray<2,-1> = CINos<I>
						end
					Next I
				end
				//Get WO_MAT key
				WONo     = FIELD(Key,'*',1)
				CassNo   = FIELD(Key,'*',3)
				WOMatKey = WONo : '*' : CassNo
				//Get and Add WO_MAT_QA key
				WOMatQA  = Xlate('WO_MAT_QA', WOMatKey, '', 'X', '')
				If WOMatQA NE '' then
					RecordArray<1,-1> = 'WO_MAT_QA'
					RecordArray<2,-1> = WOMatKey
				End
				//Get and Add NCR keys
				NCRKeys           = Xlate('WO_MAT', WOMatKey, 'NCR_KEYS', 'X', '')
				If NCRKeys NE '' then
					NCRCount       = Dcount(NCRKeys, @VM)
					For J = 1 to NCRCount
						If NCRKeys<J> NE '' then
							RecordArray<1,-1> = 'NCR'
							RecordArray<2,-1> = NCRKeys<J>
						end
					Next J
				end
			end else
				Error_Services('Add', 'This WM_OUT does not exist.')
			end
			
		Case OTHERWISE$
			Error_Services('Add', 'LotType must be either RDS or WM_OUT.')
			return
			
	End Case
	
	If RecordArray NE '' then
		Response = RecordArray
	end
	
End Service


//----------------------------------------------------------------------------------------------------------------------
// GetUnprotectedTables
//
// Returns an array of unprotected tables
//
//----------------------------------------------------------------------------------------------------------------------
Service GetUnprotectedTables()
	
	TableArray = List_Volume_Sub('LSL', '', 'TABLE_NAME', 'TABLE_NAME')
	UnprotectedArray = ''
	For Each Table in TableArray Using @FM
		If Table[1,1] NE '!' AND Table[1,5] NE 'DICT.' then
			UnprotectedArray<-1> = Table
		end
	Next Table
	
	Response = UnprotectedArray
	
End Service





//----------------------------------------------------------------------------------------------------------------------
// LogUnlockRequest
//
// CurrUser - [Required]
// TableName - [Required]
// RecordKey - [Required]
// Success - [Required]
//
// Creates an UNLOCK_REQUESTS record to log unlock attempts.
//
//----------------------------------------------------------------------------------------------------------------------
Service LogUnlockRequest(TableName, RecordKey, CurrUser, Success)
	
	NewRequestRec = ''
	CurrDateTime = Datetime()
	RecordID = CurrDateTime :'*': TableName
	NewRequestRec<UNLOCK_REQUESTS_RECORD_KEY$> = RecordKey
	NewRequestRec<UNLOCK_REQUESTS_USER_NAME$> = CurrUser
	NewRequestRec<UNLOCK_REQUESTS_SUCCESS$> = Success
	Database_Services('WriteDataRow', 'UNLOCK_REQUESTS', RecordID, NewRequestRec, 1, 0, 0)
	
End Service






