<commit_before>/**
 * This file is part of the DreamFactory Services Platform(tm) (DSP)
 *
 * DreamFactory Services Platform(tm) <http://github.com/dreamfactorysoftware/dsp-core>
 * Copyright 2012-2014 DreamFactory Software, Inc. <support@dreamfactory.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var SchemaCtrl = function( $scope, Schema, DSP_URL, DB, $http, getSchemaServices ) {

//	Scope.showJSON = function() {
//        $( "#create-form" ).hide();
//        $( "#grid-container" ).hide();
//		$( "#json_upload" ).show();
//	};
//	Scope.postJSON = function() {
//		var json = $( '#source' ).val();
//		Schema.save(
//			json, function( data ) {
//				if ( !data.table ) {
//					Scope.schemaData.push( data );
//				}
//				else {
//					data.table.forEach(
//						function( table ) {
//							Scope.schemaData.push( table );
//						}
//					)
//				}
//
//			}
//		);
//
//	};
//	Scope.enableSave = function() {
//		$( "#save_" + this.row.rowIndex ).attr( 'disabled', false );
//		//console.log(this);
//	};
//	Scope.enableSchemaSave = function() {
//		$( "#add_" + this.row.rowIndex ).attr( 'disabled', false );
//		$( "#delete_" + this.row.rowIndex ).attr( 'disabled', false );
//		$( "#save_" + this.row.rowIndex ).attr( 'disabled', false );
//		//console.log(this);
//	};
//
//	Scope.saveRow = function() {
//
//		var index = this.row.rowIndex;
//		var newRecord = this.row.entity;
//		if ( !newRecord.id ) {
//			DB.save(
//				{name: Scope.currentTable}, newRecord, function( data ) {
//					$( "#save_" + index ).attr( 'disabled', true );
//					Scope.tableData.push( data );
//				}
//			);
//		}
//		else {
//			DB.update(
//				{name: Scope.currentTable}, newRecord, function() {
//					$( "#save_" + index ).attr( 'disabled', true );
//				}
//			);
//		}
//
//	};
//	Scope.schemaSaveRow = function() {
//
//		var table = this.tableSchema.name;
//		var row = this.row.entity;
//
//		$http.put( '/rest/schema/' + table + '/?app_name=admin', row ).success(
//			function( data ) {
//				Scope.tableData = removeByAttr( Scope.tableData, 'new', true );
//				Scope.tableData.unshift( data );
//				Scope.tableData.unshift( {"new": true} );
//			}
//		);
//
//	};
//	Scope.deleteRow = function() {
//		var id = this.row.entity.id;
//		DB.delete( {name: Scope.currentTable}, {id: id} );
//		Scope.tableData = removeByAttr( Scope.tableData, 'id', id );
//
//	}
    Scope = $scope;
    $scope.typeOptions = [
        {value: "id"},
        {value: "string"},
        {value: "integer"},
        {value: "text"},
        {value: "boolean"},
        {value: "binary"},
        {value: "float"},
        {value: "decimal"},
        {value: "datetime"},
        {value: "date"},
        {value: "time"},
        {value: "reference"},
        {value: "user_id"},
        {value: "user_id_on_create"},
        {value: "user_id_on_update"},
        {value: "timestamp_on_create"},
        {value: "timestamp_on_update"}
    ];
    var editor;
    $scope.table = {};
    $scope.service = {};
    $scope.advanced = false;
    var service;
    editor = ace.edit("schema-editor");
    editor.getSession().setMode("ace/mode/json");
    $scope.dbServices = getSchemaServices.data.record;
    //console.log($scope.dbServices);
    $scope.loadServices = function(){
        $scope.dbServices.forEach(function(service){
            $http.get(DSP_URL + "/rest/" + service.api_name + "?include_schema=true").then(function(response){

                service.tables = [];
                response.data.resource.forEach(function(table){

                    service.tables.push(table);
                })
            });
        })
    }
    $scope.loadServices();
    $scope.loadSchema = function(advanced){
        $scope.table = this.table;
        $scope.service = this.service.api_name;
        $http.get(CurrentServer + "/rest/" + this.service.api_name + "/" + this.table.name)
            .then(function(response){
                $scope.table.schema = response;
                //console.log(table.schema);
                if(advanced){
                    $scope.advanced = true;
                    editor.setValue(angular.toJson($scope.table.schema.data, true), -1);
                }else{
                    $scope.advanced = false;
                }

            })
    }
    $scope.toggleJSON = function(){
        if($scope.advanced){
            $scope.table.schema.data = JSON.parse(editor.getValue());
            $scope.advanced = false;
        }else{
            $scope.advanced = true;
            editor.setValue(angular.toJson($scope.table.schema.data, true), -1);
        }
    }
    $scope.addColumn = function(){
       $scope.newColumn = {
           name : "New Column"
       }
       $scope.table.schema.data.field.unshift($scope.newColumn)
    }
    $scope.deleteColumn = function(){
        console.log(this);
        if ( !confirm( "Are you sure you want to delete " + this.column.name) ) {
            return;
        }
        $scope.table.schema.data.field.splice(this.$index, 1);
        $(function(){
            new PNotify({
                title: 'Schema',
                text: 'Column removed from working set, press Update Schema to save changes',
                type: 'warning'
            });
        });

    }
    $scope.updateJSONSchema = function(){
        $http.put(CurrentServer + "/rest/" + $scope.service + "/" + $scope.table.name, editor.getValue()).then(function(response){
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Updated Successfully',
                    type: 'success'
                });
            });
        })
    }
    $scope.updateSchema = function(){
        $http.put(CurrentServer + "/rest/" + $scope.service + "/" + $scope.table.name, $scope.table.schema.data).then(function(response){
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Updated Successfully',
                    type: 'success'
                });
            });
        })
    }
    $scope.createTable = function(){
        var requestObject = {
            name : this.newTableName,
            field: [
                {name : "id",
                 type : "id"
                }
            ]
        };
        $http.post(CurrentServer + "/rest/" + this.service.api_name , requestObject).then(function(response){
            $scope.loadServices();
        })
    }

    $scope.dropTable = function(){
        if ( !confirm( "Are you sure you want to delete " + this.table.name) ) {
            return;
        }
        $http.delete(CurrentServer + "/rest/" + this.service.api_name + "/" + this.table.name).then(function(response){
            $scope.loadServices();
        })
    }
    $scope.validateJSON = function() {
        try {
            var result = JSON.parse( editor.getValue() );
            if ( result ) {
                $(function(){
                    new PNotify({
                        title: 'Schema',
                        text: 'JSON is valid',
                        type: 'success'
                    });
                });

            }
        }
        catch ( e ) {
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: e,
                    type: 'error'
                });
            });
        }
    };
};

<commit_msg>JSON prettify on lint<commit_after>/**
 * This file is part of the DreamFactory Services Platform(tm) (DSP)
 *
 * DreamFactory Services Platform(tm) <http://github.com/dreamfactorysoftware/dsp-core>
 * Copyright 2012-2014 DreamFactory Software, Inc. <support@dreamfactory.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var SchemaCtrl = function( $scope, Schema, DSP_URL, DB, $http, getSchemaServices ) {

//	Scope.showJSON = function() {
//        $( "#create-form" ).hide();
//        $( "#grid-container" ).hide();
//		$( "#json_upload" ).show();
//	};
//	Scope.postJSON = function() {
//		var json = $( '#source' ).val();
//		Schema.save(
//			json, function( data ) {
//				if ( !data.table ) {
//					Scope.schemaData.push( data );
//				}
//				else {
//					data.table.forEach(
//						function( table ) {
//							Scope.schemaData.push( table );
//						}
//					)
//				}
//
//			}
//		);
//
//	};
//	Scope.enableSave = function() {
//		$( "#save_" + this.row.rowIndex ).attr( 'disabled', false );
//		//console.log(this);
//	};
//	Scope.enableSchemaSave = function() {
//		$( "#add_" + this.row.rowIndex ).attr( 'disabled', false );
//		$( "#delete_" + this.row.rowIndex ).attr( 'disabled', false );
//		$( "#save_" + this.row.rowIndex ).attr( 'disabled', false );
//		//console.log(this);
//	};
//
//	Scope.saveRow = function() {
//
//		var index = this.row.rowIndex;
//		var newRecord = this.row.entity;
//		if ( !newRecord.id ) {
//			DB.save(
//				{name: Scope.currentTable}, newRecord, function( data ) {
//					$( "#save_" + index ).attr( 'disabled', true );
//					Scope.tableData.push( data );
//				}
//			);
//		}
//		else {
//			DB.update(
//				{name: Scope.currentTable}, newRecord, function() {
//					$( "#save_" + index ).attr( 'disabled', true );
//				}
//			);
//		}
//
//	};
//	Scope.schemaSaveRow = function() {
//
//		var table = this.tableSchema.name;
//		var row = this.row.entity;
//
//		$http.put( '/rest/schema/' + table + '/?app_name=admin', row ).success(
//			function( data ) {
//				Scope.tableData = removeByAttr( Scope.tableData, 'new', true );
//				Scope.tableData.unshift( data );
//				Scope.tableData.unshift( {"new": true} );
//			}
//		);
//
//	};
//	Scope.deleteRow = function() {
//		var id = this.row.entity.id;
//		DB.delete( {name: Scope.currentTable}, {id: id} );
//		Scope.tableData = removeByAttr( Scope.tableData, 'id', id );
//
//	}
    Scope = $scope;
    $scope.typeOptions = [
        {value: "id"},
        {value: "string"},
        {value: "integer"},
        {value: "text"},
        {value: "boolean"},
        {value: "binary"},
        {value: "float"},
        {value: "decimal"},
        {value: "datetime"},
        {value: "date"},
        {value: "time"},
        {value: "reference"},
        {value: "user_id"},
        {value: "user_id_on_create"},
        {value: "user_id_on_update"},
        {value: "timestamp_on_create"},
        {value: "timestamp_on_update"}
    ];
    var editor;
    $scope.table = {};
    $scope.service = {};
    $scope.advanced = false;
    var service;
    editor = ace.edit("schema-editor");
    editor.getSession().setMode("ace/mode/json");
    $scope.dbServices = getSchemaServices.data.record;
    //console.log($scope.dbServices);
    $scope.loadServices = function(){
        $scope.dbServices.forEach(function(service){
            $http.get(DSP_URL + "/rest/" + service.api_name + "?include_schema=true").then(function(response){

                service.tables = [];
                response.data.resource.forEach(function(table){

                    service.tables.push(table);
                })
            });
        })
    }
    $scope.loadServices();
    $scope.loadSchema = function(advanced){
        $scope.table = this.table;
        $scope.service = this.service.api_name;
        $http.get(CurrentServer + "/rest/" + this.service.api_name + "/" + this.table.name)
            .then(function(response){
                $scope.table.schema = response;
                //console.log(table.schema);
                if(advanced){
                    $scope.advanced = true;
                    editor.setValue(angular.toJson($scope.table.schema.data, true), -1);
                }else{
                    $scope.advanced = false;
                }

            })
    }
    $scope.toggleJSON = function(){
        if($scope.advanced){
            $scope.table.schema.data = JSON.parse(editor.getValue());
            $scope.advanced = false;
        }else{
            $scope.advanced = true;
            editor.setValue(angular.toJson($scope.table.schema.data, true), -1);
        }
    }
    $scope.addColumn = function(){
       $scope.newColumn = {
           name : "New Column"
       }
       $scope.table.schema.data.field.unshift($scope.newColumn)
    }
    $scope.deleteColumn = function(){
        console.log(this);
        if ( !confirm( "Are you sure you want to delete " + this.column.name) ) {
            return;
        }
        $scope.table.schema.data.field.splice(this.$index, 1);
        $(function(){
            new PNotify({
                title: 'Schema',
                text: 'Column removed from working set, press Update Schema to save changes',
                type: 'warning'
            });
        });

    }
    $scope.updateJSONSchema = function(){
        $http.put(CurrentServer + "/rest/" + $scope.service + "/" + $scope.table.name, editor.getValue()).then(function(response){
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Updated Successfully',
                    type: 'success'
                });
            });
        })
    }
    $scope.updateSchema = function(){
        $http.put(CurrentServer + "/rest/" + $scope.service + "/" + $scope.table.name, $scope.table.schema.data).then(function(response){
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Updated Successfully',
                    type: 'success'
                });
            });
        })
    }
    $scope.createTable = function(){
        var requestObject = {
            name : this.newTableName,
            field: [
                {name : "id",
                 type : "id"
                }
            ]
        };
        $http.post(CurrentServer + "/rest/" + this.service.api_name , requestObject).then(function(response){
            $scope.loadServices();
        })
    }

    $scope.dropTable = function(){
        if ( !confirm( "Are you sure you want to delete " + this.table.name) ) {
            return;
        }
        $http.delete(CurrentServer + "/rest/" + this.service.api_name + "/" + this.table.name).then(function(response){
            $scope.loadServices();
        })
    }
    $scope.validateJSON = function() {
        try {
            var result = JSON.parse( editor.getValue() );
            if ( result ) {
                $(function(){
                    new PNotify({
                        title: 'Schema',
                        text: 'JSON is valid',
                        type: 'success'
                    });
                });
            editor.setValue(angular.toJson(result, true), -1);
            }
        }
        catch ( e ) {
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: e,
                    type: 'error'
                });
            });
        }
    };
};

<|endoftext|>


<commit_before>/**
 * This file is part of the DreamFactory Services Platform(tm) (DSP)
 *
 * DreamFactory Services Platform(tm) <http://github.com/dreamfactorysoftware/dsp-core>
 * Copyright 2012-2014 DreamFactory Software, Inc. <support@dreamfactory.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var SchemaCtrl = function( dfLoadingScreen, $scope, DSP_URL, DB, $http, getSchemaServices ) {

    dfLoadingScreen.stop();

    Scope = $scope;
    $scope.typeOptions = [
        {name : "I will manually enter a type" , value: ""},
        {name : "id",value: "id"},
        {name : "string", value: "string"},
        {name: "integer",value: "integer"},
        {name: "text", value: "text"},
        {name: "boolean", value: "boolean"},
        {name: "binary", value: "binary"},
        {name: "float", value: "float"},
        {name: "double", value: "double"},
        {name: "decimal", value: "decimal"},
        {name: "datetime", value: "datetime"},
        {name: "date", value: "date"},
        {name: "time", value: "time"},
        {name: "reference", value: "reference"},
        {name: "user_id", value: "user_id"},
        {name: "user_id_on_create",value: "user_id_on_create"},
        {name: "user_id_on_update",value: "user_id_on_update"},
        {name: "timestamp",value: "timestamp"},
        {name: "timestamp_on_create",value: "timestamp_on_create"},
        {name: "timestamp_on_update",value: "timestamp_on_update"}

    ];
    var editor;
    $scope.table = {};
    //$scope.service = {;
    $scope.advanced = false;
    //var service;
    editor = ace.edit("schema-editor");
    editor.getSession().setMode("ace/mode/json");
    $scope.dbServices = getSchemaServices.data.record;
    //console.log($scope.dbServices);
    $scope.loadServices = function(current){
        $scope.currentTables = [];
        if(current){
            $http.get(DSP_URL + "/rest/" + $scope.service + "/_schema").then(function(response){
                //console.log( $scope.dbServices[$scope.service]);
                $scope.dbServices[$scope.service_index].tables = [];
                response.data.resource.forEach(function(table){
                    $scope.dbServices[$scope.service_index].tables.push(table);
                    //$scope.currentTables.push(table.name);
                })
            });
        }else{
            $scope.dbServices.forEach(function(service, index){
                $http.get(DSP_URL + "/rest/" + service.api_name + "/_schema").then(function(response){

                    service.tables = [];

                    service.service_index = index;
                    response.data.resource.forEach(function(table){

                        service.tables.push(table);
                        $scope.currentTables.push(table.name);

                    })
                });
            })
        }

    }
    $scope.reloadService = function(){
        var service = this.service;
        $http.get(DSP_URL + "/rest/" + service.api_name + "/_schema?reload=true").then(function(response){
            //console.log( $scope.dbServices[$scope.service]);
            $scope.dbServices[service.service_index].tables = [];
            response.data.resource.forEach(function(table){
                $scope.dbServices[service.service_index].tables.push(table);
                //$scope.currentTables.push(table.name);
            })
        });
    }
    $scope.loadServices();
    $scope.referenceFields  = [];
    $scope.loadNewSchema = function(table){
        $scope.import = false;
        $scope.table = table;
        $http.get(CurrentServer + "/rest/" + $scope.service + "/_schema/" + $scope.table.name)
            .then(function(response){
                $scope.table.schema = response;
            })
    }
    $scope.loadSchema = function(advanced){
        $scope.import = false;
        $scope.table = this.table;
        $scope.currentTables = $scope.dbServices[this.service.service_index].tables;
        $scope.currentTable = $scope.table.name;
        $scope.service = this.service.api_name;
        $scope.service_index = this.service.service_index;
        $http.get(CurrentServer + "/rest/" + this.service.api_name + "/_schema/" + this.table.name)
            .then(function(response){
                $scope.table.schema = response;
                //console.log(table.schema);
                if(advanced){
                    $scope.advanced = true;
                    editor.setValue(angular.toJson($scope.table.schema.data, true), -1);
                }else{
                    $scope.advanced = false;

                }

            })
    }
    $scope.loadReferenceFields = function(){
        console.log(this);
        if(!this.column.ref_table){
            return;
        }
        var refTable = this.column.ref_table;
        $http.get(CurrentServer + "/rest/" + $scope.service + "/_schema/" + refTable)
            .then(function(response){
                $scope.referenceFields = response.data.field;

            })
    }
    $scope.showImport = function(){
        editor.setValue("");
        $scope.advanced = true;
        $scope.import = true;
    }
    $scope.toggleJSON = function(){
        if($scope.advanced){
            $scope.table.schema.data = JSON.parse(editor.getValue());
            $scope.advanced = false;
        }else{
            $scope.advanced = true;
            editor.setValue(angular.toJson($scope.table.schema.data, true), -1);
        }
    }
    $scope.addColumn = function(){
        $scope.newColumn = {
            name : "New_Column",
            is_new : true,
            type : "string"
        };
        //$scope.currentField = "New_Column";
        $scope.table.schema.data.field.unshift($scope.newColumn)
    }
    $scope.deleteColumn = function(){
        //console.log(this);
        if ( !confirm( "Are you sure you want to delete " + this.column.name) ) {
            return;
        }
        $scope.table.schema.data.field.splice(this.$index, 1);
        $(function(){
            new PNotify({
                title: 'Schema',
                text: 'Column removed from working set, press Update Schema to save changes',
                type: 'warning'
            });
        });

    }
    $scope.updateJSONSchema = function(){
        $http.put(CurrentServer + "/rest/" + $scope.service + "/_schema?return_schema=true" , editor.getValue()).then(function(response){

            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Updated Successfully',
                    type: 'success'
                });
            });
        })
    }
    $scope.updateSchema = function(){
        $http.put(CurrentServer + "/rest/" + $scope.service + "/_schema?return_schema=true" , {table:$scope.table.schema.data}).then(function(response){
            $scope.table.schema.data = response.data.table[0];
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Updated Successfully',
                    type: 'success'
                });
            });
        })
    }
    $scope.postJSONSchema = function(){
        $http.post(CurrentServer + "/rest/" + $scope.service + "/_schema?return_schema=true", editor.getValue()).then(function(response){
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Posted Successfully',
                    type: 'success'
                });
            });
            $scope.loadServices(true);

        })
    }
    $scope.createTable = function(){
        var name = this.newTableName;
        this.newTableName = "";
        var requestObject = {
            name : name,
            field: [
                {name : "id",
                    type : "id"
                }
            ]
        };
        $http.post(CurrentServer + "/rest/" + this.service.api_name + "/_schema?return_schema=true" , {table:requestObject}).then(function(response){
            //$scope.loadServices();
            $scope.currentTable = name;
            //$scope.currentTables.unshift(name);
            $scope.dbServices[$scope.service_index].tables.unshift(requestObject);
            $scope.loadNewSchema(requestObject);

        })
    }

    $scope.dropTable = function(){
        var table_index = this.$index;
        var service_index = this.service.service_index;

        if ( !confirm( "Are you sure you want to delete " + this.table.name) ) {
            return;
        }
        $http.delete(CurrentServer + "/rest/" + this.service.api_name + "/_schema/" + this.table.name)
            .then(function(){
                $scope.dbServices[service_index].tables.splice(table_index , 1);
                $scope.table = {};
            })
    }
    $scope.setService = function(){
        $scope.service = this.service.api_name;
        $scope.service_index = this.service.service_index;
    }
    $scope.validateJSON = function() {
        try {
            var result = JSON.parse( editor.getValue() );
            if ( result ) {
                $(function(){
                    new PNotify({
                        title: 'Schema',
                        text: 'JSON is valid',
                        type: 'success'
                    });
                });
                editor.setValue(angular.toJson(result, true), -1);
            }
        }
        catch ( e ) {
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: e,
                    type: 'error'
                });
            });
        }
    };
};

<commit_msg>reload->refresh<commit_after>/**
 * This file is part of the DreamFactory Services Platform(tm) (DSP)
 *
 * DreamFactory Services Platform(tm) <http://github.com/dreamfactorysoftware/dsp-core>
 * Copyright 2012-2014 DreamFactory Software, Inc. <support@dreamfactory.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var SchemaCtrl = function( dfLoadingScreen, $scope, DSP_URL, DB, $http, getSchemaServices ) {

    dfLoadingScreen.stop();

    Scope = $scope;
    $scope.typeOptions = [
        {name : "I will manually enter a type" , value: ""},
        {name : "id",value: "id"},
        {name : "string", value: "string"},
        {name: "integer",value: "integer"},
        {name: "text", value: "text"},
        {name: "boolean", value: "boolean"},
        {name: "binary", value: "binary"},
        {name: "float", value: "float"},
        {name: "double", value: "double"},
        {name: "decimal", value: "decimal"},
        {name: "datetime", value: "datetime"},
        {name: "date", value: "date"},
        {name: "time", value: "time"},
        {name: "reference", value: "reference"},
        {name: "user_id", value: "user_id"},
        {name: "user_id_on_create",value: "user_id_on_create"},
        {name: "user_id_on_update",value: "user_id_on_update"},
        {name: "timestamp",value: "timestamp"},
        {name: "timestamp_on_create",value: "timestamp_on_create"},
        {name: "timestamp_on_update",value: "timestamp_on_update"}

    ];
    var editor;
    $scope.table = {};
    //$scope.service = {;
    $scope.advanced = false;
    //var service;
    editor = ace.edit("schema-editor");
    editor.getSession().setMode("ace/mode/json");
    $scope.dbServices = getSchemaServices.data.record;
    //console.log($scope.dbServices);
    $scope.loadServices = function(current){
        $scope.currentTables = [];
        if(current){
            $http.get(DSP_URL + "/rest/" + $scope.service + "/_schema").then(function(response){
                //console.log( $scope.dbServices[$scope.service]);
                $scope.dbServices[$scope.service_index].tables = [];
                response.data.resource.forEach(function(table){
                    $scope.dbServices[$scope.service_index].tables.push(table);
                    //$scope.currentTables.push(table.name);
                })
            });
        }else{
            $scope.dbServices.forEach(function(service, index){
                $http.get(DSP_URL + "/rest/" + service.api_name + "/_schema").then(function(response){

                    service.tables = [];

                    service.service_index = index;
                    response.data.resource.forEach(function(table){

                        service.tables.push(table);
                        $scope.currentTables.push(table.name);

                    })
                });
            })
        }

    }
    $scope.reloadService = function(){
        var service = this.service;
        $http.get(DSP_URL + "/rest/" + service.api_name + "/_schema?refresh=true").then(function(response){
            //console.log( $scope.dbServices[$scope.service]);
            $scope.dbServices[service.service_index].tables = [];
            response.data.resource.forEach(function(table){
                $scope.dbServices[service.service_index].tables.push(table);
                //$scope.currentTables.push(table.name);
            })
        });
    }
    $scope.loadServices();
    $scope.referenceFields  = [];
    $scope.loadNewSchema = function(table){
        $scope.import = false;
        $scope.table = table;
        $http.get(CurrentServer + "/rest/" + $scope.service + "/_schema/" + $scope.table.name)
            .then(function(response){
                $scope.table.schema = response;
            })
    }
    $scope.loadSchema = function(advanced){
        $scope.import = false;
        $scope.table = this.table;
        $scope.currentTables = $scope.dbServices[this.service.service_index].tables;
        $scope.currentTable = $scope.table.name;
        $scope.service = this.service.api_name;
        $scope.service_index = this.service.service_index;
        $http.get(CurrentServer + "/rest/" + this.service.api_name + "/_schema/" + this.table.name)
            .then(function(response){
                $scope.table.schema = response;
                //console.log(table.schema);
                if(advanced){
                    $scope.advanced = true;
                    editor.setValue(angular.toJson($scope.table.schema.data, true), -1);
                }else{
                    $scope.advanced = false;

                }

            })
    }
    $scope.loadReferenceFields = function(){
        console.log(this);
        if(!this.column.ref_table){
            return;
        }
        var refTable = this.column.ref_table;
        $http.get(CurrentServer + "/rest/" + $scope.service + "/_schema/" + refTable)
            .then(function(response){
                $scope.referenceFields = response.data.field;

            })
    }
    $scope.showImport = function(){
        editor.setValue("");
        $scope.advanced = true;
        $scope.import = true;
    }
    $scope.toggleJSON = function(){
        if($scope.advanced){
            $scope.table.schema.data = JSON.parse(editor.getValue());
            $scope.advanced = false;
        }else{
            $scope.advanced = true;
            editor.setValue(angular.toJson($scope.table.schema.data, true), -1);
        }
    }
    $scope.addColumn = function(){
        $scope.newColumn = {
            name : "New_Column",
            is_new : true,
            type : "string"
        };
        //$scope.currentField = "New_Column";
        $scope.table.schema.data.field.unshift($scope.newColumn)
    }
    $scope.deleteColumn = function(){
        //console.log(this);
        if ( !confirm( "Are you sure you want to delete " + this.column.name) ) {
            return;
        }
        $scope.table.schema.data.field.splice(this.$index, 1);
        $(function(){
            new PNotify({
                title: 'Schema',
                text: 'Column removed from working set, press Update Schema to save changes',
                type: 'warning'
            });
        });

    }
    $scope.updateJSONSchema = function(){
        $http.put(CurrentServer + "/rest/" + $scope.service + "/_schema?return_schema=true" , editor.getValue()).then(function(response){

            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Updated Successfully',
                    type: 'success'
                });
            });
        })
    }
    $scope.updateSchema = function(){
        $http.put(CurrentServer + "/rest/" + $scope.service + "/_schema?return_schema=true" , {table:$scope.table.schema.data}).then(function(response){
            $scope.table.schema.data = response.data.table[0];
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Updated Successfully',
                    type: 'success'
                });
            });
        })
    }
    $scope.postJSONSchema = function(){
        $http.post(CurrentServer + "/rest/" + $scope.service + "/_schema?return_schema=true", editor.getValue()).then(function(response){
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Posted Successfully',
                    type: 'success'
                });
            });
            $scope.loadServices(true);

        })
    }
    $scope.createTable = function(){
        var name = this.newTableName;
        this.newTableName = "";
        var requestObject = {
            name : name,
            field: [
                {name : "id",
                    type : "id"
                }
            ]
        };
        $http.post(CurrentServer + "/rest/" + this.service.api_name + "/_schema?return_schema=true" , {table:requestObject}).then(function(response){
            //$scope.loadServices();
            $scope.currentTable = name;
            //$scope.currentTables.unshift(name);
            $scope.dbServices[$scope.service_index].tables.unshift(requestObject);
            $scope.loadNewSchema(requestObject);

        })
    }

    $scope.dropTable = function(){
        var table_index = this.$index;
        var service_index = this.service.service_index;

        if ( !confirm( "Are you sure you want to delete " + this.table.name) ) {
            return;
        }
        $http.delete(CurrentServer + "/rest/" + this.service.api_name + "/_schema/" + this.table.name)
            .then(function(){
                $scope.dbServices[service_index].tables.splice(table_index , 1);
                $scope.table = {};
            })
    }
    $scope.setService = function(){
        $scope.service = this.service.api_name;
        $scope.service_index = this.service.service_index;
    }
    $scope.validateJSON = function() {
        try {
            var result = JSON.parse( editor.getValue() );
            if ( result ) {
                $(function(){
                    new PNotify({
                        title: 'Schema',
                        text: 'JSON is valid',
                        type: 'success'
                    });
                });
                editor.setValue(angular.toJson(result, true), -1);
            }
        }
        catch ( e ) {
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: e,
                    type: 'error'
                });
            });
        }
    };
};

<|endoftext|>


<commit_before>'use strict';

/* Controllers */
angular.module('cargoApp.controllers')
  .controller('homeController', function($rootScope,$scope,cargosFactory, $filter, $routeParams, $location, $route) {
  	$scope.ready= false;

    $scope.autoPersons = [];

  	$scope.activePersons = [];
    $scope.estado = "";
  	$rootScope.observers =[];
    $rootScope.yearObserver =[];
    $scope.filterLinea ="cargo";

   function removeAccents(value) {
        return value
            .replace(/á/g, 'a')
            .replace(/é/g, 'e')
            .replace(/í/g, 'i')
            .replace(/ó/g, 'o')
            .replace(/ú/g, 'u');
    }

    $scope.ignoreAccents = function(item) {
      console.log($scope.autocomplete);
        if (!$scope.autocomplete) {

          return true;
        }

        var text = removeAccents(item.name.toLowerCase())
        var search = removeAccents($scope.autocomplete.toLowerCase());
        return text.indexOf(search) > -1;
    };

  var onDataLoaded = function(){

     $scope.estado = "Motor de Visualizacion";
      for (var i = 0; i < $rootScope.observers.length; i++) {
        var observer = $rootScope.observers[i];
        observer();
      };
      $scope.estado = "Listo!";
      $scope.ready= true;

      //Load initial ids from the url
      if($routeParams.ids){
        angular.forEach($routeParams.ids.split('-'), function(id){
          $scope.add($scope.autoPersons[id], id);
        });
      }
      $scope.redrawPoderometro();

  };

  $scope.redrawPoderometro = function(){

    if ($scope.activePersons.length > 0 ){
      for (var i = 0; i < $rootScope.yearObserver.length; i++) {
        var observer = $rootScope.yearObserver[i];
        var poderometro = cargosFactory.getPoderometro($scope.poderometroYear, $scope.activePersons);
        observer(poderometro);
      };
    };
  }

  cargosFactory.load($scope,onDataLoaded);

  var lastRoute = $route.current;
  $scope.$on('$locationChangeSuccess', function(event) {
      // If same controller, then ignore the route change.
      if(lastRoute.controller == $route.current.controller) {
        $route.current = lastRoute;
      }
  });

  function updateTheUrl(){
      //Update the URL
      $location.path("/" + $scope.activePersons.map(function(p){ return p.autoPersona.index }).join('-'));
  }

    $scope.add = function(autoPersona, id){

      $scope.autocomplete = " ";
      autoPersona.agregada = true;

      var person = cargosFactory.getFullPerson(id);
      person.autoPersona = autoPersona;
      $scope.activePersons.push(person);

    	var idPersonas = cargoTimeline.options.filtro.idPersonas;
    	idPersonas.push(person.id);
			var timelineParams = {
			   filtro: { idPersonas: idPersonas },
			   mostrarPor: $scope.filterLinea,
			};
    	window.cargoTimeline.update(timelineParams);

      updateTheUrl();

    };

    $scope.orderLine =function(order){
      $scope.filterLinea = order;
      var idPersonas = cargoTimeline.options.filtro.idPersonas;
      var timelineParams = {
         filtro: { idPersonas: idPersonas },
         mostrarPor: $scope.filterLinea,
      };
      window.cargoTimeline.update(timelineParams);

    }

    $scope.remove = function(person){
    	var indexOf = $scope.activePersons.indexOf(person);
    	if (indexOf > -1){
    		 $scope.activePersons.splice(indexOf, 1);
    	}
      person.autoPersona.agregada = false;
    	indexOf = cargoTimeline.options.filtro.idPersonas.indexOf(person.id);
    	if (indexOf > -1){
    		 cargoTimeline.options.filtro.idPersonas.splice(indexOf, 1);
    	}
    	var idPersonas = cargoTimeline.options.filtro.idPersonas;
			var timelineParams = {
			   filtro: { idPersonas: idPersonas },
			   mostrarPor: $scope.filterLinea,
			};
    	window.cargoTimeline.update(timelineParams);

      updateTheUrl();

    };

    $scope.clearAll = function(){
      for (var i = 0; i < $scope.activePersons.length; i++) {
        $scope.activePersons[i].autoPersona.agregada = false;
      };
      $scope.activePersons = [];
      var idPersonas = [];
      var timelineParams = {
         filtro: { idPersonas: idPersonas },
         mostrarPor: $scope.filterLinea,
      };
      window.cargoTimeline.update(timelineParams);

      updateTheUrl();

    }

  });

