Compile function Nica_Orders_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 Technologies.

    Name        :   Nica_Orders_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

    History     :   (Date, Initials, Notes)
        12/05/24    djs     Original programmer.

***********************************************************************************************************************/
#pragma precomp SRP_PreCompiler

$Insert APP_INSERTS
$Insert SERVICE_SETUP
$Insert REACTOR_EQUATES
$Insert REACTOR_LOG_EQUATES
$Insert NICA_ORDERS_EQUATES

Declare function   Environment_Services, Database_Services, Error_Services, Logging_Services, Nica_Orders_Services
Declare function   Httpclient_Services, SRP_JSON, Reactor_Services, Reactor_Log_Services
Declare subroutine Error_Services, Btree.Extract, Database_Services, Logging_Services, Nica_Orders_Services, Delay
Declare subroutine Httpclient_Services, SRP_JSON, Mona_Services, Service_Services

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

GoToService

Return Response or ""

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Service Parameter Options
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Options BOOLEAN        = True$, False$
Options ENTITY_TYPES   = 'REACTOR','REACTOR_LOG'
Options ORDER_TYPES    = 'INTRUSIVE_MAINT','CHANGEOVER','INITIATE_IDLE','IDLE','ASM_HTR_TUBE_CHANGE','ASM_HTR_ANNUAL_PM','ASM_HTR_SEMIANNUAL_PM','ASM_HTR_FIVE_AND_TEN_YEAR_PM','IQS_HGCV_ALARM'
Options ORDER_STATUSES = 'new','creating','not-started','in-progress','cancelled','done'

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// SERVICES
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Service GetOrderIds(EntityType=ENTITY_TYPES, EntityID, OrderTypes=ORDER_TYPES, OrderStatus=ORDER_STATUSES, IsComplete=BOOLEAN)

	OrderKeys = ''
	ErrorMsg  = ''
	If ( (EntityType NE '') or (EntityID NE '') or (OrderTypes NE '') or (OrderStatus NE '') or (IsComplete NE '') ) then 
		Open 'DICT.NICA_ORDERS' to hDict then
			Query   = ''
			Table   = 'NICA_ORDERS'
			Option  = 'E'
			Flag    = ''
			If EntityType   NE '' then Query := 'ENTITY_TYPE'  : @VM : EntityType  : @FM
			If EntityID 	NE '' then Query := 'ENTITY_ID'    : @VM : EntityID    : @FM
			If OrderTypes   NE '' then
				Query := 'ORDER_TYPE'
				For each OrderType in OrderTypes using @VM
					Query := @VM : OrderType
				Next OrderType
				Query := @FM
			end
			If OrderStatus  NE '' then Query := 'ORDER_STATUS' : @VM : OrderStatus : @FM
			If IsComplete   NE '' then Query := 'IS_COMPLETE'  : @VM : IsComplete  : @FM
			Btree.Extract(Query, Table, hDict, OrderKeys, Option, Flag)
			If Flag NE 0 then
				ErrorMsg = 'Error in ':Service:' service. Btree.Extract call failed.'
			end
		end else
			ErrorMsg = 'Error in ':Service:' service. Failed to open DICT.NICA_ORDERS.'
		end
	end else
		ErrorMsg = 'Error in ':Service:' service. At least one search parameter must be provided.'
	end
	
	If ErrorMsg EQ '' then
		Response = OrderKeys
	end else
		Error_Services('Add', ErrorMsg)
	end
	
End Service


Service GetOrderUpdates()
	
	hSysLists   = Database_Services('GetTableHandle', 'SYSLISTS')
	Lock hSysLists, ServiceKeyID then
		ActiveOrderIds = Nica_Orders_Services('GetActiveOrders')
		For each OrderId in ActiveOrderIds using @VM
			Nica_Orders_Services('GetOrderStatusUpdate', OrderId)
		Next OrderId
		Unlock hSysLists, ServiceKeyID else Null
		Nica_Orders_Services('UpdateNicaFlags')
	end
	
end service


