Compile function RETURN_TO_FAB_Services(@Service, @Params)
#pragma precomp SRP_PreCompiler

Declare subroutine Error_Services, Database_Services, Btree.Extract, Logging_Services, SRP_JSON

Declare function Rti_Createguid, Database_Services, Return_To_Fab_Services, Datetime, Error_Services
Declare function Logging_Services, Environment_Services, SRP_JSON, MemberOf
Declare subroutine obj_notes, SRP_Run_Command

$insert LOGICAL
$Insert APP_INSERTS
$Insert RETURN_TO_FAB_LOTS_EQUATES
$Insert RETURN_TO_FAB_RESULT_OPTION_EQUATES
$Insert WO_MAT_EQUATES
$Insert RDS_EQUATES
$Insert NOTIFICATION_EQUATES

LogPath    = Environment_Services('GetApplicationRootPath') : '\LogFiles\Return_To_Fab_Services'; //Define the directory where the log will be saved to. This happens the first time of the day that the log is written to.
LogDate    = Oconv(Date(), 'D4/')
LogTime    = Oconv(Time(), 'MTS')
LoggingDTM = LogDate : ' ' : LogTime   ; // Logging DTM

LogFileName       = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' ReturnToFabServicesLog.csv'
Headers           = 'Logging DTM' : @FM : 'Cass Id' : @FM: 'User' : @FM : 'ReturnToFabId' : @FM : 'Message'; //Define the column names in the log file, delimited by a Field Mark.
objReturnToFabLog = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, ',', Headers, '', False$, False$); //Actually creates the log.

GoToService

Return Response or ""

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

Service CreateReturnToFabRecord(CassId, UserId)
    ErrorMessage = ''
    NewRTFId     = ''
    If CassId NE '' then
        CassType = ''
        Begin Case
            Case RowExists('RDS', CassId)
                CassType = 'RDS'
            Case RowExists('WM_OUT', CassId)
                CassType = 'WM_OUT'
            Case Otherwise$
                ErrorMessage = 'Error creating return to fab record, Cassette ID not found.'
        End Case
        If ErrorMessage EQ '' then
            OpenRTFRecordExists = Return_To_Fab_Services('GetOpenReturnToFabRecordIdByCassId', CassId) NE ''
            If Not(OpenRTFRecordExists) then
                If RowExists('LSL_USERS', UserId) then
                    //Validation: Need to ensure the lot has a batch number to ensure it "Has Left The Fab"
                    SAPBatchNo = ''
                    Begin Case
                        Case CassType EQ 'RDS'
                            WONo       = Database_Services('ReadDataColumn', 'RDS', CassId, RDS_WO$, True$, 0, False$)
                            CassNo     = Database_Services('ReadDataColumn', 'RDS', CassId, RDS_CASS_NO$, True$, 0, False$)
                            WOMatKeyId = WONo : '*' : CassNo
                            SAPBatchNo = Database_Services('ReadDataColumn', 'WO_MAT', WOMatKeyId, WO_MAT_SAP_BATCH_NO$, True$, 0, False$)
                        Case CassType EQ 'WM_OUT'
                            WONo       = Field(CassId, '*', 1)
                            CassNo     = Field(CassId, '*', 3)
                            WOMatKeyId = WONo : '*' : CassNo
                            SAPBatchNo = Database_Services('ReadDataColumn', 'WO_MAT', WOMatKeyId, WO_MAT_SAP_BATCH_NO$, True$, 0, False$)
                    End Case
                    If SAPBatchNo NE '' then
                        NewRTFId                                         = Rti_Createguid()
                        RTFRecord                                        = ''
                        RTFRecord<RETURN_TO_FAB_LOTS_CASS_ID$>           = CassId
                        RTFRecord<RETURN_TO_FAB_LOTS_LOT_TYPE$>          = CassType
                        RTFRecord<RETURN_TO_FAB_LOTS_REQUESTOR_USER_ID$> = UserId
                        RTFRecord<RETURN_TO_FAB_LOTS_START_DTM$>         = Datetime()
                        RTFRecord<RETURN_TO_FAB_LOTS_COMPLETED$>         = False$
                        Database_Services('WriteDataRow', 'RETURN_TO_FAB_LOTS', NewRTFId, RTFRecord, True$, False$, True$)
                        If Error_Services('NoError') then
                            //Send notification that a return to fab record was created.
                            Message            = 'Return to fab form created for ' : CassId : ' by ' : UserId : '.' : CRLF$
                            Message           := 'Link to Return To Fab form: https://goto.infineon.com/oiwizard/ReturnToFab'
                            Recipients         = XLATE('NOTIFICATION','SHIPPING',NOTIFICATION_USER_ID$,'X')
                            Recipients<1, -1>  = XLATE('NOTIFICATION','RETURN_TO_FAB_ENG',NOTIFICATION_USER_ID$,'X')
                            Recipients<1, -1>  = XLATE('NOTIFICATION','RETURN_TO_FAB_MANUF',NOTIFICATION_USER_ID$,'X')
                            Recipients<1, -1>  = XLATE('NOTIFICATION','RETURN_TO_FAB_GENERAL',NOTIFICATION_USER_ID$,'X')
                            Recipients<1, -1>  = UserId
                            SentFrom           = 'OI_ADMIN'
                            Subject            = 'Return To Fab Form Created'
                            SendToGroup        = ''
                            AttachWindow       = ''
                            AttachKey          = ''
                            Parms              = Recipients:@RM:SentFrom:@RM:Subject:@RM:Message:@RM:AttachWindow:@RM:AttachKey:@RM:SendToGroup
                            obj_Notes('Create',Parms)
                        end else
                            ErrorMessage = Error_Services('GetMessage')
                        end
                    end else
                        ErrorMessage = 'Error creating return to fab record, Cassette ID is not currently in SAP and cannot be returned to fab.'    
                    end
                end else
                    ErrorMessage = 'Error creating return to fab record, User not found.' 
                end
            end else
                ErrorMessage = 'Error creating return to fab record, an active return to fab for this lot already exists.'
            end
        end
    end else
        ErrorMessage = 'Error creating return to fab record, Cassette ID was null'
    end
    If ErrorMessage EQ '' AND NewRTFId NE '' then
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = CassId
        LogData<3> = UserId
        LogData<4> = NewRTFId
        LogData<5> = 'Successfully created new RETURN_TO_FAB_LOTS record'
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
        Response   = NewRTFId
    end else
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = CassId
        LogData<3> = UserId
        LogData<4> = NewRTFId
        LogData<5> = ErrorMessage
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
        Response   = NewRTFId
        Error_Services('Add', ErrorMessage)
    end