<commit_msg>ignorar acentos code, comentado<commit_after>'use strict';

/* Controllers */
angular.module('cargoApp.controllers')
  .controller('homeController', function($rootScope,$scope,cargosFactory, $filter, $routeParams, $location, $route) {
  	$scope.ready= false;

    $scope.autoPersons = [];

  	$scope.activePersons = [];
    $scope.estado = "";
  	$rootScope.observers =[];
    $rootScope.yearObserver =[];
    $scope.filterLinea ="cargo";

   function removeAccents(value) {
        return value
            .replace(/á/g, 'a')
            .replace(/é/g, 'e')
            .replace(/í/g, 'i')
            .replace(/ó/g, 'o')
            .replace(/ú/g, 'u');
    }

    $scope.ignoreAccents = function(item) {

        if (!$scope.autocomplete) {

          return true;
        }

        var text = removeAccents(item.name.toLowerCase())
        var search = removeAccents($scope.autocomplete.toLowerCase());
        return text.indexOf(search) > -1;
    };

  var onDataLoaded = function(){

     $scope.estado = "Motor de Visualizacion";
      for (var i = 0; i < $rootScope.observers.length; i++) {
        var observer = $rootScope.observers[i];
        observer();
      };
      $scope.estado = "Listo!";
      $scope.ready= true;

      //Load initial ids from the url
      if($routeParams.ids){
        angular.forEach($routeParams.ids.split('-'), function(id){
          $scope.add($scope.autoPersons[id], id);
        });
      }
      $scope.redrawPoderometro();

  };

  $scope.redrawPoderometro = function(){

    if ($scope.activePersons.length > 0 ){
      for (var i = 0; i < $rootScope.yearObserver.length; i++) {
        var observer = $rootScope.yearObserver[i];
        var poderometro = cargosFactory.getPoderometro($scope.poderometroYear, $scope.activePersons);
        observer(poderometro);
      };
    };
  }

  cargosFactory.load($scope,onDataLoaded);

  var lastRoute = $route.current;
  $scope.$on('$locationChangeSuccess', function(event) {
      // If same controller, then ignore the route change.
      if(lastRoute.controller == $route.current.controller) {
        $route.current = lastRoute;
      }
  });

  function updateTheUrl(){
      //Update the URL
      $location.path("/" + $scope.activePersons.map(function(p){ return p.autoPersona.index }).join('-'));
  }

    $scope.add = function(autoPersona, id){

      $scope.autocomplete = " ";
      autoPersona.agregada = true;

      var person = cargosFactory.getFullPerson(id);
      person.autoPersona = autoPersona;
      $scope.activePersons.push(person);

    	var idPersonas = cargoTimeline.options.filtro.idPersonas;
    	idPersonas.push(person.id);
			var timelineParams = {
			   filtro: { idPersonas: idPersonas },
			   mostrarPor: $scope.filterLinea,
			};
    	window.cargoTimeline.update(timelineParams);

      updateTheUrl();

    };

    $scope.orderLine =function(order){
      $scope.filterLinea = order;
      var idPersonas = cargoTimeline.options.filtro.idPersonas;
      var timelineParams = {
         filtro: { idPersonas: idPersonas },
         mostrarPor: $scope.filterLinea,
      };
      window.cargoTimeline.update(timelineParams);

    }

    $scope.remove = function(person){
    	var indexOf = $scope.activePersons.indexOf(person);
    	if (indexOf > -1){
    		 $scope.activePersons.splice(indexOf, 1);
    	}
      person.autoPersona.agregada = false;
    	indexOf = cargoTimeline.options.filtro.idPersonas.indexOf(person.id);
    	if (indexOf > -1){
    		 cargoTimeline.options.filtro.idPersonas.splice(indexOf, 1);
    	}
    	var idPersonas = cargoTimeline.options.filtro.idPersonas;
			var timelineParams = {
			   filtro: { idPersonas: idPersonas },
			   mostrarPor: $scope.filterLinea,
			};
    	window.cargoTimeline.update(timelineParams);

      updateTheUrl();

    };

    $scope.clearAll = function(){
      for (var i = 0; i < $scope.activePersons.length; i++) {
        $scope.activePersons[i].autoPersona.agregada = false;
      };
      $scope.activePersons = [];
      var idPersonas = [];
      var timelineParams = {
         filtro: { idPersonas: idPersonas },
         mostrarPor: $scope.filterLinea,
      };
      window.cargoTimeline.update(timelineParams);

      updateTheUrl();

    }

  });