Service UpdateNicaFlags()
	
	rv       = ''
	ErrCode  = ''
	ReactNos = Reactor_Services('GetReactorNumbers')
	Open 'REACTOR' to hReactor then
		Open 'REACTOR_LOG' to hReactorLog then 
			For each ReactNo in ReactNos using @FM
				ProveInActive            = Reactor_Services('GetProveInActive', ReactNo)
				HgCVChecklistActive      = (Nica_Orders_Services('GetActiveOrders', 'REACTOR', ReactNo, 'IQS_HGCV_ALARM') NE '')
				Open 'REACTOR' to hReactor then
					ReadV CacheProveInActive from hReactor, ReactNo, REACTOR_PROVE_IN_ACTIVE$ then
						If CacheProveInActive NE ProveInActive then
							Lock hReactor, ReactNo then
								WriteV ProveInActive on hReactor, ReactNo, REACTOR_PROVE_IN_ACTIVE$ else Null
								Unlock hReactor, ReactNo else Null
							end
						end
					end
					ReadV CacheHgCVChecklistActive from hReactor, ReactNo, REACTOR_HGCV_CHECKLIST_ACTIVE$ then
						If CacheHgCVChecklistActive NE HgCVChecklistActive then
							Lock hReactor, ReactNo then
								WriteV HgCVChecklistActive on hReactor, ReactNo, REACTOR_HGCV_CHECKLIST_ACTIVE$ else Null
								Unlock hReactor, ReactNo else Null
							end
						end
					end
				end
				CurrModeKey       = Xlate('REACTOR_CHILD_KEY_IDS_NG', ReactNo, 'REACT_MODE_KEY_IDS', 'X')
				CurrModeKey       = CurrModeKey[-1, 'B':@VM]
				CurrRLKey         = Xlate('REACT_MODE_NG', CurrModeKey, 'START_RL_ID', 'X')			
				RLChecklistActive = Reactor_Log_Services('GetRlChecklistActive', CurrRlKey)
				Open 'REACTOR_LOG' to hReactorLog then 
					ReadV CacheRlChecklistActive from hReactorLog, CurrRlKey, REACTOR_LOG_CHECKLIST_ACTIVE$ then
						If CacheRlChecklistActive NE RLChecklistActive then
							Lock hReactorLog, CurrRlKey then
								WriteV RlChecklistActive on hReactorLog, CurrRlKey, REACTOR_LOG_CHECKLIST_ACTIVE$ else Null	
								Unlock hReactorLog, CurrRlKey else Null	
							end
						end
					end
				end
			Next ReactNo		
		end
	end

end service


Service GetActiveOrders(EntityType=ENTITY_TYPES, EntityId, OrderTypes=ORDER_TYPES)
	
	Response = Nica_Orders_Services('GetOrderIds', EntityType, EntityID, OrderTypes, '#cancelled', False$) 
	
end service