End Service

Service GetReturnToFabResultOptions()
    ErrorMessage        = ''
    RTFResultOptions    = ''
    RTFResultOptionKeys = ''
    table = "RETURN_TO_FAB_RESULT_OPTION"
    Open "DICT ":table To @DICT Else
        ErrorMessage = 'Error opening RETURN_TO_FAB_RESULT_OPTION dictionary'
    End
    If ErrorMessage EQ '' then
        srch_strng  = "ACTIVE":@VM:True$:@FM
        option      = ""
        flag        = ""
        Btree.Extract(srch_strng, table, @DICT, RTFResultOptionKeys, option, flag)
        for each RTFOptionID in RTFResultOptionKeys using @VM setting rPos
            RTFResultOptions<1, rPos> = RTFOptionID
            ResultDesc                = Database_Services('ReadDataColumn', table, RTFOptionID, RETURN_TO_FAB_RESULT_OPTION_RESULT$, True$, 0, False$)
            RTFResultOptions<2, rPos> = ResultDesc
        Next RTFReasonID
    end
    If ErrorMessage EQ '' then
        Response = RTFResultOptions
    end else
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = ''
        LogData<4> = ''
        LogData<5> = ErrorMessage
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
        Error_Services('Add', ErrorMessage)
    end
end service

Service ConvertReturnToFabRecordToJSON(RTFId)
    ErrorMessage = ''
    JsonString   = ''
    If RowExists('RETURN_TO_FAB_LOTS', RTFId) then
        objJSON = ''
        If SRP_JSON(objJSON, 'New', 'Object') then
            RTFRecord = Database_Services('ReadDataRow', 'RETURN_TO_FAB_LOTS', RTFId, True$, 0, False$)
            If Error_Services('NoError') AND RTFRecord NE '' then
                If SRP_JSON(objRTF, 'New', 'Object') then
                    SRP_JSON(objRTF, 'SetValue', 'ReturnToFabLotsId', RTFId)
                    SRP_JSON(objRTF, 'SetValue', 'CassId', RTFRecord<RETURN_TO_FAB_LOTS_CASS_ID$>)
                    SRP_JSON(objRTF, 'SetValue', 'LotType', RTFRecord<RETURN_TO_FAB_LOTS_LOT_TYPE$>)
                    SRP_JSON(objRTF, 'SetValue', 'RequestorUserId', RTFRecord<RETURN_TO_FAB_LOTS_REQUESTOR_USER_ID$>)
                    SRP_JSON(objRTF, 'SetValue', 'StartDtm', OConv(RTFRecord<RETURN_TO_FAB_LOTS_START_DTM$>, 'DT'))
                    SRP_JSON(objRTF, 'SetValue', 'MHInitUserId', RTFRecord<RETURN_TO_FAB_LOTS_MH_INIT_USER_ID$>)
                    SRP_JSON(objRTF, 'SetValue', 'MHInitDtm', OConv(RTFRecord<RETURN_TO_FAB_LOTS_MH_INIT_DTM$>, 'DT'))
                    SRP_JSON(objRTF, 'SetValue', 'EvalUserId', RTFRecord<RETURN_TO_FAB_LOTS_EVAL_USER_ID$>)
                    SRP_JSON(objRTF, 'SetValue', 'EvalResultId', RTFRecord<RETURN_TO_FAB_LOTS_EVAL_RESULT_ID$>, 'Number')
                    if RTFRecord<RETURN_TO_FAB_LOTS_EVAL_RESULT_ID$> NE '' then
                        EvaluationDescription = Database_Services('ReadDataColumn', 'RETURN_TO_FAB_RESULT_OPTION', RTFRecord<RETURN_TO_FAB_LOTS_EVAL_RESULT_ID$>, RETURN_TO_FAB_RESULT_OPTION_RESULT$, True$, 0, False$)
                    end else
                        EvaluationDescription = ''
                    end
                    SRP_JSON(objRTF, 'SetValue', 'EvalDesc', EvaluationDescription)
                    SRP_JSON(objRTF, 'SetValue', 'EvalDtm', OConv(RTFRecord<RETURN_TO_FAB_LOTS_EVAL_DTM$>, 'DT'))
                    SRP_JSON(objRTF, 'SetValue', 'FinalCompleteUserId', RTFRecord<RETURN_TO_FAB_LOTS_FINAL_COMPLETE_USER_ID$>)
                    SRP_JSON(objRTF, 'SetValue', 'FinalCompleteDtm', OConv(RTFRecord<RETURN_TO_FAB_LOTS_FINAL_COMPLETE_DTM$>, 'DT'))
                    SRP_JSON(objRTF, 'SetValue', 'Completed', RTFRecord<RETURN_TO_FAB_LOTS_COMPLETED$>, 'Boolean')
                    SRP_JSON(objRTF, 'SetValue', 'CompletedDtm', OConv(RTFRecord<RETURN_TO_FAB_LOTS_COMPLETED_DTM$>,'DT'))
                    SRP_JSON(objRTF, 'SetValue', 'Reason', RTFRecord<RETURN_TO_FAB_LOTS_REASON$>)
                    CurrStepId = Return_To_Fab_Services('GetRTFCurrStep', RTFId)
                    SRP_Json(objRTF, 'SetValue', 'CurrStepId', CurrStepId, 'Number')
                    Notes      = RTFRecord<RETURN_TO_FAB_LOTS_NOTES$>
                    NotesUser  = RTFRecord<RETURN_TO_FAB_LOTS_NOTES_USER$>
                    If Notes NE '' then
                        JsonArrayNotes = ''
                        If SRP_JSON(JsonArrayNotes, 'New', 'Array') then
                            For each Note in Notes using @VM setting vPos
                                objSingleNote = ''
                                If SRP_Json(objSingleNote, 'New', 'Object') then
                                    SRP_Json(objSingleNote, 'SetValue', 'NoteText', Notes<1,vPos>, 'String')
                                    SRP_Json(objSingleNote, 'SetValue', 'NoteUser', NotesUser<1,vPos>, 'String')
                                    SRP_Json(JsonArrayNotes, 'Add', objSingleNote)
                                    SRP_Json(objSingleNote, 'Release')
                                end
                            Next Note
                            SRP_JSON(objRTF, 'Set', 'Notes', JsonArrayNotes)
                            SRP_JSON(JsonArrayNotes, 'Release')
                        end
                    end else
                        SRP_JSON(objRTF, 'SetValue', 'Notes', '')
                    end
                    SRP_JSON(objJSON, 'Set', 'ReturnToFab', objRTF)
                    SRP_JSON(objRTF, 'Release')
                end else
                    ErrorMessage = 'Error creating new Json Object'
                end
            end else
                ErrorMessage = 'Error reading RTFRecord from database...' 
            end
            JsonString = SRP_JSON(objJSON, 'Stringify', 'Styled')
            SRP_JSON(objJSON, 'Release')
        end else
            ErrorMessage = 'Error creating new Json Object'
        end
    end else
        ErrorMessage = 'Error Converting RTF record to JSON. RTFId not found in database.'
    end
    If ErrorMessage NE '' then
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = ''
        LogData<4> = ''
        LogData<5> = ErrorMessage
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
        Error_Services('Add', ErrorMessage)
    end
    Response = JsonString