<|endoftext|>


<commit_before>'use strict';

viewModel.TurbineHealth = new Object();
var pg = viewModel.TurbineHealth;

vm.currentMenu('Time Series Plots');
vm.currentTitle('Time Series Plots');
vm.breadcrumb([{ title: 'Analysis Tool Box', href: '#' }, { title: 'Time Series Plots', href: viewModel.appName + 'page/timeseries' }]);

pg.availabledatestartscada = ko.observable();
pg.availabledateendscada = ko.observable();
var timeSeriesData = [];
var seriesOptions = [],
    seriesCounter = 0;

var yAxis = [];

pg.LoadData = function(){
	// fa.getProjectInfo();
    fa.LoadData();
    app.loading(true);

    var param = {
        period: fa.period,
        Turbine: fa.turbine,
        DateStart: fa.dateStart,
        DateEnd: fa.dateEnd,
        Project: fa.project
    };

    var requestData = toolkit.ajaxPost(viewModel.appName + "timeseries/getdata", param, function (res) {
        if (!app.isFine(res)) {
            return;
        }
        // pg.chartWindSpeed(res.data.Data.windspeed);
        // pg.chartProduction(res.data.Data.production);
        timeSeriesData = res.data.Data;
        pg.createChart();
    });

    $.when(requestData).done(function(){
        setTimeout(function(){
            app.loading(false);
        },500);
    });
}