Service CreateNewOrder(EntityType=ENTITY_TYPES, EntityID, OrderType=ORDER_TYPES)
	
	ErrorMsg     = ''
	EntityTypes  = 'REACTOR,REACTOR_LOG'
	OrderTypes   = 'INTRUSIVE_MAINT,CHANGEOVER,INITIATE_IDLE,IDLE,ASM_HTR_TUBE_CHANGE,ASM_HTR_ANNUAL_PM,'
	OrderTypes  := 'ASM_HTR_SEMIANNUAL_PM,ASM_HTR_FIVE_AND_TEN_YEAR_PM,IQS_HGCV_ALARM'	
	
	Machine        = Environment_Services('GetServer')
	Headers        = 'Logging DTM' : @FM : 'Machine' : @FM : 'Log'
	ColumnWidths   = 20 : @FM : 15 : @FM : 300
	LogPath        = Environment_Services('GetApplicationRootPath') : '\LogFiles\NicaOrders'
	makeDirSuccess = Utility("MAKEDIR", LogPath)
	LogFileName    = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : LogTime : '_CreateNicaOrder.csv'
	objLog         = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, ' ', Headers, ColumnWidths, False$, False$)
	
	Prod             = Environment_Services('IsProd')
	IgnoreCertErrors = Not(Prod)	
	
	If ( (EntityType NE '') and (EntityID NE '') and (OrderType NE '') ) then
		
		Begin Case
			Case Not(InList(EntityTypes, EntityType, ','))
				ErrorMsg = 'Error in ':Service:' service. Unsupported entity type'
			Case Not(InList(OrderTypes, OrderType, ','))
				ErrorMsg = 'Error in ':Service:' service. Unsupported order type'
		End Case
		
		If ErrorMsg EQ '' then 
			
			LogData    = ''
			LogData<1> = Oconv(Date(), 'D4/') : ' ' : Oconv(Time(), 'MTS') ; // Logging DTM
			LogData<2> = Machine
			LogData<3> = 'Attempting to create NICA order for entity ':EntityType:' ' :EntityID:' of type ':OrderType
			Logging_Services('AppendLog', objLog, LogData, @RM, @FM, False$)			
			
			CurrActiveOrders       = Nica_Orders_Services('GetActiveOrders', EntityType, EntityID, OrderType) 
			OrderTypeAlreadyActive = (CurrActiveOrders NE '')
			
			If OrderTypeAlreadyActive EQ False$ then
				
				Begin Case
					Case EntityType EQ 'REACTOR'
						ReactNo = EntityID
						
					Case EntityType EQ 'REACTOR_LOG'
						ReactNo = Xlate(EntityType, EntityID, REACTOR_LOG_REACTOR$, 'X')
				End Case
				
				// Call the API
				NicaURL  = Environment_Services("GetProveInApiUrl"):'/checklists?'
				NicaURL := 'checklistType=':OrderType					
				NicaURL := '&reactorNumber=':ReactNo
				
				Retries        = 3
				BackoffSeconds = 1
				IsSuccessful   = False$
				
				OrderId = ''
				
				Loop
				while (IsSuccessful EQ False$ and Retries GT 0)
					WaitSeconds = (3 - retries) * BackoffSeconds
					Delay(WaitSeconds)
					
					Retries = Retries - 1
					
					HttpResponseJson = Httpclient_Services('SendHTTPRequest', 'POST', NicaURL, 'Accept':@VM:'*/*', '', '', '', False$, False$, '', IgnoreCertErrors)
					If HttpResponseJson NE '' then
						ObjResponseJson = ''
						If SRP_JSON(ObjResponseJson, 'Parse', HttpResponseJson) EQ '' then
							OrderId = SRP_JSON(ObjResponseJson, 'GetValue', 'id')
							If OrderId NE '' then
								Convert @Lower.Case to @Upper.Case in OrderId
								NicaOrderRec                            = ''
								NicaOrderRec<NICA_ORDERS.ORDER_TYPE$>   = OrderType
								NicaOrderRec<NICA_ORDERS.ORDER_STATUS$> = SRP_JSON(ObjResponseJson, 'GetValue', 'state')
								NicaOrderRec<NICA_ORDERS.ENTITY_TYPE$>  = EntityType
								NicaOrderRec<NICA_ORDERS.ENTITY_ID$>    = EntityID
								NicaOrderRec<NICA_ORDERS.IS_COMPLETE$>  = SRP_JSON(ObjResponseJson, 'GetValue', 'isComplete')
								If NicaOrderRec<NICA_ORDERS.IS_COMPLETE$> EQ False$ then
								    NicaOrderRec<NICA_ORDERS.PROGRESS_PERCENTAGE$>  = SRP_JSON(ObjResponseJson, 'GetValue', 'progressPercentage')
								end else
								    NicaOrderRec<NICA_ORDERS.PROGRESS_PERCENTAGE$>  = 100
								end
								Database_Services('WriteDataRow', 'NICA_ORDERS', OrderId, NicaOrderRec, True$, False$, False$)
								If Error_Services('NoError') then
									If ( (OrderType _EQC 'INITIATE_IDLE') and (EntityType _EQC 'REACTOR') ) then
										Open 'REACTOR' to hReactor then
											WriteV True$ to hReactor, ReactNo, REACTOR_IDLE_STARTUP_REQUIRED$ else
												ErrorMsg = 'Error in ':Service:' service. Error setting IDLE_STARTUP_REQUIRED flag in REACTOR record.'		
											end
										end
									end
									If ErrorMsg EQ '' then 
										IsSuccessful = True$
										Response     = OrderId
									end
								end else
									ErrorMsg = Error_Services('GetMessage')
								end
							end else
								ErrorMsg = 'Error in ':Service:' service. Null OrderId returned from MesaProveInAPI.'
							end
						end else
							ErrorMsg = 'Error in ':Service:' service. Error parsing JSON response from MesaProveInAPI.'
						end
					end else
						ErrorMsg = 'Error in ':Service:' service. Null JSON response returned from MesaProveInAPI.'
					end
					SRP_JSON(ObjResponseJson, 'Release')
				Repeat
				
				If Environment_Services('IsProd') then
					MonAResource = 'GRP_OPENINSIGHT_MES_OP_FE_MESAPROVEINAPI'
				end else
					MonAResource = 'GRP_OPENINSIGHT_MES_OP_FE_DEV_MESAPROVEINAPI_DEV'
				end
				StatusName = 'CreateNicaOrder'
				If IsSuccessful then
					LogData     = ''
					LogData<1>  = Oconv(Date(), 'D4/') : ' ' : Oconv(Time(), 'MTS') ; // Logging DTM
					LogData<2>  = Machine
					LogData<3>  = 'Successfully created Nica order for entity ':EntityType:' ':EntityID:' of type ':OrderType
					Logging_Services('AppendLog', objLog, LogData, @RM, @FM, False$) 
					Mona_Services('SendBufferedStatus', MonAResource, StatusName, 'Ok')
				end else
					ErrorMsg   = 'Error encountered when attempting to create Nica in order for reactor ':ReactNo:' of type ':OrderType
					Mona_Services('SendBufferedStatus', MonAResource, StatusName, 'Critical')
				end
			end else
				ErrorMsg   = 'Error encountered when attempting to create Nica order for entity ':EntityType:' ' :EntityID:' of type ':OrderType:'. Active order already exists.'
			end
		end
	end else
		ErrorMsg = 'Error in ':Service:' service. Null EntityType, EntityID, or OrderType passed in.'
	end
	
	If ErrorMsg NE '' then
		LogData    = ''
		LogData<1> = Oconv(Date(), 'D4/') : ' ' : Oconv(Time(), 'MTS') ; // Logging DTM
		LogData<2> = Machine
		LogData<3> = ErrorMsg
		Logging_Services('AppendLog', objLog, LogData, @RM, @FM, False$) 		
		Error_Services('Add', ErrorMsg)
		Response = 'error'
	end
	