end service

Service CreateReturnToFabReportJson(ShowOpenReport)
    ErrorMessage = ''
    JsonString   = ''
    objJSON = ''
    Begin Case
        Case ShowOpenReport
            RTFIdList = Return_To_Fab_Services('GetAllReturnToFabRecords', True$)
        Case Otherwise$
            RTFIdList = Return_To_Fab_Services('GetAllReturnToFabRecords', False$)
    End Case
    If SRP_JSON(objJSON, 'New', 'Object') then
        If SRP_Json(objReturnToFabReport, 'New', 'Array') then
            for each RTFId in RTFIdList using @VM
                RTFRecord = Database_Services('ReadDataRow', 'RETURN_TO_FAB_LOTS', RTFId, True$, 0, False$)
                If Error_Services('NoError') and RTFRecord NE '' then
                    hRTFJsonSingle = ''
                    if SRP_Json(hRTFJsonSingle, 'New', 'Object') then
                        SRP_JSON(hRTFJsonSingle, 'SetValue', 'ReturnToFabLotsId', RTFId)
                        SRP_JSON(hRTFJsonSingle, 'SetValue', 'CassId', RTFRecord<RETURN_TO_FAB_LOTS_CASS_ID$>)
                        SRP_JSON(hRTFJsonSingle, 'SetValue', 'LotType', RTFRecord<RETURN_TO_FAB_LOTS_LOT_TYPE$>)
                        SRP_JSON(hRTFJsonSingle, 'SetValue', 'RequestorUserId', RTFRecord<RETURN_TO_FAB_LOTS_REQUESTOR_USER_ID$>)
                        SRP_JSON(hRTFJsonSingle, 'SetValue', 'StartDtm', OConv(RTFRecord<RETURN_TO_FAB_LOTS_START_DTM$>, 'DT'))
                        if RTFRecord<RETURN_TO_FAB_LOTS_EVAL_RESULT_ID$> NE '' then
                            EvaluationDescription = Database_Services('ReadDataColumn', 'RETURN_TO_FAB_RESULT_OPTION', RTFRecord<RETURN_TO_FAB_LOTS_EVAL_RESULT_ID$>, RETURN_TO_FAB_RESULT_OPTION_RESULT$, True$, 0, False$)
                        end else
                            EvaluationDescription = ''
                        end
                        SRP_JSON(hRTFJsonSingle, 'SetValue', 'EvalDesc', EvaluationDescription)
                        SRP_JSON(hRTFJsonSingle, 'SetValue', 'FinalCompleteDtm', OConv(RTFRecord<RETURN_TO_FAB_LOTS_FINAL_COMPLETE_DTM$>, 'DT'))
                        SRP_JSON(hRTFJsonSingle, 'SetValue', 'Completed', RTFRecord<RETURN_TO_FAB_LOTS_COMPLETED$>, 'Boolean')
                        SRP_JSON(hRTFJsonSingle, 'SetValue', 'CompletedDtm', OConv(RTFRecord<RETURN_TO_FAB_LOTS_COMPLETED_DTM$>,'DT'))
                        CurrStepId = Return_To_Fab_Services('GetRTFCurrStep', RTFId)
                        SRP_Json(hRTFJsonSingle, 'SetValue', 'CurrStepId', CurrStepId, 'Number')
                        SRP_Json(objReturnToFabReport, 'Add', hRTFJsonSingle)
                        SRP_Json(hRTFJsonSingle, 'Release')
                    end
                end else
                    Error_Services('Clear')
                end
            Next RTFId
            SRP_JSON(objJSON, 'Set', 'ReturnToFabReport', objReturnToFabReport)
            SRP_JSON(objReturnToFabReport, 'Release')
        end
        JsonString = SRP_JSON(objJSON, 'Stringify', 'Styled')
        SRP_JSON(objJSON, 'Release')
    end else
        ErrorMessage = 'Error creating root JSON object.'
    end
    If ErrorMessage NE '' then
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = ''
        LogData<4> = ''
        LogData<5> = ErrorMessage
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
        Error_Services('Add', ErrorMessage)
    end
    Response = JsonString