toolkit.ajaxPost(viewModel.appName + "analyticlossanalysis/getavaildate", {}, function (res) {
    if (!app.isFine(res)) {
        return;
    }
    var minDatetemp = new Date(res.data.ScadaData[0]);
    var maxDatetemp = new Date(res.data.ScadaData[1]);

    pg.availabledatestartscada(kendo.toString(moment.utc(minDatetemp).format('DD-MMMM-YYYY')));
    pg.availabledateendscada(kendo.toString(moment.utc(maxDatetemp).format('DD-MMMM-YYYY')));

    $('#availabledatestart').html(pg.availabledatestartscada());
    $('#availabledateend').html(pg.availabledateendscada());

})

pg.setSeries = function(name, axis, color, data){
  return {
    name: name,
    type: "line",
    field: "value",
    categoryField: "timestamp",
    axis: axis,
    color: color,
    data: data,
    aggregate: "sum",
    markers : {
        visible : false,
    },
  }
}

pg.setValueAxis = function(name, titleText, crossingVal){
  return {
    name: name,
    title: {
        text: titleText,
        visible: true,
        font: '12px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
    },
    labels: {
        // format: "{0:p2}"
        font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
        format: "{0}"
    },
    majorGridLines: {
        visible: true,
        color: "#eee",
        width: 0.8,
    },
    line: {
        visible: false
    },
    axisCrossingValue: crossingVal
  }
}

