Function Transactions_API(@API)
/***********************************************************************************************************************

    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 SRP Computer Solutions, Inc.

    Name        :   Transactions_API

    Description :   API logic for the Transactions resource.

    Notes       :   All web APIs should include the API_SETUP insert. This will provide several useful variables:

                        HTTPMethod              - The HTTP Method (Verb) submitted by the client (e.g., GET, POST, etc.)
                        APIURL                  - The URL for the API entry point (e.g., api.mysite.com/v1).
                        FullEndpointURL         - The URL submitted by the client, including query params.
                        FullEndpointURLNoQuery  - The URL submitted by the client, excluding query params.
                        EndpointSegment         - The URL endpoint segment.
                        ParentURL               - The URL path preceeding the current endpoint.
                        CurrentAPI              - The name of this stored procedure.

    Parameters  :
        API             [in] -- Web API to process. Format is [APIPattern].[HTTPMethod]:
                                    - APIPattern must follow this structure Transactions[.ID.[<Property>]]
                                    - HTTPMethod can be any valid HTTP method, e.g., GET, POST, PUT, DELETE, etc.
                                Examples:
                                    - Transactions.POST
                                    - Transactions.ID.PUT
                                    - Transactions.ID.firstName.GET
        Response       [out] -- Response to be sent back to the Controller (HTTP_MCP) or requesting procedure. Web API
                                services do not rely upon anything being returned in the response. This is what the
                                various services like SetResponseBody and SetResponseStatus services are for. A response
                                value is only helpful if the developers want to use it for debug purposes.

    History     :   (Date, Initials, Notes)
        06/28/22    xxx     Original programmer.

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

#pragma precomp SRP_PreCompiler

$insert APP_INSERTS
$insert API_SETUP
$insert HTTP_INSERTS

Declare function   OI_Wizard_Services, Reactor_Services, Unassigned
Declare subroutine OI_Wizard_Services

GoToAPI else
    // The specific resource endpoint doesn't have a API handler yet.
    HTTP_Services('SetResponseStatus', 204, 'This is a valid endpoint but a web API handler has not yet been created.')
end

Return Response OR ''


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Endpoint Handlers
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


// Endpoint for creating a new transaction record
API transactions.POST
    
    // Look for the sessionID in the cookie
    Cookies = HTTP_Services('GetHTTPCookie')
    For each Cookie in Cookies using ';'
        Key = Field(Cookie, '=', 1)
        If Key EQ 'sessionID' then
            OIWizardID = Field(Cookie, '=', 2)
        end
    Next Cookie

    Body = HTTP_Services('GetHTTPPostString')
    If Body NE '' then
        // The POST string will have been encoded so use percent (URL) decoding.
        TransactionJSON    = HTTP_Services('DecodePercentString', Body)
        ParseResponse = SRP_JSON(hTransactionJSON, 'PARSE', TransactionJSON)
        
        If (ParseResponse EQ '') then
            
            If Unassigned(OIWizardID) then OIWizardID = SRP_JSON(hTransactionJSON, 'GetValue', 'session.ID')
            
            ValidSession = OI_Wizard_Services('ValidateSession', OIWizardID)
            
            If ValidSession then
                TransType = SRP_JSON(hTransactionJSON, 'GetValue', 'session.transType')
                Data      = SRP_JSON(hTransactionJSON, 'GetValue', 'session.data')
                SRP_JSON(hTransactionJSON, 'Release')
                If RowExists('OI_WIZARD_TRANS_TYPES', TransType) then
                    TransactionID = OI_Wizard_Services('CreateTransaction', OIWizardID, TransType, Data)
                    If Error_Services('NoError') then
                        StatusCode = 201
                        GoSub CreateHALItem
                    end else
                        Message = Error_Services('GetMessage')
                        HTTP_Services('SetResponseStatus', 500, Message)
                    end
                end else
                    HTTP_Services('SetResponseStatus', 400, 'Invalid transaction type requested.')
                end
            end else
                HTTP_Services('SetResponseStatus', 500, 'Invalid session. Reauthentication required.')
            end
        end else
            HTTP_Services('SetResponseStatus', 400, 'Unable to parse the JSON data from the request.')
        end
    end else
        HTTP_Services('SetResponseStatus', 400, 'JSON object is missing from the request.')
    end   
    
end api


// Endpoing for updating a transaction record
API transactions.ID.POST
    ErrorMsg      = ''
    TransactionID = EndpointSegment
    Body          = HTTP_Services('GetHTTPPostString')
    If Body NE '' then
        // The POST string will have been encoded so use percent (URL) decoding.
        TransactionJSON    = HTTP_Services('DecodePercentString', Body)
        ParseResponse = SRP_JSON(hTransactionJSON, 'PARSE', TransactionJSON)
        If (ParseResponse EQ '') then
            OIWizardID = SRP_JSON(hTransactionJSON, 'GetValue', 'session.ID')
            If OIWizardID NE '' then
                ValidSession = Xlate('OI_WIZARD', OIWizardID, 'VALID', 'X')
            end else
                ValidSession = False$
            end
            If ValidSession then
                TransComp = Xlate('OI_WIZARD_TRANSACTIONS', TransactionID, 'COMPLETED', 'X')
                If TransComp EQ False$ then
                    TransType = SRP_JSON(hTransactionJSON, 'GetValue', 'transaction.transType')
                    Begin Case
                        Case TransType EQ 'REACT_MODE_CHG'
                            TransCurrModeKey = SRP_JSON(hTransactionJSON, 'GetValue', 'transaction.reactor.currModeKey')
                            ReactNo          = SRP_JSON(hTransactionJSON, 'GetValue', 'transaction.reactor.reactorNo')
                            CurrModeKey      = Reactor_Services('GetReactCurrModeId', ReactNo)
                            If TransCurrModeKey NE CurrModeKey then
                                TransCurrMode = SRP_JSON(hTransactionJSON, 'GetValue', 'transaction.reactor.currMode')
                                CurrMode      = Xlate('REACT_MODE_NG', CurrModeKey, 'MODE', 'X')
                                ErrorMsg      = 'Error! Reactor mode has already changed from ':TransCurrMode:' to ':CurrMode:'.'
                            end
                            
                        Case TransType EQ ''
                            ErrorMsg = 'transaction.transType is missing in JSON request.'
                            
                        Case Otherwise$
                            ErrorMsg = TransType:' is an unsupported transaction type.'
                    End Case
                    
                    If ErrorMsg EQ '' then
                        
                        RequiredFields = Xlate('OI_WIZARD_TRANS_TYPES', TransType, 'REQUIRED_FIELDS', 'X')
                        FieldData      = ''
                        If RequiredFields NE '' then
                            For each RequiredField in RequiredFields using @VM setting vPos
                                FieldData<vPos> = SRP_JSON(hTransactionJSON, 'GetValue', 'transaction.requiredFields.':RequiredField)
                            Next RequiredField
                            OI_Wizard_Services('UpdateTransaction', TransactionID, FieldData)
                            If Error_Services('NoError') then
                                OI_Wizard_Services('CompleteTransaction', TransactionID)
                                If Error_Services('NoError') then
                                    Message    = 'Transaction complete.'
                                    StatusCode = 200
                                    GoSub CreateHALItem
                                end else
                                    Message = Error_Services('GetMessage')
                                    HTTP_Services('SetResponseStatus', 500, Message)
                                end
                            end else
                                Message = Error_Services('GetMessage')
                                HTTP_Services('SetResponseStatus', 400, Message)
                            end
                        end else
                            HTTP_Services('SetResponseStatus', 500, 'Failed to retrieve required fields from OI_WIZARD_TRANS_TYPES record ':TransType:'.')
                        end
                    end else
                        HTTP_Services('SetResponseStatus', 400, ErrorMsg)
                    end
                end else
                    HTTP_Services('SetResponseStatus', 400, 'Transaction already complete.')
                end
            end else
                HTTP_Services('SetResponseStatus', 401, 'Invalid session. Reauthentication required.')
            end
            SRP_JSON(hTransactionJSON, 'Release')
        end else
            HTTP_Services('SetResponseStatus', 400, 'Unable to parse the JSON data from the request.')
        end
    end else
        HTTP_Services('SetResponseStatus', 400, 'JSON object is missing from the request.')
    end

end api


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


//----------------------------------------------------------------------------------------------------------------------
// CreateHALItem
//
// Creates a HAL+JSON object based on the OpenInsight data row representation of the scan.
//----------------------------------------------------------------------------------------------------------------------
CreateHALItem:
    
    TransactionJSON = OI_Wizard_Services('ConvertMVTransactionToJSON', TransactionID, '', FullEndpointURL)

    If Error_Services('NoError') then
        If SRP_JSON(objResource, 'Parse', TransactionJSON) EQ '' then
            lastModified    = SRP_JSON(objResource, 'GetValue', 'lastModified')
        end else
            lastModified    = ''
        end
        SRP_JSON(objResource, 'Release')
        HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
        HTTP_Services('SetResponseBody', TransactionJSON, False$, 'application/hal+json')
        If Assigned(Message) then
            HTTP_Services('SetResponseStatus', StatusCode, Message)
        end else
            HTTP_Services('SetResponseStatus', StatusCode)
        end
    end else
        Message = Error_Services('GetMessage')          
        HTTP_Services('SetResponseStatus', 500, 'Error in the ' : CurrentAPI : ' API. Message: ': Message)
    end

return