end service

Service GetReturnToFabRecordIdByCassId(CassId)
    ErrorMessage = ''
    RTFRecords   = ''
    If CassId NE '' then
        table = "RETURN_TO_FAB_LOTS"
        Open "DICT ":table To @DICT Else
            ErrorMessage = 'Error opening RETURN_TO_FAB_LOTS dictionary'
        End
        If ErrorMessage EQ '' then
            srch_strng  = "CASS_ID":@VM:CassId:@FM
            option      = ""
            flag        = ""
            Btree.Extract(srch_strng, table, @DICT, RTFRecords, option, flag)
        end
    end else
        ErrorMessage = 'Error getting return to fab record by cass. ID. Cassette ID was null'
    end
    If ErrorMessage EQ '' then
        Response = RTFRecords
    end else
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = CassId
        LogData<3> = ''
        LogData<4> = ''
        LogData<5> = ErrorMessage
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
        Error_Services('Add', ErrorMessage)
    end
End Service

Service GetAllReturnToFabRecords(ShowOnlyOpen)
    ErrorMessage = ''
    RTFRecords   = ''
    table = "RETURN_TO_FAB_LOTS"
    Open "DICT ":table To @DICT Else
        ErrorMessage = 'Error opening RETURN_TO_FAB_LOTS dictionary'
    End
    If ErrorMessage EQ '' then
        srch_strng  = "CASS_ID":@VM:"#NULL":@FM
        if ShowOnlyOpen then
            srch_strng := "COMPLETED":@VM:"#1":@FM
        end
        option      = ""
        flag        = ""
        Btree.Extract(srch_strng, table, @DICT, RTFRecords, option, flag)
    end
    If ErrorMessage EQ '' then
        Response = RTFRecords
    end else
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = ''
        LogData<4> = ''
        LogData<5> = ErrorMessage
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
        Error_Services('Add', ErrorMessage)
    end
end service

Service GetOpenReturnToFabRecordIdByCassId(CassId)
    ErrorMessage   = ''
    OpenRTFRecords = ''
    If CassId NE '' then
        table = "RETURN_TO_FAB_LOTS"
        Open "DICT ":table To @DICT Else
            ErrorMessage = 'Error opening RETURN_TO_FAB_LOTS dictionary'
        End
        If ErrorMessage EQ '' then
            srch_strng  = "CASS_ID":@VM:CassId:@FM:"COMPLETED":@VM:"#1":@FM
            option      = ""
            flag        = ""
            Btree.Extract(srch_strng, table, @DICT, OpenRTFRecords, option, flag)
        end
    end else
        ErrorMessage = 'Error getting return to fab record by cass. ID. Cassette ID was null'
    end
    If ErrorMessage EQ '' then
        Response = OpenRTFRecords
    end else
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = ''
        LogData<4> = ''
        LogData<5> = ErrorMessage
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
        Error_Services('Add', ErrorMessage)
    end
End Service