pg.createChart = function(){
  var seriesList = [];
  seriesList.push(pg.setSeries("Wind Speed", "windspeedAxis", "#337ab7", timeSeriesData.windspeed));
  seriesList.push(pg.setSeries("Production", "productionAxis", "#ea5b19", timeSeriesData.production));

  var valueAxisList = [];
  valueAxisList.push(pg.setValueAxis("windspeedAxis", "m/s", 0));
  valueAxisList.push(pg.setValueAxis("productionAxis", "MWh", 0));

  var naviSeriesList = [];
  var series1 = pg.setSeries("Wind Speed", "windspeedAxis", "#337ab7", timeSeriesData.windspeed);
  series1.shared = true;
  var series2 = pg.setSeries("Production", "productionAxis", "#ea5b19", timeSeriesData.production);
  series2.shared = true;
  naviSeriesList.push(series1);
  naviSeriesList.push(series2);

  $("#chartTimeSeries").kendoStockChart({
    title: {
        text: "Wind Speed & Production",
        font: '14px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
      },
      legend: {
        position: "top",
        visible: true
      },
      theme: "flat",
      seriesDefaults: {
          area: {
              line: {
                  style: "smooth",
              }
          },
          width: 1.3,
      },
      series: seriesList,
      navigator: {
        categoryAxis: {
          roundToBaseUnit: true
        },
        series: naviSeriesList
      },
      valueAxis: valueAxisList,
      categoryAxis: {
            labels: {
                font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
            },
            majorGridLines: {
                visible: false
            },
            majorTickType: "none",
            axisCrossingValues: [0, 1000],
            autoBaseUnitSteps: {
                // Would produce 31 groups
                // => Skip to weeks
                minutes: [10],
            }
      },
      tooltip: {
            visible: true,
            template: "#= kendo.toString(value,'n2') # MWh",
            background: "rgb(255,255,255, 0.9)",
            color: "#58666e",
            font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
            border: {
                color: "#eee",
                width: "2px",
            },
            shared: true,
            sharedTemplate: kendo.template($("#template").html())
        }
    });
}

pg.chartWindSpeed = function(dataSource){
	$("#chartWindSpeed").kendoStockChart({
	  title: {
        text: "Wind Speed",
        font: '14px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
      },
      legend: {
        position: "top",
        visible: false
      },
      dataSource: {
        data: dataSource
      },
      theme: "flat",
      seriesDefaults: {
	        area: {
	            line: {
	                style: "smooth"
	            }
	        }
	    },
      dateField: "timestamp",
      series: [{
        type: "area",
        field: "value",
        aggregate: "avg",
        color: "#337ab7",
      }],
      navigator: {
        categoryAxis: {
          roundToBaseUnit: true
        },
        series: [{
          type: "area",
          field: "value",
          aggregate: "avg",
          color: "#337ab7",
        }]
      },
      valueAxis: {
        title: {
            text: "m/s",
            visible: true,
            font: '12px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
        },
        labels: {
            // format: "{0:p2}"
            format: "{0}"
        },
        majorGridLines: {
            visible: true,
            color: "#eee",
            width: 0.8,
        },
        line: {
            visible: false
        },
        axisCrossingValue: 0
      },
	  categoryAxis: {
            majorGridLines: {
                visible: false
            },
            majorTickType: "none"
      },
      tooltip: {
            visible: true,
            template: "#= kendo.toString(value,'n2') # m/s",
            background: "rgb(255,255,255, 0.9)",
            color: "#58666e",
            font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
            border: {
                color: "#eee",
                width: "2px",
            }
        }
    });
}
pg.chartProduction = function(dataSource){
	$("#chartProduction").kendoStockChart({
	  title: {
        text: "Production",
        font: '14px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
      },
      legend: {
        position: "top",
        visible: false
      },
      dataSource: {
        data: dataSource
      },
      theme: "flat",
      seriesDefaults: {
	        area: {
	            line: {
	                style: "smooth"
	            }
	        }
	    },
      dateField: "timestamp",
      series: [{
        type: "area",
        field: "value",
        aggregate: "sum",
        color: "#ea5b19",
      }],
      navigator: {
        categoryAxis: {
          roundToBaseUnit: true
        },
        series: [{
          type: "area",
          field: "value",
          aggregate: "sum",
          color: "#ea5b19",
        }]
      },
      valueAxis: {
        title: {
            text: "MWh",
            visible: true,
            font: '12px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
        },
        labels: {
            // format: "{0:p2}"
            format: "{0}"
        },
        majorGridLines: {
            visible: true,
            color: "#eee",
            width: 0.8,
        },
        line: {
            visible: false
        },
        axisCrossingValue: 0
      },
	  categoryAxis: {
            majorGridLines: {
                visible: false
            },
            majorTickType: "none"
      },
      tooltip: {
            visible: true,
            template: "#= kendo.toString(value,'n2') # MWh",
            background: "rgb(255,255,255, 0.9)",
            color: "#58666e",
            font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
            border: {
                color: "#eee",
                width: "2px",
            }
        }
    });
}

pg.createStockChart = function(){
    $("#chartTimeSeries").html("");

    Highcharts.stockChart('chartTimeSeries', {
        legend: {
                layout: 'horizontal',
                // align: 'top',
                verticalAlign: 'top',
                borderWidth: 0,
                enabled: true,
                margin : 5
        },
        rangeSelector: {
            selected: 1
        },
         navigator: {
            series: {
                color: '#999',
                lineWidth: 2
            }
        },
        exporting: {
          enabled: false
        },
        yAxis: yAxis,
        plotOptions: {
        series: {
                lineWidth: 1,
                states: {
                    hover: {
                        enabled: true,
                        lineWidth: 1
                    }
                }
            }
        },
        tooltip: {
            pointFormat: '{series.name}: {point.y}
',
            valueDecimals: 2,
            split: true
        },

        series: seriesOptions,

    });

    app.loading(false);
}

pg.getTimestamp = function(param){
  var dateString = moment(param).format("DD-MM-YYYY HH:mm:ss"),
      dateTimeParts = dateString.split(' '),
      timeParts = dateTimeParts[1].split(':'),
      dateParts = dateTimeParts[0].split('-'),
      date;

      date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);

      return date.getTime();
}
pg.getDataStockChart = function(){
    var param = {
        period: fa.period,
        Turbine: fa.turbine,
        DateStart: fa.dateStart,
        DateEnd: fa.dateEnd,
        Project: fa.project
    };
    toolkit.ajaxPost(viewModel.appName + "timeseries/getdata", param, function (res) {
        if (!app.isFine(res)) {
            return;
        }

        var data = res.data.Data;
        var series = [];

        var colors = ["#0066dd","#dc3912","#eee"];

        $.each(data, function(id, ress){
            series.push(id);
        });

        var i = 0;
        $.each(data, function(idx, val){
            var newData = [];
            $.each(data[idx], function(y, result){
                newData.push([pg.getTimestamp(result.timestamp), result.value]);
            });

             yAxis [i] = {
                gridLineWidth: 1,
                labels: {
                    format: '{value}',
                },
                title: {
                    text: (idx == "windspeed" ? "(m/s)" : "(MWh)"),
                },
                opposite: (idx == "production" ? true : false)

            }

            seriesOptions[i] = {
                  name : idx.substr(0,1).toUpperCase()+idx.substr(1),
                  data : newData,
                  color: colors[i],
                  type: 'line',
                  yAxis: i,
                  tooltip: {
                      valueSuffix: (idx == "windspeed" ? " (m/s)" : " (MWh)"),
                  }
            }

          seriesCounter += 1;

          if (seriesCounter === series.length) {
              pg.createStockChart();
          }

          i++;

        });
    });
}

$(document).ready(function () {
    $('#btnRefresh').on('click', function () {
        pg.getDataStockChart();
    });

    setTimeout(function () {
        // pg.LoadData();
        pg.getDataStockChart();
    }, 1000);
});
<commit_msg>change font family<commit_after>'use strict';

viewModel.TurbineHealth = new Object();
var pg = viewModel.TurbineHealth;

vm.currentMenu('Time Series Plots');
vm.currentTitle('Time Series Plots');
vm.breadcrumb([{ title: 'Analysis Tool Box', href: '#' }, { title: 'Time Series Plots', href: viewModel.appName + 'page/timeseries' }]);

pg.availabledatestartscada = ko.observable();
pg.availabledateendscada = ko.observable();
var timeSeriesData = [];
var seriesOptions = [],
    seriesCounter = 0;

var yAxis = [];

pg.LoadData = function(){
	// fa.getProjectInfo();
    fa.LoadData();
    app.loading(true);

    var param = {
        period: fa.period,
        Turbine: fa.turbine,
        DateStart: fa.dateStart,
        DateEnd: fa.dateEnd,
        Project: fa.project
    };

    var requestData = toolkit.ajaxPost(viewModel.appName + "timeseries/getdata", param, function (res) {
        if (!app.isFine(res)) {
            return;
        }
        // pg.chartWindSpeed(res.data.Data.windspeed);
        // pg.chartProduction(res.data.Data.production);
        timeSeriesData = res.data.Data;
        pg.createChart();
    });

    $.when(requestData).done(function(){
        setTimeout(function(){
            app.loading(false);
        },500);
    });
}

toolkit.ajaxPost(viewModel.appName + "analyticlossanalysis/getavaildate", {}, function (res) {
    if (!app.isFine(res)) {
        return;
    }
    var minDatetemp = new Date(res.data.ScadaData[0]);
    var maxDatetemp = new Date(res.data.ScadaData[1]);

    pg.availabledatestartscada(kendo.toString(moment.utc(minDatetemp).format('DD-MMMM-YYYY')));
    pg.availabledateendscada(kendo.toString(moment.utc(maxDatetemp).format('DD-MMMM-YYYY')));

    $('#availabledatestart').html(pg.availabledatestartscada());
    $('#availabledateend').html(pg.availabledateendscada());

})

pg.setSeries = function(name, axis, color, data){
  return {
    name: name,
    type: "line",
    field: "value",
    categoryField: "timestamp",
    axis: axis,
    color: color,
    data: data,
    aggregate: "sum",
    markers : {
        visible : false,
    },
  }
}

pg.setValueAxis = function(name, titleText, crossingVal){
  return {
    name: name,
    title: {
        text: titleText,
        visible: true,
        font: '12px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
    },
    labels: {
        // format: "{0:p2}"
        font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
        format: "{0}"
    },
    majorGridLines: {
        visible: true,
        color: "#eee",
        width: 0.8,
    },
    line: {
        visible: false
    },
    axisCrossingValue: crossingVal
  }
}

