// *************************************
// Title: Work Orders - Type Check
// Author: Fluke Calibration
// Date: 2016-03-01
//
// This data check verifies whether the
// asset's type record is inactive,
// and corrects type mismatches between
// the work order and the asset.
// *************************************

/*
SQL Function 1: GetTypeInfo
SELECT c.lClosed, c.nTypeUID 'csTypeUID', a.nTypeUID 'aTypeUID', t.lActive
FROM dbo.CallSheets c
    INNER JOIN dbo.Assets a ON c.nAssetUID = a.nAssetUID
    INNER JOIN dbo.Types t ON a.nTypeUID = t.nTypeUID
WHERE c.nCallSheetUID = strUID
*/

// Grab information about the type
DataCheck.ExecuteSQL('GetTypeInfo', function(result) {
    // If the work order is closed, do nothing
    if (result[0].lClosed != 0) {
        pass();
        return;
    }
    
    // If there is a work order/asset type mismatch, fix the work order
    if (result[0].csTypeUID != result[0].aTypeUID) {
        DataCheck.Alert('Attention', 'A correction was made to fix a type ' +
                        'record mismatch between this work order and its ' +
                        'asset.', function() {
                DataCheck.SetValue('nTypeUID', result[0].aTypeUID);
                DataCheck.SetValue('nProcedureUID', undefined);
                DataCheck.SetValue('nTypeProcedureDefaultUID', undefined);
                if (result[0].lActive == 0)
                    DataCheck.Alert('Attention', 'This work order cannot be saved ' +
                                    'because its type is inactive.', function() {fail();});
                else
                    pass();
        });
    } else {
        // If the type is inactive, fail.
        if (result[0].lActive == 0)
            DataCheck.Alert('Attention', 'This work order cannot be saved ' +
                            'because its type is inactive.', function() {fail();});
        else
            pass();
    }
});