Service SetReasonForReturn(RTFId, UserId, Reason)
    ErrorMessage = ''
    If RTFId NE '' then
        If RowExists('RETURN_TO_FAB_LOTS', RTFId) then
            RTFCurrStep       = Return_To_Fab_Services('GetRTFCurrStep', RTFId)
            If RTFCurrStep LE 3 AND RTFCurrStep GE 1 then
                RTFRecord         = Database_Services('ReadDataRow', 'RETURN_TO_FAB_LOTS', RTFId, True$, 0, False$)
                RTFRecordComplete = RTFRecord<RETURN_TO_FAB_LOTS_COMPLETED$>
                If RTFRecordComplete NE True$ then
                    If UserId NE '' then
                        if RowExists('LSL_USERS', UserId) then
                            If Reason NE '' then
                                RTFRecord<RETURN_TO_FAB_LOTS_REASON$> = Reason
                                Database_Services('WriteDataRow', 'RETURN_TO_FAB_LOTS', RTFId, RTFRecord, True$, False$, False$)
                                If Error_Services('HasError') then
                                    ErrorMessage = Error_Services('GetMessage')
                                end
                            end else
                                ErrorMessage = 'Error setting return to fab reason. Reason was null.'  
                            end
                        end else
                            ErrorMessage = 'Error setting return to fab reason. User not found in openinsight.'
                        end
                    end else
                        ErrorMessage = 'Error setting return to fab reason. User ID was null.'
                    end
                end else
                    ErrorMessage = 'Error setting return to fab reason. Return to fab record has already been completed.' 
                end
            end else
                ErrorMessage = 'Error setting Return To Fab reason. Form is currently at step ': RTFCurrStep :'.' 
            end
        end else
            ErrorMessage = 'Error setting return to fab reason. Return to fab record did not exists'
        end
    end else
        ErrorMessage = 'Error setting return to fab reason. Return to fab record id was null'
    end
    if ErrorMessage EQ '' then
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = UserId
        LogData<4> = RTFId
        LogData<5> = 'Successfully set reason for return on RETURN_TO_FAB_LOTS record'
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
    end else
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = UserId
        LogData<4> = RTFId
        LogData<5> = ErrorMessage
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$) 
        Error_Services('Add', ErrorMessage) 
    end
end service

Service SetBinToBin(RTFId, MHUserId)
    ErrorMessage = ''
    If RTFId NE '' then
        If RowExists('RETURN_TO_FAB_LOTS', RTFId) then
            RTFCurrStep       = Return_To_Fab_Services('GetRTFCurrStep', RTFId)
            If RTFCurrStep EQ 3 then
                RTFRecord         = Database_Services('ReadDataRow', 'RETURN_TO_FAB_LOTS', RTFId, True$, 0, False$)
                RTFRecordComplete = RTFRecord<RETURN_TO_FAB_LOTS_COMPLETED$>
                If RTFRecordComplete NE True$ then
                    If MHUserId NE '' then
                        If RowExists('LSL_USERS', MHUserId) then
                            If MemberOf(MHUserId, 'MATERIAL HANDLER') then
                                RTFRecord<RETURN_TO_FAB_LOTS_MH_INIT_USER_ID$> = MHUserId
                                RTFRecord<RETURN_TO_FAB_LOTS_MH_INIT_DTM$>     = Datetime()
                                Database_Services('WriteDataRow', 'RETURN_TO_FAB_LOTS', RTFId, RTFRecord, True$, False$, False$)
                                If Error_Services('NoError') then
                                    //Send notification that a return to fab record was created.
                                    CassId             = RTFRecord<RETURN_TO_FAB_LOTS_CASS_ID$>
                                    RTFOrigUser        = RTFRecord<RETURN_TO_FAB_LOTS_REQUESTOR_USER_ID$>
                                    Message            = 'Return to fab form updated for ' : CassId : ' by ' : MHUserId : '.' : CRLF$
                                    Message           := 'Initial Bin to Bin has been marked as completed.' : CRLF$
                                    Message           := 'Link to Return To Fab form: https://goto.infineon.com/oiwizard/ReturnToFab'
                                    Recipients         = XLATE('NOTIFICATION','SHIPPING',NOTIFICATION_USER_ID$,'X')
                                    Recipients<1, -1>  = XLATE('NOTIFICATION','RETURN_TO_FAB_ENG',NOTIFICATION_USER_ID$,'X')
                                    Recipients<1, -1>  = XLATE('NOTIFICATION','RETURN_TO_FAB_MANUF',NOTIFICATION_USER_ID$,'X')
                                    Recipients<1, -1>  = XLATE('NOTIFICATION','RETURN_TO_FAB_GENERAL',NOTIFICATION_USER_ID$,'X')
                                    Recipients<1, -1>  = RTFOrigUser
                                    SentFrom           = 'OI_ADMIN'
                                    Subject            = 'Return To Fab Form Updated'
                                    SendToGroup        = ''
                                    AttachWindow       = ''
                                    AttachKey          = ''
                                    Parms              = Recipients:@RM:SentFrom:@RM:Subject:@RM:Message:@RM:AttachWindow:@RM:AttachKey:@RM:SendToGroup
                                    obj_Notes('Create',Parms)
                                end else
                                    ErrorMessage = Error_Services('GetMessage')
                                end  
                            end else
                                ErrorMessage = 'Error setting Initial SAP Bin-to-Bin. User does not have permissions to perform this function. User must be apart of OI Security Group "MATERIAL HANDLER"'
                            end
                        end else
                            ErrorMessage = 'Error setting Initial SAP Bin-to-Bin. Material Handler User ID was not found in OpenInsight.'
                        end
                    end else
                        ErrorMessage = 'Error setting Initial SAP Bin-to-Bin. Material Handler User ID was null.'  
                    end
                end else
                    ErrorMessage = 'Error setting Initial SAP Bin-to-Bin. Return to fab record has already been completed.' 
                end    
            end else
                ErrorMessage = 'Error setting Initial SAP Bin-to-Bin. Form is currently at step ': RTFCurrStep :'.'  
            end
        end else
            ErrorMessage = 'Error setting Initial SAP Bin-to-Bin. Return to fab record did not exists'
        end
    end else
        ErrorMessage = 'Error setting Initial SAP Bin-to-Bin. Return to fab record id was null'
    end
    If ErrorMessage EQ '' then
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = MHUserId
        LogData<4> = RTFId
        LogData<5> = 'Successfully set bin to bin complete on RETURN_TO_FAB_LOTS record'
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
    end else
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = MHUserId
        LogData<4> = RTFId
        LogData<5> = ErrorMessage
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
        Error_Services('Add', ErrorMessage)
    end