pg.createChart = function(){
  var seriesList = [];
  seriesList.push(pg.setSeries("Wind Speed", "windspeedAxis", "#337ab7", timeSeriesData.windspeed));
  seriesList.push(pg.setSeries("Production", "productionAxis", "#ea5b19", timeSeriesData.production));

  var valueAxisList = [];
  valueAxisList.push(pg.setValueAxis("windspeedAxis", "m/s", 0));
  valueAxisList.push(pg.setValueAxis("productionAxis", "MWh", 0));

  var naviSeriesList = [];
  var series1 = pg.setSeries("Wind Speed", "windspeedAxis", "#337ab7", timeSeriesData.windspeed);
  series1.shared = true;
  var series2 = pg.setSeries("Production", "productionAxis", "#ea5b19", timeSeriesData.production);
  series2.shared = true;
  naviSeriesList.push(series1);
  naviSeriesList.push(series2);

  $("#chartTimeSeries").kendoStockChart({
    title: {
        text: "Wind Speed & Production",
        font: '14px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
      },
      legend: {
        position: "top",
        visible: true
      },
      theme: "flat",
      seriesDefaults: {
          area: {
              line: {
                  style: "smooth",
              }
          },
          width: 1.3,
      },
      series: seriesList,
      navigator: {
        categoryAxis: {
          roundToBaseUnit: true
        },
        series: naviSeriesList
      },
      valueAxis: valueAxisList,
      categoryAxis: {
            labels: {
                font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
            },
            majorGridLines: {
                visible: false
            },
            majorTickType: "none",
            axisCrossingValues: [0, 1000],
            autoBaseUnitSteps: {
                // Would produce 31 groups
                // => Skip to weeks
                minutes: [10],
            }
      },
      tooltip: {
            visible: true,
            template: "#= kendo.toString(value,'n2') # MWh",
            background: "rgb(255,255,255, 0.9)",
            color: "#58666e",
            font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
            border: {
                color: "#eee",
                width: "2px",
            },
            shared: true,
            sharedTemplate: kendo.template($("#template").html())
        }
    });
}

pg.chartWindSpeed = function(dataSource){
	$("#chartWindSpeed").kendoStockChart({
	  title: {
        text: "Wind Speed",
        font: '14px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
      },
      legend: {
        position: "top",
        visible: false
      },
      dataSource: {
        data: dataSource
      },
      theme: "flat",
      seriesDefaults: {
	        area: {
	            line: {
	                style: "smooth"
	            }
	        }
	    },
      dateField: "timestamp",
      series: [{
        type: "area",
        field: "value",
        aggregate: "avg",
        color: "#337ab7",
      }],
      navigator: {
        categoryAxis: {
          roundToBaseUnit: true
        },
        series: [{
          type: "area",
          field: "value",
          aggregate: "avg",
          color: "#337ab7",
        }]
      },
      valueAxis: {
        title: {
            text: "m/s",
            visible: true,
            font: '12px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
        },
        labels: {
            // format: "{0:p2}"
            format: "{0}"
        },
        majorGridLines: {
            visible: true,
            color: "#eee",
            width: 0.8,
        },
        line: {
            visible: false
        },
        axisCrossingValue: 0
      },
	  categoryAxis: {
            majorGridLines: {
                visible: false
            },
            majorTickType: "none"
      },
      tooltip: {
            visible: true,
            template: "#= kendo.toString(value,'n2') # m/s",
            background: "rgb(255,255,255, 0.9)",
            color: "#58666e",
            font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
            border: {
                color: "#eee",
                width: "2px",
            }
        }
    });
}
pg.chartProduction = function(dataSource){
	$("#chartProduction").kendoStockChart({
	  title: {
        text: "Production",
        font: '14px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
      },
      legend: {
        position: "top",
        visible: false
      },
      dataSource: {
        data: dataSource
      },
      theme: "flat",
      seriesDefaults: {
	        area: {
	            line: {
	                style: "smooth"
	            }
	        }
	    },
      dateField: "timestamp",
      series: [{
        type: "area",
        field: "value",
        aggregate: "sum",
        color: "#ea5b19",
      }],
      navigator: {
        categoryAxis: {
          roundToBaseUnit: true
        },
        series: [{
          type: "area",
          field: "value",
          aggregate: "sum",
          color: "#ea5b19",
        }]
      },
      valueAxis: {
        title: {
            text: "MWh",
            visible: true,
            font: '12px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
        },
        labels: {
            // format: "{0:p2}"
            format: "{0}"
        },
        majorGridLines: {
            visible: true,
            color: "#eee",
            width: 0.8,
        },
        line: {
            visible: false
        },
        axisCrossingValue: 0
      },
	  categoryAxis: {
            majorGridLines: {
                visible: false
            },
            majorTickType: "none"
      },
      tooltip: {
            visible: true,
            template: "#= kendo.toString(value,'n2') # MWh",
            background: "rgb(255,255,255, 0.9)",
            color: "#58666e",
            font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
            border: {
                color: "#eee",
                width: "2px",
            }
        }
    });
}

pg.createStockChart = function(){
    $("#chartTimeSeries").html("");

    Highcharts.setOptions({
        chart: {
            style: {
                fontFamily: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
            }
        }
    });

    Highcharts.stockChart('chartTimeSeries', {
        legend: {
                layout: 'horizontal',
                // align: 'top',
                verticalAlign: 'top',
                borderWidth: 0,
                enabled: true,
                margin : 5
        },
        rangeSelector: {
            selected: 1
        },
         navigator: {
            series: {
                color: '#999',
                lineWidth: 2
            }
        },
        exporting: {
          enabled: false
        },
        yAxis: yAxis,
        plotOptions: {
        series: {
                lineWidth: 1,
                states: {
                    hover: {
                        enabled: true,
                        lineWidth: 1
                    }
                }
            }
        },
        tooltip: {
            pointFormat: '{series.name}: {point.y}
',
            valueDecimals: 2,
            split: true
        },

        series: seriesOptions,

    });

    app.loading(false);
}

pg.getTimestamp = function(param){
  var dateString = moment(param).format("DD-MM-YYYY HH:mm:ss"),
      dateTimeParts = dateString.split(' '),
      timeParts = dateTimeParts[1].split(':'),
      dateParts = dateTimeParts[0].split('-'),
      date;

      date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);

      return date.getTime();
}
pg.getDataStockChart = function(){
    var param = {
        period: fa.period,
        Turbine: fa.turbine,
        DateStart: fa.dateStart,
        DateEnd: fa.dateEnd,
        Project: fa.project
    };
    toolkit.ajaxPost(viewModel.appName + "timeseries/getdata", param, function (res) {
        if (!app.isFine(res)) {
            return;
        }

        var data = res.data.Data;
        var series = [];

        var colors = ["#0066dd","#dc3912","#eee"];

        $.each(data, function(id, ress){
            series.push(id);
        });

        var i = 0;
        $.each(data, function(idx, val){
            var newData = [];
            $.each(data[idx], function(y, result){
                newData.push([pg.getTimestamp(result.timestamp), result.value]);
            });

             yAxis [i] = {
                gridLineWidth: 1,
                labels: {
                    format: '{value}',
                },
                title: {
                    text: (idx == "windspeed" ? "(m/s)" : "(MWh)"),
                },
                opposite: (idx == "production" ? true : false)

            }

            seriesOptions[i] = {
                  name : idx.substr(0,1).toUpperCase()+idx.substr(1),
                  data : newData,
                  color: colors[i],
                  type: 'line',
                  yAxis: i,
                  tooltip: {
                      valueSuffix: (idx == "windspeed" ? " (m/s)" : " (MWh)"),
                  }
            }

          seriesCounter += 1;

          if (seriesCounter === series.length) {
              pg.createStockChart();
          }

          i++;

        });
    });
}

$(document).ready(function () {
    $('#btnRefresh').on('click', function () {
        pg.getDataStockChart();
    });

    setTimeout(function () {
        // pg.LoadData();
        pg.getDataStockChart();
    }, 1000);
});
<|endoftext|>


