Function Receivecassette_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        :   Receivecassette_API

    Description :   API logic for the Receivecassette 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 Receivecassette[.ID.[<Property>]]
                                    - HTTPMethod can be any valid HTTP method, e.g., GET, POST, PUT, DELETE, etc.
                                Examples:
                                    - Receivecassette.POST
                                    - Receivecassette.ID.PUT
                                    - Receivecassette.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)
        08/28/25    xxx     Original programmer.

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

#pragma precomp SRP_PreCompiler

$insert APP_INSERTS
$insert API_SETUP
$insert HTTP_INSERTS

Declare function Work_Order_Services, Wo_Mat_Services, OI_Wizard_Services, Date_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
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


API receivecassette.POST

    OIWizardID = ''
    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
    
    ValidSession = OI_Wizard_Services('ValidateSession', OIWizardID)

    If ValidSession then
        ErrorMsg    = ''
        // Check if payload has the required information to create a react mode change record
        Body        = HTTP_Services('GetHTTPPostString')
        If Body NE '' then
            // The POST string will have been encoded so use percent (URL) decoding.
            SubstrateScanJSON = HTTP_Services('DecodePercentString', Body)
            ParseResponse     = SRP_JSON(hJSON, 'PARSE', SubstrateScanJSON)
            If (ParseResponse EQ '') then
                WONo        = SRP_JSON(hJSON, 'GetValue', 'WoNo', '')
                LotNo       = SRP_JSON(hJSON, 'GetValue', 'LotNo', '')
                Qty         = SRP_JSON(hJSON, 'GetValue', 'Qty', 0)
                SubPartNo   = SRP_JSON(hJSON, 'GetValue', 'SubPartNo', '')
                SubVendCd   = SRP_JSON(hJSON, 'GetValue', 'VendorCd', '')
                ReceiveDtm  = SRP_JSON(hJSON, 'GetValue', 'ReceiveDtm', '01/01/0001 00:00:00')
                ReceiveUser = SRP_JSON(hJSON, 'GetValue', 'ReceiveUser', '')
                Begin Case
                    Case (WONo EQ '')
                        ErrorMsg = 'WoNo cannot be null'
                    Case (ReceiveUser EQ '')
                        ErrorMsg = 'ReceiveUser cannot be null'
                    Case (LotNo EQ '')
                        ErrorMsg = 'Scanned LotNo cannot be null'
                    Case (Qty EQ 0)
                        ErrorMsg = 'Scanned Qty cannot be 0'
                    Case (SubPartNo EQ '')
                        ErrorMsg = 'Scanned SubPartNo cannot be null'
                    Case (SubVendCd EQ '')
                        ErrorMsg = 'Scanned VendorCd cannot be  null'
                    Case (ReceiveDtm EQ '01/01/0001 00:00:00')
                        ErrorMsg = 'Invalid ReceiveDtm'
                    Case Otherwise$
                        Null
                End Case
                If (ErrorMsg EQ '') then
                    ReceiveDtm = Date_Services('ConvertISO8601ToDateTime', ReceiveDtm)
                    WOMatKey   = Work_Order_Services('ReceiveReleaseCassette', WONo, ReceiveUser, LotNo, Qty, SubPartNo, SubVendCd, IConv(ReceiveDtm, 'DT'))
                    If Error_Services('NoError') then
                        ResponseCode = 201
                        Message      = 'Cassette ':WOMatKey:' received'
                        GoSub CreateHalItem
                    end else
                        HTTP_Services('SetResponseStatus', 400, Error_Services('GetMessage'))
                    end
                end else
                    HTTP_Services('SetResponseStatus', 400, 'Error receiving cassette. ':ErrorMsg)
                end
                SRP_JSON(hJSON, 'Release')
            end else
                // Error parsing JSON
                HTTP_Services('SetResponseStatus', 400, 'Unable to parse the JSON data from the request.')
            end
        end else
            // No JSON payload sent with request
            HTTP_Services('SetResponseStatus', 400, 'JSON object is missing in the body of the request.')
        end
    end else
        HTTP_Services('SetResponseStatus', 401, 'Invalid session. Reauthentication required.')
    end

end api

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

CreateHalItem:
    
    JSON = ''
    
    IF RowExists('WO_MAT', WOMatKey) then
        // Update Scan object in root JSON object to contain the returned WO_MAT object
        WOMatJson = Wo_Mat_Services('ConvertRecordToJsonOIWizard', WOMatKey)
        If (SRP_JSON(objWOMat, 'Parse', WOMatJson) EQ '') then
            objTemp = SRP_JSON(objWOMat, 'Get', 'WO_Mat')
            SRP_JSON(hJSON, 'Remove', 'ReceivedCass')
            SRP_JSON(hJSON, 'Set', 'ReceivedCass', objTemp)
            SRP_JSON(objTemp, 'Release')
            SRP_JSON(objWOMat, 'Release')
            JSON    = SRP_JSON(hJSON, 'Stringify', 'Fast')
        end
    end else
        ResponseCode    = 406
        ResponseMessage = 'Error receiving and releasing cassette. WO_MAT record ':WOMatKey:' does not exist after calling ReceiveReleaseCassette.'
        HTTP_Services('SetResponseStatus', ResponseCode, ResponseMessage)
    end

    If Error_Services('NoError') then
        HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
        HTTP_Services('SetResponseBody', JSON, False$, 'application/hal+json')
        If Assigned(Message) then
            HTTP_Services('SetResponseStatus', ResponseCode, Message)
        end else
            HTTP_Services('SetResponseStatus', ResponseCode)
        end
    end else
        Message = Error_Services('GetMessage')          
        HTTP_Services('SetResponseStatus', 500, 'Error in the ' : CurrentAPI : ' API. Message: ': Message)
    end
    
return