end service

Service SetRTFCompleted(RTFId, CompleteUserId)
    ErrorMessage = ''
    If RTFId NE '' then
        If RowExists('RETURN_TO_FAB_LOTS', RTFId) then
            RTFRecord         = Database_Services('ReadDataRow', 'RETURN_TO_FAB_LOTS', RTFId, True$, 0, False$)
            RTFRecordComplete = RTFRecord<RETURN_TO_FAB_LOTS_COMPLETED$>
            If RTFRecordComplete NE True$ then
                If CompleteUserId NE '' then
                    If RowExists('LSL_USERS', CompleteUserId) then
                        RTFRecord<RETURN_TO_FAB_LOTS_COMPLETED$>     = True$
                        RTFRecord<RETURN_TO_FAB_LOTS_COMPLETED_DTM$> = Datetime()
                        Database_Services('WriteDataRow', 'RETURN_TO_FAB_LOTS', RTFId, RTFRecord, True$, False$, False$)
                        If Error_Services('NoError') then
                            //Send notification that a return to fab record was created.
                            CassId             = RTFRecord<RETURN_TO_FAB_LOTS_CASS_ID$>
                            RTFOrigUser        = RTFRecord<RETURN_TO_FAB_LOTS_REQUESTOR_USER_ID$>
                            Message            = 'Return to fab form updated for ' : CassId : ' by ' : CompleteUserId : '.' : CRLF$
                            Message           := 'Return to fab marked as completed.' : CRLF$
                            Message           := 'Link to Return To Fab form: https://goto.infineon.com/oiwizard/ReturnToFab'
                            Recipients         = XLATE('NOTIFICATION','SHIPPING',NOTIFICATION_USER_ID$,'X')
                            Recipients<1, -1>  = XLATE('NOTIFICATION','RETURN_TO_FAB_ENG',NOTIFICATION_USER_ID$,'X')
                            Recipients<1, -1>  = XLATE('NOTIFICATION','RETURN_TO_FAB_MANUF',NOTIFICATION_USER_ID$,'X')
                            Recipients<1, -1>  = XLATE('NOTIFICATION','RETURN_TO_FAB_GENERAL',NOTIFICATION_USER_ID$,'X')
                            Recipients<1, -1>  = RTFRecord<RETURN_TO_FAB_LOTS_REQUESTOR_USER_ID$>
                            SentFrom           = 'OI_ADMIN'
                            Subject            = 'Return To Fab Form Completed'
                            SendToGroup        = ''
                            AttachWindow       = ''
                            AttachKey          = ''
                            Parms              = Recipients:@RM:SentFrom:@RM:Subject:@RM:Message:@RM:AttachWindow:@RM:AttachKey:@RM:SendToGroup
                            obj_Notes('Create',Parms)
                        end else
                            ErrorMessage = Error_Services('GetMessage')
                        end
                    end else
                        ErrorMessage = 'Error setting Return To Fab form as complete. User ID was not found in OpenInsight.'
                    end
                end else
                    ErrorMessage = 'Error setting Return To Fab form as complete. User ID was null.'  
                end
            end else
                ErrorMessage = 'Error setting Return To Fab form as complete. Return to fab record has already been completed.' 
            end
        end else
            ErrorMessage = 'Error setting Return To Fab form as complete. Return to fab record did not exists'
        end
    end else
        ErrorMessage = 'Error setting Return To Fab form as complete. Return to fab record id was null'
    end
    If ErrorMessage EQ '' then
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = CompleteUserId
        LogData<4> = RTFId
        LogData<5> = 'Successfully set bin to bin complete on RETURN_TO_FAB_LOTS record'
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
    end else
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = CompleteUserId
        LogData<4> = RTFId
        LogData<5> = ErrorMessage
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
        Error_Services('Add', ErrorMessage)
    end
end service