<commit_before>Module.register("MMM-Scrobbler",{
    // Default module config.
    defaults: {
        username: '',
		apikey: '',
		updateInterval: 15 * 1000,
		delayCount: 5,
		delayInterval: 120*1000,
		animationSpeed: 1000,
	    showAlbumArt: true,
	    showMetaData: true,
	    alignment: "bottom", //possible values: top, bottom, left, right
    },
	getStyles: function() {
		return ['MMM-Scrobbler.css']
		},
	start: function() {
		Log.info("Starting module: " + this.name);
		//set module data object
		this.songData = {playing:"false"};
		//prepare loading
		this.loaded = false;
		this.delay = this.config.updateInterval;
		this.failedCounter = 0;
		this.scheduleUpdate(0);
	},
    // Override dom generator.
    getDom: function() {
        var wrapper = document.createElement("div");
		if (!this.loaded) {
			wrapper.innerHTML = "Scrobble data...";
			wrapper.className = "dimmed light small";
			return wrapper;
		}
		if (this.config.username == '' || this.config.apikey == '') {
			wrapper.innerHTML = "Please check your config file. Username or ApiKey is missing!";
			wrapper.className = "bright";
			return wrapper;
		}
		if(this.songData.playing === "true"){
			this.failedCounter = 0;
			this.delay = this.config.updateInterval;
			this.show(this.config.animationSpeed);
			var html = "
";
			var albumart_html = '';
			var meta_html = '';
			if(this.config.showAlbumArt){
				albumart_html += "

";
			}
			if(this.config.showMetaData){
				meta_html += "

"+this.songData.title+"

"+this.songData.artist +"

"+this.songData.album+"

";
			}
			if(this.config.alignment === 'left' || this.config.alignment === 'top'){
				html += meta_html;
				html += albumart_html;
			}
			else{
				html += albumart_html;
				html += meta_html;
			}
			html += "
";
			wrapper.innerHTML = html;
		}
		else{
			this.hide(this.config.animationSpeed);
			this.failedCounter = this.failedCounter + 1;
			if(this.failedCounter > this.config.delayCount){
				this.delay = this.config.delayInterval;
			}
			this.songData = {playing:"false"};
			wrapper.innerHTML = "Not playing...";
		}
		this.scheduleUpdate(this.delay);
		return wrapper;
    },
	queryLastFm: function(){
		var url = "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user="+this.config.username+"&api_key="+this.config.apikey+"&limit=1&format=json";
		var self = this;
		var i = new XMLHttpRequest;
		i.open("GET",url,true),i.onload=function(){
			var r=JSON.parse(i.responseText);
			if(!(i.status>=200&&i.status<400)){
				Log.error(r.message);
				self.hide(1000);
			}
			var a = r.recenttracks.track[0] ? r.recenttracks.track[0] : r.recenttracks.track;
			var nowplaying = false;
			if(a["@attr"]){ nowplaying = a["@attr"].nowplaying;}
			self.songData = {title:a.name,artist:a.artist["#text"],album:a.album["#text"],image:a.image[2]["#text"], playing: nowplaying};
			self.loaded = true;
			self.updateDom(self.config.animationSpeed);
			},
			i.onerror=function(){Log.error("Something went wrong")};
		i.send();
	},
	scheduleUpdate: function(delay) {
		var nextLoad = this.delay;
		if (typeof delay !== "undefined" && delay >= 0) {
			nextLoad = delay;
		}
		//set update timeout
		var self = this;
		setTimeout(function() {
			self.queryLastFm();
		}, nextLoad);
	}
});
<commit_msg>Use https<commit_after>Module.register("MMM-Scrobbler",{
    // Default module config.
    defaults: {
        username: '',
		apikey: '',
		updateInterval: 15 * 1000,
		delayCount: 5,
		delayInterval: 120*1000,
		animationSpeed: 1000,
	    showAlbumArt: true,
	    showMetaData: true,
	    alignment: "bottom", //possible values: top, bottom, left, right
    },
	getStyles: function() {
		return ['MMM-Scrobbler.css']
		},
	start: function() {
		Log.info("Starting module: " + this.name);
		//set module data object
		this.songData = {playing:"false"};
		//prepare loading
		this.loaded = false;
		this.delay = this.config.updateInterval;
		this.failedCounter = 0;
		this.scheduleUpdate(0);
	},
    // Override dom generator.
    getDom: function() {
        var wrapper = document.createElement("div");
		if (!this.loaded) {
			wrapper.innerHTML = "Scrobble data...";
			wrapper.className = "dimmed light small";
			return wrapper;
		}
		if (this.config.username == '' || this.config.apikey == '') {
			wrapper.innerHTML = "Please check your config file. Username or ApiKey is missing!";
			wrapper.className = "bright";
			return wrapper;
		}
		if(this.songData.playing === "true"){
			this.failedCounter = 0;
			this.delay = this.config.updateInterval;
			this.show(this.config.animationSpeed);
			var html = "
";
			var albumart_html = '';
			var meta_html = '';
			if(this.config.showAlbumArt){
				albumart_html += "

";
			}
			if(this.config.showMetaData){
				meta_html += "

"+this.songData.title+"

"+this.songData.artist +"

"+this.songData.album+"

";
			}
			if(this.config.alignment === 'left' || this.config.alignment === 'top'){
				html += meta_html;
				html += albumart_html;
			}
			else{
				html += albumart_html;
				html += meta_html;
			}
			html += "
";
			wrapper.innerHTML = html;
		}
		else{
			this.hide(this.config.animationSpeed);
			this.failedCounter = this.failedCounter + 1;
			if(this.failedCounter > this.config.delayCount){
				this.delay = this.config.delayInterval;
			}
			this.songData = {playing:"false"};
			wrapper.innerHTML = "Not playing...";
		}
		this.scheduleUpdate(this.delay);
		return wrapper;
    },
	queryLastFm: function(){
		var url = "https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user="+this.config.username+"&api_key="+this.config.apikey+"&limit=1&format=json";
		var self = this;
		var i = new XMLHttpRequest;
		i.open("GET",url,true),i.onload=function(){
			var r=JSON.parse(i.responseText);
			if(!(i.status>=200&&i.status<400)){
				Log.error(r.message);
				self.hide(1000);
			}
			var a = r.recenttracks.track[0] ? r.recenttracks.track[0] : r.recenttracks.track;
			var nowplaying = false;
			if(a["@attr"]){ nowplaying = a["@attr"].nowplaying;}
			self.songData = {title:a.name,artist:a.artist["#text"],album:a.album["#text"],image:a.image[2]["#text"], playing: nowplaying};
			self.loaded = true;
			self.updateDom(self.config.animationSpeed);
			},
			i.onerror=function(){Log.error("Something went wrong")};
		i.send();
	},
	scheduleUpdate: function(delay) {
		var nextLoad = this.delay;
		if (typeof delay !== "undefined" && delay >= 0) {
			nextLoad = delay;
		}
		//set update timeout
		var self = this;
		setTimeout(function() {
			self.queryLastFm();
		}, nextLoad);
	}
});
<|endoftext|>


<commit_before>'use strict';

/*!
 * V4Fire Client Core
 * https://github.com/V4Fire/Client
 *
 * Released under the MIT license
 * https://github.com/V4Fire/Client/blob/master/LICENSE
 */

const
	config = require('config');

/**
 * Parameters for webpack.externals
 */
module.exports = config.webpack.externals;
<commit_msg>Improved externals API<commit_after>'use strict';

/*!
 * V4Fire Client Core
 * https://github.com/V4Fire/Client
 *
 * Released under the MIT license
 * https://github.com/V4Fire/Client/blob/master/LICENSE
 */

const
	$C = require('collection.js'),
	config = require('config');

const
	externals = [],
	rgxp = /^\/(.*?)\/$/;

const externalMap = $C(config.webpack.externals).filter((el, key) => {
	if (!rgxp.test(key)) {
		return true;
	}

	const
		r = new RegExp(RegExp.$1);

	externals.push((ctx, req, cb) => {
		if (r.test(req)) {
			return cb(null, `root ${Object.isObject(el) ? el.root : el}`);
		}

		cb();
	});

}).map();

/**
 * Parameters for webpack.externals
 */
module.exports = [externalMap].concat(externals);
<|endoftext|>