end service


Service CancelOrder(OrderId)
	
	ErrorMsg       = ''
	Machine        = Environment_Services('GetServer')
	Headers        = 'Logging DTM' : @FM : 'Machine' : @FM : 'Log'
	ColumnWidths   = 20 : @FM : 15 : @FM : 300
	LogPath        = Environment_Services('GetApplicationRootPath') : '\LogFiles\NicaOrders'
	makeDirSuccess = Utility("MAKEDIR", LogPath)
	LogFileName    = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : '_CancelNicaOrder.csv'
	objLog         = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, ' ', Headers, ColumnWidths, False$, False$)
	
	LogData    = ''
	LogData<1> = Oconv(Date(), 'D4/') : ' ' : Oconv(Time(), 'MTS') ; // Logging DTM
	LogData<2> = Machine
	LogData<3> = 'Attempting to cancel Nica order ' : OrderId :'.'
	Logging_Services('AppendLog', objLog, LogData, @RM, @FM, False$)
	
	Prod             = Environment_Services('IsProd')
	IgnoreCertErrors = Not(Prod)	
	
	If OrderId NE '' then
		LockRetries        = 3
		LockBackoffSeconds = 1
		HaveLock           = False$
		Loop
		While (HaveLock EQ False$ and LockRetries GT 0)
			WaitSeconds = (3 - LockRetries) * LockBackoffSeconds
			Delay(WaitSeconds)
			LockRetries = LockRetries - 1		
			HaveLock    = Database_Services('GetKeyIDLock', 'NICA_ORDERS', OrderId, True$)
		Repeat	
		
		If HaveLock then
			NicaOrderRec = Database_Services('ReadDataRow', 'NICA_ORDERS', OrderId)
			If Error_Services('NoError') then 
				EntityType = NicaOrderRec<NICA_ORDERS.ENTITY_TYPE$>
				EntityId   = NicaOrderRec<NICA_ORDERS.ENTITY_ID$>
				Begin Case
					Case EntityType EQ 'REACTOR'
						ReactNo = EntityId
						
					Case EntityType EQ 'REACTOR_LOG'
						ReactNo = Xlate(EntityType, EntityId, REACTOR_LOG_REACTOR$, 'X')
						
					Case Otherwise$
						ErrorMsg = 'Error in ':Service:' service. Unsupported entity type.'
				End Case	
				
				If ErrorMsg EQ '' then 
					
					LogData     = ''
					LogData<1>  = Oconv(Date(), 'D4/') : ' ' : Oconv(Time(), 'MTS') ; // Logging DTM
					LogData<2>  = Machine
					LogData<3>  = 'Sending cancel request for Nica order ' : OrderId : ' for reactor ' : ReactNo
					Logging_Services('AppendLog', objLog, LogData, @RM, @FM, False$)
					
					Response       = False$
					BaseProveInUrl = Environment_Services("GetProveInApiUrl"):'/checklists?'
					UrlOrderId     = OrderId
					Convert @Upper.Case to @Lower.Case in UrlOrderId
					ProveInUrl     = BaseProveInUrl:'checklistOrderId=':UrlOrderId					
					ProveInUrl     = ProveInUrl:'&checklistState=cancelled'
					
					Retries        = 3
					BackoffSeconds = 1
					IsSuccessful   = False$
					
					Loop
					while (IsSuccessful EQ False$ and Retries GT 0)
						WaitSeconds = (3 - Retries) * BackoffSeconds
						Delay(WaitSeconds)
						Retries = Retries - 1
						HttpResponseJson = Httpclient_Services('SendHTTPRequest', 'PUT', ProveInUrl, 'Accept':@VM:'*/*', '', '', '', False$, False$, '', IgnoreCertErrors)
						If HttpResponseJson NE '' then
							ObjResponseJson = ''
							If SRP_JSON(ObjResponseJson, 'Parse', HttpResponseJson) EQ '' then
								IsComplete = SRP_JSON(ObjResponseJson, 'GetValue', 'pendingUpdate')
								NicaOrderRec<NICA_ORDERS.ORDER_STATUS$> = SRP_JSON(ObjResponseJson, 'GetValue', 'state')
								NicaOrderRec<NICA_ORDERS.IS_COMPLETE$>  = SRP_JSON(ObjResponseJson, 'GetValue', 'isComplete')
								If IsComplete EQ False$ then
								    NicaOrderRec<NICA_ORDERS.PROGRESS_PERCENTAGE$>  = SRP_JSON(ObjResponseJson, 'GetValue', 'progressPercentage')
								end else
								    NicaOrderRec<NICA_ORDERS.PROGRESS_PERCENTAGE$>  = 100
								end
								Database_Services('WriteDataRow', 'NICA_ORDERS', OrderId, NicaOrderRec, True$, False$, False$)						
								If Error_Services('NoError') then
									OrderType = NicaOrderRec<NICA_ORDERS.ORDER_TYPE$>
									If ( (OrderType _EQC 'IDLE') and (EntityType EQ 'REACTOR') ) then
										Open 'REACTOR' to hReactor then
											WriteV False$ on hReactor, ReactNo, REACTOR_IDLE_STARTUP_REQUIRED$ else
												ErrorMsg = 'Error in ':Service:' service. Error setting IDLE_STARTUP_REQUIRED flag in REACTOR record.'
											end
										end
									end										
									If ( (Response EQ True$) or (Response EQ False$) ) then IsSuccessful = True$
								end else
									ErrorMsg = Error_Services('GetMessage')
								end
								If IsComplete EQ True$ then
									Response = True$
								end else
									Response = False$
								end
							end
						end
						SRP_JSON(ObjResponseJson, 'Release')
					Repeat
					
					If Environment_Services('IsProd') then
						MonAResource = 'GRP_OPENINSIGHT_MES_OP_FE_MESAPROVEINAPI'
					end else
						MonAResource = 'GRP_OPENINSIGHT_MES_OP_FE_DEV_MESAPROVEINAPI_DEV'
					end	
					StatusName = 'CancelNicaOrder'
					If ( (IsSuccessful EQ True$) and (Response NE 'error') and (ErrorMsg EQ '') ) then		
						LogData     = ''
						LogData<1>  = Oconv(Date(), 'D4/') : ' ' : Oconv(Time(), 'MTS') ; // Logging DTM
						LogData<2>  = Machine
						LogData<3>  = 'Successfully cancelled Nica order ' : OrderId : ' for reactor ' : ReactNo
						Logging_Services('AppendLog', objLog, LogData, @RM, @FM, False$)
						Mona_Services('SendBufferedStatus', MonAResource, StatusName, 'Ok')
					end else
						ErrorMsg   = 'Error encountered cancelling Nica order ' : OrderId : ' for reactor ' : ReactNo
						Mona_Services('SendBufferedStatus', MonAResource, StatusName, 'Critical')
					end
				end else
					ErrorMsg = Error_Services('GetMessage')
					Database_Services('ReleaseKeyIDLock', 'NICA_ORDERS', OrderId)
				end			
			end else
				ErrorMsg = 'Error in ':Service:' service. Failed to lock NICA_ORDERS ':OrderId:' for cancellation.'
			end
		end else
			ErrorMsg = 'Error in ':Service:' service. Null OrderID passed in.'
		end
	end else
		ErrorMsg = Error_Services('GetMessage')
	end
	
	If ErrorMsg NE '' then
		LogData    = ''
		LogData<1> = Oconv(Date(), 'D4/') : ' ' : Oconv(Time(), 'MTS') ; // Logging DTM
		LogData<2> = Machine
		LogData<3> = ErrorMsg
		Logging_Services('AppendLog', objLog, LogData, @RM, @FM, False$) 		
		Error_Services('Add', ErrorMsg)
		Response = 'error'
	end
	