Service SetEvalInfo(RTFId, EvalUserId, ResultId)
    ErrorMessage = ''
    If RTFId NE '' then
        if RowExists('RETURN_TO_FAB_LOTS', RTFId) then
            RTFCurrStep       = Return_To_Fab_Services('GetRTFCurrStep', RTFId)
            If RTFCurrStep EQ 4 OR RTFCurrStep EQ 5 then
                If EvalUserId NE '' then
                    if RowExists('LSL_USERS', EvalUserId) then
                        If ResultId NE '' then
                            If RowExists('RETURN_TO_FAB_RESULT_OPTION', ResultId) then
                                RTFRecord         = Database_Services('ReadDataRow', 'RETURN_TO_FAB_LOTS', RTFId, True$, 0, False$)
                                RTFRecordComplete = RTFRecord<RETURN_TO_FAB_LOTS_COMPLETED$>
                                If RTFRecordComplete NE True$ then
                                    RTFRecord<RETURN_TO_FAB_LOTS_EVAL_USER_ID$>   = EvalUserId
                                    RTFRecord<RETURN_TO_FAB_LOTS_EVAL_RESULT_ID$> = ResultId
                                    RTFRecord<RETURN_TO_FAB_LOTS_EVAL_DTM$>       = Datetime()
                                    Database_Services('WriteDataRow', 'RETURN_TO_FAB_LOTS', RTFId, RTFRecord, True$, False$, False$)
                                    If Error_Services('NoError') then
                                        ResultDescription  = XLate('RETURN_TO_FAB_RESULT_OPTION', ResultId, RETURN_TO_FAB_RESULT_OPTION_RESULT$, 'X')
                                        //Send notification that a return to fab record was created.
                                        CassId             = RTFRecord<RETURN_TO_FAB_LOTS_CASS_ID$>
                                        RTFOrigUser        = RTFRecord<RETURN_TO_FAB_LOTS_REQUESTOR_USER_ID$>
                                        Message            = 'Return to fab form updated for ' : CassId : ' by ' : EvalUserId : '.' : CRLF$
                                        Message           := 'Result has been set to ' : ResultDescription : '.' : CRLF$
                                        Message           := 'Link to Return To Fab form: https://goto.infineon.com/oiwizard/ReturnToFab'
                                        Recipients         = XLATE('NOTIFICATION','SHIPPING',NOTIFICATION_USER_ID$,'X')
                                        Recipients<1, -1>  = XLATE('NOTIFICATION','RETURN_TO_FAB_ENG',NOTIFICATION_USER_ID$,'X')
                                        Recipients<1, -1>  = XLATE('NOTIFICATION','RETURN_TO_FAB_MANUF',NOTIFICATION_USER_ID$,'X')
                                        Recipients<1, -1>  = XLATE('NOTIFICATION','RETURN_TO_FAB_GENERAL',NOTIFICATION_USER_ID$,'X')
                                        Recipients<1, -1>  = RTFRecord<RETURN_TO_FAB_LOTS_REQUESTOR_USER_ID$>
                                        SentFrom           = 'OI_ADMIN'
                                        Subject            = 'Return To Fab Form Updated'
                                        SendToGroup        = ''
                                        AttachWindow       = ''
                                        AttachKey          = ''
                                        Parms              = Recipients:@RM:SentFrom:@RM:Subject:@RM:Message:@RM:AttachWindow:@RM:AttachKey:@RM:SendToGroup
                                        obj_Notes('Create',Parms)
                                    end else
                                        ErrorMessage = Error_Services('GetMessage')
                                    end
                                end else
                                    ErrorMessage = 'Error setting Eval. info. Return to fab record has already been completed.' 
                                end
                                //Possbile to add auto-closing logic here.
                                
                            end else
                                ErrorMessage = 'Error setting Eval. info. Result was an invalid result option.'
                            end
                        end else
                            ErrorMessage = 'Error setting Eval. info. Result was null.'
                        end
                    end else
                        ErrorMessage = 'Error setting Eval. info. Evaluation user is not a valid OpenInsight user.' 
                    end
                end else
                    ErrorMessage = 'Error setting Eval. info. Evaluation user id was null.'
                end
            end else
                ErrorMessage = 'Error setting Eval. info. Form is currently at step ': RTFCurrStep :'.'
            end
        end else
            ErrorMessage = 'Error setting Eval. info. Return to fab record was not found.'
        end
    end else
        ErrorMessage = 'Error setting Eval. info. Return to fab id was null.'
    end
    If ErrorMessage EQ '' then
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = EvalUserId
        LogData<4> = RTFId
        LogData<5> = 'Successfully set evaluation result on RETURN_TO_FAB_LOTS record'
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
    end else
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = EvalUserId
        LogData<4> = RTFId
        LogData<5> = ErrorMessage
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
        Error_Services('Add', ErrorMessage)
    end
end service