<commit_before>/* global angular, console, $ */
(function() {
    'use strict';

    angular.module('serviceHealth', []).
    factory("$serviceHealth", ["$rootScope", "$q", "$http", "resourcesService", function($rootScope, $q, $http, resourcesService){

        var servicesService = resourcesService;

        var STATUS_STYLES = {
            "bad": "glyphicon-exclamation-sign bad",
            "good": "glyphicon-ok-sign good",
            "unknown": "glyphicon-question-sign unknown",
            // "disabled": "glyphicon-minus-sign disabled",
            "disabled": ""
        };

        // auto update all service health statuses
        var updateInterval = setInterval(update, 3000);

        // simple array search util
        function findInArray(key, arr, val){
            for(var i = 0; i < arr.length; i++){
                if(arr[i][key] === val){
                    return arr[i];
                }
            }
        }

        function getRunningServiceById(serviceId){
            // subservices isn't defined if we're on a single
            // service page, so just skip this service alltogether
            if(!running) return;

            return findInArray("ServiceID", running, serviceId);
        }

        // updates health check data for all services
        // `appId` is the id of the specific service being clicked
        function update(appId) {

            // TODO - these methods should return promises, but they
            // don't so use our own promises
            var servicesDeferred = $q.defer();
            var runningServicesDeferred = $q.defer();
            var healthCheckDeferred = $http.get("/servicehealth");

            servicesService.get_services(true, function(top, mapped){
                servicesDeferred.resolve(mapped);
            });

            servicesService.get_running_services(function(runningServices){
                runningServicesDeferred.resolve(runningServices);
            });

            $q.all({
                services: servicesDeferred.promise,
                health: healthCheckDeferred,
                running: runningServicesDeferred.promise
            }).then(function(results){
                evaluateServiceStatus(results.running, results.services, results.health.data, appId);
            });
        }

        function evaluateServiceStatus(running, services, healthCheckData, appId) {

            var healths = healthCheckData.Statuses,
                timestamp = healthCheckData.Timestamp;

            var service, data, runningService, startTime,
                passingAny, failingAny, unknownAny, downAny, status,
                missedIntervals, tooltipMessage;

            for (var ServiceId in healths) {

                service = services[ServiceId];
                runningService = findInArray("ServiceID", running, ServiceId);

                if(!service){
                    return;
                }

                // get the time this service was started
                if(runningService){
                    startTime = new Date(runningService.StartedAt).getTime();

                // otherwise service hasn't been started
                } else {
                    startTime = 0;
                }

                data = healths[ServiceId];

                service.healthTooltipTitle = "";

                passingAny = false;
                failingAny = false;
                unknownAny = false;
                downAny = false;
                status = null;
                missedIntervals = 0;
                tooltipMessage = "";

                for (var name in data) {

                    // calculates the number of missed healthchecks since last start time
                    missedIntervals = (timestamp - Math.max(data[name].Timestamp, startTime)) / data[name].Interval;

                    // if service hasn't started yet
                    if(!startTime){
                        data[name].Status = "down";

                    // if service has missed 2 updates, mark unknown
                    } else if (missedIntervals > 2 && missedIntervals < 60) {
                        data[name].Status = "unknown";

                    // if service has missed 60 updates, mark failed
                    } else if (missedIntervals > 60) {
                        data[name].Status = "failed";
                    }

                    switch(data[name].Status){
                        case "passed":
                            passingAny = true;
                            break;
                        case "failed":
                            failingAny = true;
                            break;
                        case "unknown":
                            unknownAny = true;
                            break;
                        case "down":
                            downAny = true;
                            break;
                        default:
                            break;
                    }

                    // TODO - do something with `name` so the user has a
                    // more detailed explanation of which checks are failing
                }

                // the following conditions are relevant when the service
                // *should* be started
                if(service.DesiredState === 1){

                    // service should be up, but is failing. bad!
                    if(failingAny){
                        status = "bad";
                        tooltipMessage = "Failing Health Checks";

                    // service should be up, but container has not
                    // yet loaded
                    } else if(downAny){
                        status = "unknown";
                        tooltipMessage = "Container Unavailable";

                    // service should be up, but seems unresponsive
                    // It could be just starting, or on its way down
                    } else if(!passingAny && unknownAny){
                        status = "unknown";
                        tooltipMessage = "Missing Some Health Checks";

                    // service is up and healthy
                    } else if(passingAny && !unknownAny){
                        status = "good";
                        tooltipMessage = "Passing All Health Checks";
                    }

                // the following conditions are relevant when the service
                // *should* be off
                } else if(service.DesiredState === 0){

                    // it should be off, but its still on... weird.
                    if(passingAny){
                        status = "unknown";
                        tooltipMessage = "Stopping Service...";
                        // TODO - enable stop control?

                    // service is off, as expected
                    } else {
                        status = "disabled";
                    }
                }

                updateServiceStatus(service, status, tooltipMessage);
            }

            // if a specific appId was provided, its status may not
            // yet be part of health checks, so give it unknown status
            if(appId && !findInArray("ServiceID", running, appId)){
                updateServiceStatus(services[appId], "unknown", "Container Unavailable");
            }
        }

        function updateServiceStatus(service, status, tooltipMessage){
            setStatus(service, status);

            // if the status has changed since last tick, or
            // it was and is still unknown, notify user
            if(service.healthStatus !== status ||
                service.healthStatus === "unknown" && status === "unknown"){
                bounceStatus(service);
            }

            service.healthTooltipTitle = tooltipMessage;

            // store the status for comparison later
            service.healthStatus = status;
        }

        function setStatus(service, status){
            service.healthIconClass = ["glyphicon", STATUS_STYLES[status]];
        }
        function bounceStatus(service){
            service.healthIconClass.push("zoom");

            // TODO - dont touch dom!
            var $el = $("tr[data-id='"+ service.Id +"'] .healthIcon");
            $el.on("webkitAnimationEnd", function(){
                // if zoom is in the class list, remove it
                if(~service.healthIconClass.indexOf("zoom")){
                    service.healthIconClass.splice(service.healthIconClass.indexOf("zoom"), 1);
                }
                // clean up animation end listener
                $el.off("webkitAnimationEnd");
            });
        }

        // TODO - this is a terrible way to expose this object, but
        // until main.js is fully encapsulated, this is the only way
        $rootScope.serviceHealth = {
            update: update
        };

        return {
            update: update
        };
    }]);

})();<commit_msg>more descriptive var names<commit_after>/* global angular, console, $ */
(function() {
    'use strict';

    angular.module('serviceHealth', []).
    factory("$serviceHealth", ["$rootScope", "$q", "$http", "resourcesService", function($rootScope, $q, $http, resourcesService){

        var servicesService = resourcesService;

        var STATUS_STYLES = {
            "bad": "glyphicon-exclamation-sign bad",
            "good": "glyphicon-ok-sign good",
            "unknown": "glyphicon-question-sign unknown",
            // "disabled": "glyphicon-minus-sign disabled",
            "disabled": ""
        };

        // auto update all service health statuses
        var updateInterval = setInterval(update, 3000);

        // simple array search util
        function findInArray(key, arr, val){
            for(var i = 0; i < arr.length; i++){
                if(arr[i][key] === val){
                    return arr[i];
                }
            }
        }

        function getRunningServiceById(serviceId){
            // subservices isn't defined if we're on a single
            // service page, so just skip this service alltogether
            if(!running) return;

            return findInArray("ServiceID", running, serviceId);
        }

        // updates health check data for all services
        // `appId` is the id of the specific service being clicked
        function update(appId) {

            // TODO - these methods should return promises, but they
            // don't so use our own promises
            var servicesDeferred = $q.defer();
            var runningServicesDeferred = $q.defer();
            var healthCheckDeferred = $http.get("/servicehealth");

            servicesService.get_services(true, function(top, mapped){
                servicesDeferred.resolve(mapped);
            });

            servicesService.get_running_services(function(runningServices){
                runningServicesDeferred.resolve(runningServices);
            });

            $q.all({
                services: servicesDeferred.promise,
                health: healthCheckDeferred,
                running: runningServicesDeferred.promise
            }).then(function(results){
                evaluateServiceStatus(results.running, results.services, results.health.data, appId);
            });
        }

        function evaluateServiceStatus(running, services, healthCheckData, appId) {

            var healths = healthCheckData.Statuses,
                serverTimestamp = healthCheckData.Timestamp;

            var service, healthCheck, runningService, startTime,
                passingAny, failingAny, unknownAny, downAny, status,
                missedIntervals, tooltipMessage;

            for (var ServiceId in healths) {

                service = services[ServiceId];
                runningService = findInArray("ServiceID", running, ServiceId);

                if(!service){
                    return;
                }

                // get the time this service was started
                if(runningService){
                    startTime = new Date(runningService.StartedAt).getTime();

                // otherwise service hasn't been started
                } else {
                    startTime = 0;
                }

                healthCheck = healths[ServiceId];

                service.healthTooltipTitle = "";

                passingAny = false;
                failingAny = false;
                unknownAny = false;
                downAny = false;
                status = null;
                missedIntervals = 0;
                tooltipMessage = "";

                for (var name in healthCheck) {

                    // calculates the number of missed healthchecks since last start time
                    missedIntervals = (serverTimestamp - Math.max(healthCheck[name].Timestamp, startTime)) / healthCheck[name].Interval;

                    // if service hasn't started yet
                    if(!startTime){
                        healthCheck[name].Status = "down";

                    // if service has missed 2 updates, mark unknown
                    } else if (missedIntervals > 2 && missedIntervals < 60) {
                        healthCheck[name].Status = "unknown";

                    // if service has missed 60 updates, mark failed
                    } else if (missedIntervals > 60) {
                        healthCheck[name].Status = "failed";
                    }

                    switch(healthCheck[name].Status){
                        case "passed":
                            passingAny = true;
                            break;
                        case "failed":
                            failingAny = true;
                            break;
                        case "unknown":
                            unknownAny = true;
                            break;
                        case "down":
                            downAny = true;
                            break;
                        default:
                            break;
                    }

                    // TODO - do something with `name` so the user has a
                    // more detailed explanation of which checks are failing
                }

                // the following conditions are relevant when the service
                // *should* be started
                if(service.DesiredState === 1){

                    // service should be up, but is failing. bad!
                    if(failingAny){
                        status = "bad";
                        tooltipMessage = "Failing Health Checks";

                    // service should be up, but container has not
                    // yet loaded
                    } else if(downAny){
                        status = "unknown";
                        tooltipMessage = "Container Unavailable";

                    // service should be up, but seems unresponsive
                    // It could be just starting, or on its way down
                    } else if(!passingAny && unknownAny){
                        status = "unknown";
                        tooltipMessage = "Missing Some Health Checks";

                    // service is up and healthy
                    } else if(passingAny && !unknownAny){
                        status = "good";
                        tooltipMessage = "Passing All Health Checks";
                    }

                // the following conditions are relevant when the service
                // *should* be off
                } else if(service.DesiredState === 0){

                    // it should be off, but its still on... weird.
                    if(passingAny){
                        status = "unknown";
                        tooltipMessage = "Stopping Service...";
                        // TODO - enable stop control?

                    // service is off, as expected
                    } else {
                        status = "disabled";
                    }
                }

                updateServiceStatus(service, status, tooltipMessage);
            }

            // if a specific appId was provided, its status may not
            // yet be part of health checks, so give it unknown status
            if(appId && !findInArray("ServiceID", running, appId)){
                updateServiceStatus(services[appId], "unknown", "Container Unavailable");
            }
        }

        function updateServiceStatus(service, status, tooltipMessage){
            setStatus(service, status);

            // if the status has changed since last tick, or
            // it was and is still unknown, notify user
            if(service.healthStatus !== status ||
                service.healthStatus === "unknown" && status === "unknown"){
                bounceStatus(service);
            }

            service.healthTooltipTitle = tooltipMessage;

            // store the status for comparison later
            service.healthStatus = status;
        }

        function setStatus(service, status){
            service.healthIconClass = ["glyphicon", STATUS_STYLES[status]];
        }
        function bounceStatus(service){
            service.healthIconClass.push("zoom");

            // TODO - dont touch dom!
            var $el = $("tr[data-id='"+ service.Id +"'] .healthIcon");
            $el.on("webkitAnimationEnd", function(){
                // if zoom is in the class list, remove it
                if(~service.healthIconClass.indexOf("zoom")){
                    service.healthIconClass.splice(service.healthIconClass.indexOf("zoom"), 1);
                }
                // clean up animation end listener
                $el.off("webkitAnimationEnd");
            });
        }

        // TODO - this is a terrible way to expose this object, but
        // until main.js is fully encapsulated, this is the only way
        $rootScope.serviceHealth = {
            update: update
        };

        return {
            update: update
        };
    }]);

})();<|endoftext|>


<commit_before>import test from 'ava';
import '~client-test/browser';
import { fromJS } from 'immutable';
import { render } from 'react-testing-library';
import { createMockStore } from 'redux-test-utils';
import React from 'react';
import Root from '~client/containers/Root';

const getContainer = (customProps = {}, customState = null) => {
    let state = fromJS({
        user: {
            uid: 1
        },
        loadingApi: false,
        errorMsg: [],
        loginForm: {
            inputStep: 0,
            visible: false,
            active: false,
            values: []
        },
        edit: {
            requestList: []
        }
    });

    if (customState) {
        state = customState(state);
    }

    const store = createMockStore(state);

    const props = {
        store,
        ...customProps
    };

    const utils = render(
        <Root {...props} />
    );

    return { store, ...utils };
};

test('main container', t => {
    const { container } = getContainer();

    t.is(container.childNodes.length, 1);

    const [div] = container.childNodes;

    t.is(div.tagName, 'DIV');
    t.is(div.className, 'main');
    t.is(div.childNodes.length, 3);
});

<commit_msg>Added properties to state in <Root /> test to get rid of missing prop warnings in test<commit_after>import test from 'ava';
import '~client-test/browser';
import { fromJS } from 'immutable';
import { render } from 'react-testing-library';
import { createMockStore } from 'redux-test-utils';
import React from 'react';
import Root from '~client/containers/Root';

const getContainer = (customProps = {}, customState = null) => {
    let state = fromJS({
        user: {
            uid: 1
        },
        currentPage: 'general',
        loading: false,
        loadingApi: false,
        errorMsg: [],
        loginForm: {
            inputStep: 0,
            visible: false,
            active: false,
            values: []
        },
        modalDialog: {
            active: false,
            visible: false,
            loading: false
        },
        edit: {
            requestList: []
        }
    });

    if (customState) {
        state = customState(state);
    }

    const store = createMockStore(state);

    const props = {
        store,
        ...customProps
    };

    const utils = render(
        <Root {...props} />
    );

    return { store, ...utils };
};

test('main container', t => {
    const { container } = getContainer();

    t.is(container.childNodes.length, 1);

    const [div] = container.childNodes;

    t.is(div.tagName, 'DIV');
    t.is(div.className, 'main');
    t.is(div.childNodes.length, 3);
});

<|endoftext|>