end service


Service GetOrderStatus(OrderId)
	
	If OrderId NE '' then
		If RowExists('NICA_ORDERS', OrderId) then
			Response = Xlate('NICA_ORDERS', OrderId, 'ORDER_STATUS', 'X')
		end else
			Error_Services('Add', 'Error in ':Service:' service. Nica order ':OrderId:' does not exist.')
		end
	end else
		Error_Services('Add', 'Error in ':Service:' service. Null OrderId passed in.')
	end
	
end service


Service GetOrderStatusUpdate(OrderId)
	
	ErrorMsg       = ''
	Headers        = 'Logging DTM' : @FM : 'Machine' : @FM : 'Log'
	ColumnWidths   = 20 : @FM : 15 : @FM : 300
	LogPath        = Environment_Services('GetApplicationRootPath') : '\LogFiles\NicaOrders'
	makeDirSuccess = Utility("MAKEDIR", LogPath)
	LogFileName    = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : '_GetOrderStatusUpdate.csv'
	objLog         = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, ' ', Headers, ColumnWidths, False$, False$)
	
	LogData    = ''
	LogData<1> = Oconv(Date(), 'D4/') : ' ' : Oconv(Time(), 'MTS') ; // Logging DTM
	LogData<2> = Machine
	LogData<3> = 'Attempting to update Nica order ' : OrderId :'.'
	Logging_Services('AppendLog', objLog, LogData, @RM, @FM, False$)
	
	Prod             = Environment_Services('IsProd')
	IgnoreCertErrors = Not(Prod)
	
	If OrderId NE '' then 
		HaveLock = Database_Services('GetKeyIDLock', 'NICA_ORDERS', OrderId, True$)
		If HaveLock then
			NicaOrderRec = Database_Services('ReadDataRow', 'NICA_ORDERS', OrderId)
			If Error_Services('NoError') then 
				EntityType = NicaOrderRec<NICA_ORDERS.ENTITY_TYPE$>
				EntityId   = NicaOrderRec<NICA_ORDERS.ENTITY_ID$>
				Begin Case
					Case EntityType EQ 'REACTOR'
						ReactNo = EntityId
						
					Case EntityType EQ 'REACTOR_LOG'
						ReactNo = Xlate(EntityType, EntityId, REACTOR_LOG_REACTOR$, 'X')
						
					Case Otherwise$
						ErrorMsg = 'Error in ':Service:' service. Unsupported entity type.'
				End Case	
				
				If ErrorMsg EQ '' then 	
					
					LogData    = ''
					LogData<1> = Oconv(Date(), 'D4/') : ' ' : Oconv(Time(), 'MTS') ; // Logging DTM
					LogData<2> = Machine
					LogData<3> = 'Attempting to fetch Nica order ':OrderId:' for reactor ':ReactNo
					Logging_Services('AppendLog', objLog, LogData, @RM, @FM, False$)
					
					Response       = True$
					IsSuccessful   = True$
					BaseProveInUrl = Environment_Services("GetProveInApiUrl"):'/checklists?'
					UrlOrderId     = OrderId
					Convert @Upper.Case to @Lower.Case in UrlOrderId
					ProveInUrl     = BaseProveInUrl:'checklistOrderId=':UrlOrderId
					
					Retries        = 3
					BackoffSeconds = 1
					IsSuccessful   = False$
					
					Loop
					while (IsSuccessful EQ False$ and Retries GT 0)
						WaitSeconds = (3 - Retries) * BackoffSeconds
						
						Delay(WaitSeconds)
						
						Retries          = Retries - 1
						
						HttpResponseJson = Httpclient_Services('SendHTTPRequest', 'GET', ProveInUrl, 'Accept':@VM:'*/*', '', '', '', False$, False$, '', IgnoreCertErrors)
						
						If HttpResponseJson NE '' then
							ObjResponseJson = ''
							If SRP_JSON(ObjResponseJson, 'Parse', HttpResponseJson) EQ '' then
								IsComplete = SRP_JSON(ObjResponseJson, 'GetValue', 'isComplete')
								NicaOrderRec<NICA_ORDERS.ORDER_TYPE$>   = SRP_JSON(ObjResponseJson, 'GetValue', 'type')
								NicaOrderRec<NICA_ORDERS.ORDER_STATUS$> = SRP_JSON(ObjResponseJson, 'GetValue', 'state')
								NicaOrderRec<NICA_ORDERS.IS_COMPLETE$>  = IsComplete
								If IsComplete EQ False$ then
								    NicaOrderRec<NICA_ORDERS.PROGRESS_PERCENTAGE$>  = SRP_JSON(ObjResponseJson, 'GetValue', 'progressPercentage')
								end else
								    NicaOrderRec<NICA_ORDERS.PROGRESS_PERCENTAGE$>  = 100
								end
								Database_Services('WriteDataRow', 'NICA_ORDERS', OrderId, NicaOrderRec, True$, False$, False$)
								If Error_Services('NoError') then
									If IsComplete EQ True$ then
										OrderType = NicaOrderRec<NICA_ORDERS.ORDER_TYPE$>
										If ( (OrderType _EQC 'IDLE') and (EntityType _EQC 'REACTOR') ) then
											Open 'REACTOR' to hReactor then
												WriteV False$ on hReactor, ReactNo, REACTOR_IDLE_STARTUP_REQUIRED$ else
													ErrorMsg = 'Error in ':Service:' service. Error setting IDLE_STARTUP_REQUIRED flag in REACTOR record.'
												end
											end
										end										
										If ErrorMsg EQ '' then Response = True$
									end else
										Response = False$
									end									
									If ( (Response EQ True$) or (Response EQ False$) ) then IsSuccessful = True$
								end else
									ErrorMsg = Error_Services('GetMessage')
								end
							end
						end
						SRP_JSON(ObjResponseJson, 'Release')
					Repeat
					
					If Environment_Services('IsProd') then
						MonAResource = 'GRP_OPENINSIGHT_MES_OP_FE_MESAPROVEINAPI'
					end else
						MonAResource = 'GRP_OPENINSIGHT_MES_OP_FE_DEV_MESAPROVEINAPI_DEV'
					end
					
					StatusName = 'GetNicaOrderUpdate'
					If IsSuccessful and Response NE 'error' then
						LogData     = ''
						LogData<1>  = Oconv(Date(), 'D4/') : ' ' : Oconv(Time(), 'MTS') ; // Logging DTM
						LogData<2>  = Machine
						LogData<3>  = 'Successfully updated Nica order ':OrderId:' for reactor ':ReactNo:'.'
						Mona_Services('SendBufferedStatus', MonAResource, StatusName, 'Ok')
						Logging_Services('AppendLog', objLog, LogData, @RM, @FM, False$)
					end else
						Database_Services('ReleaseKeyIDLock', 'NICA_ORDERS', OrderId)
						ErrorMsg   = 'Error encountered updating Nica order ':OrderId:' for reactor ':ReactNo:'.'
						Mona_Services('SendBufferedStatus', MonAResource, StatusName, 'Critical')
					end					
				end
			end else
				ErrorMsg = Error_Services('GetMessage')
			end
		end else
			ErrorMsg = 'Error in ':Service:' service. Failed to lock NICA_ORDERS ':OrderId:'.'
		end
	end else
		ErrorMsg = 'Error in ':Service:' service. Null OrderId passed in.'
	end
		
	If ErrorMsg NE '' then
		LogData    = ''
		LogData<1> = Oconv(Date(), 'D4/') : ' ' : Oconv(Time(), 'MTS') ; // Logging DTM
		LogData<2> = Machine
		LogData<3> = ErrorMsg
		Logging_Services('AppendLog', objLog, LogData, @RM, @FM, False$)
		Error_Services('Add', ErrorMsg)
		Response = 'error'		
	end
		
end service


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