Service SetFinalBinToBin(RTFId, MHUserId)
    ErrorMessage = ''
    If RTFId NE '' then
        If RowExists('RETURN_TO_FAB_LOTS', RTFId) then
            RTFCurrStep       = Return_To_Fab_Services('GetRTFCurrStep', RTFId)
            If RTFCurrStep EQ 5 then
                RTFRecord         = Database_Services('ReadDataRow', 'RETURN_TO_FAB_LOTS', RTFId, True$, 0, False$)
                RTFRecordComplete = RTFRecord<RETURN_TO_FAB_LOTS_COMPLETED$>
                If RTFRecordComplete NE True$ then
                    If MHUserId NE '' then
                        If RowExists('LSL_USERS', MHUserId) then
                            If MemberOf(MHUserId, 'MATERIAL HANDLER') then
                                RTFRecord<RETURN_TO_FAB_LOTS_FINAL_COMPLETE_USER_ID$> = MHUserId
                                RTFRecord<RETURN_TO_FAB_LOTS_FINAL_COMPLETE_DTM$> = Datetime()
                                Database_Services('WriteDataRow', 'RETURN_TO_FAB_LOTS', RTFId, RTFRecord, True$, False$, False$)
                                If Error_Services('HasError') then
                                    ErrorMessage = Error_Services('GetMessage')
                                end 
                            end else
                                ErrorMessage = 'Error setting Final SAP Bin-to-Bin. User does not have permissions to perform this function. User must be apart of OI Security Group "MATERIAL HANDLER"' 
                            end
                        end else
                            ErrorMessage = 'Error setting Final SAP Bin-to-Bin. Material Handler User ID was not found in OpenInsight.'
                        end
                        
                    end else
                        ErrorMessage = 'Error setting Final SAP Bin-to-Bin. Material Handler User ID was null.'  
                    end
                end else
                    ErrorMessage = 'Error setting Final SAP Bin-to-Bin. Return to fab record has already been completed.' 
                end
            end else
                ErrorMessage = 'Error setting Final SAP Bin-to-Bin. Form is currently at step ': RTFCurrStep :'.' 
            end
        end else
            ErrorMessage = 'Error setting Final SAP Bin-to-Bin. Return to fab record did not exists'
        end
    end else
        ErrorMessage = 'Error setting Final SAP Bin-to-Bin. Return to fab record id was null'
    end
    If ErrorMessage EQ '' then
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = MHUserId
        LogData<4> = RTFId
        LogData<5> = 'Successfully set final bin to bin on RETURN_TO_FAB_LOTS record'
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
    end else
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = MHUserId
        LogData<4> = RTFId
        LogData<5> = ErrorMessage
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
        Error_Services('Add', ErrorMessage)
    end   
end service

Service AddMiscNote(RTFId, Note, UserId)
    ErrorMessage = ''
    If RTFId NE '' then
        If RowExists('RETURN_TO_FAB_LOTS', RTFId) then
            RTFRecord         = Database_Services('ReadDataRow', 'RETURN_TO_FAB_LOTS', RTFId, True$, 0, False$)
            RTFRecordComplete = RTFRecord<RETURN_TO_FAB_LOTS_COMPLETED$>
            If RTFRecordComplete NE True$ then
                If UserId NE '' then
                    If RowExists('LSL_USERS', UserId) then
                        RTFRecord<RETURN_TO_FAB_LOTS_NOTES$>      = Insert(RTFRecord<RETURN_TO_FAB_LOTS_NOTES$>, 1, -1, 0, Note)
                        RTFRecord<RETURN_TO_FAB_LOTS_NOTES_USER$> = Insert(RTFRecord<RETURN_TO_FAB_LOTS_NOTES_USER$>, 1, -1, 0, UserId)
                        Database_Services('WriteDataRow', 'RETURN_TO_FAB_LOTS', RTFId, RTFRecord, True$, False$, False$)
                        If Error_Services('HasError') then
                            ErrorMessage = Error_Services('GetMessage')
                        end 
                    end else
                        ErrorMessage = 'Error adding note to RTF Record. User ID was not found in OpenInsight.'
                    end
                end else
                    ErrorMessage = 'Error adding note to RTF Record. User ID was null.'  
                end
            end else
                ErrorMessage = 'Error adding note to RTF Record. Return to fab record has already been completed.' 
            end
        end else
            ErrorMessage = 'Error adding note to RTF Record. Return to fab record did not exists'
        end
    end else
        ErrorMessage = 'Error adding note to RTF Record. Return to fab record id was null'
    end
    If ErrorMessage EQ '' then
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = UserId
        LogData<4> = RTFId
        LogData<5> = 'Successfully added note to RETURN_TO_FAB_LOTS record'
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
    end else
        LogData    = ''
        LogData<1> = LoggingDTM;//Defined at entry of subroutine
        LogData<2> = ''
        LogData<3> = UserId
        LogData<4> = RTFId
        LogData<5> = ErrorMessage
        Logging_Services('AppendLog', objReturnToFabLog, LogData, @RM, @FM, False$)
        Error_Services('Add', ErrorMessage)
    end   
end service

Service GetRTFCurrStep(RTFId)
    CurrStep  = 0
    RTFRecord = Database_Services('ReadDataRow', 'RETURN_TO_FAB_LOTS', RTFId, True$, 0, False$)
    If RTFRecord NE '' then
        CurrStep = 1
        If RTFRecord<RETURN_TO_FAB_LOTS_REASON$> NE '' then
            //Skip 2 because step 2 is an adhoc step(printing a label)
            CurrStep = 3
            If RTFRecord<RETURN_TO_FAB_LOTS_MH_INIT_USER_ID$> NE '' then
                CurrStep = 4
                If RTFRecord<RETURN_TO_FAB_LOTS_EVAL_RESULT_ID$> NE '' AND RTFRecord<RETURN_TO_FAB_LOTS_EVAL_RESULT_ID$> NE 0 then
                    CurrStep = 5
                    If RTFRecord<RETURN_TO_FAB_LOTS_FINAL_COMPLETE_USER_ID$> NE '' then
                        CurrStep = 6
                    end
                end
            end
        end
    end
    Response = CurrStep
end service

Service OpenOIWizardReturnToFabInBrowser(RTFId)
    Command = 'explorer https://goto.infineon.com/oiwizard/returntofab/' : RTFId
    SRP_Run_Command(Command)
end service







