<commit_before>// for Google Publisher Tag ads
//
// required props:
//    - adId: eg, '/6355419/Travel/Europe/France/Paris'
//    - height: a css size in pixels
//    - width: ditto
//
// optional props:
//    - placement: only useful if the same `adId` is used more than once on a
//      page, use this to distinguish between them: call one "1" and the other
//      "2", or call them "top-left" and "bottom-right", etc
//    - refresh: number of seconds between refreshes
//    - shouldWatchViewport: turn off checks for ad in view
//    - tracing: verbose messages in console.log via Ember.Logger.log

import Ember from 'ember';
import {task, timeout} from 'ember-concurrency';
import InViewportMixin from 'ember-in-viewport';
import getViewportTolerance from '../utils/get-viewport-tolerance';

const {
    Component,
    assert,
    get, set, getProperties, setProperties,
    String: { htmlSafe },
    Logger: { log },
    inject: { service },
    run,
    run: { scheduleOnce }
} = Ember;

export default Component.extend(InViewportMixin, {
    classNames: ['google-publisher-tag'],
    attributeBindings: ['style'],

    adQueue: service(),

    placement: 0,
    refresh: 0,
    refreshCount: 0,
    tracing: false,
    shouldWatchViewport: true,

    didReceiveAttrs() {
        this._super(...arguments);

        let {adId, width, height, placement} = getProperties(this, 'adId', 'width', 'height', 'placement');

        // width and height are also passed into .defineSlot(), which will
        // silently fail unless they are actually numbers
        assert(`google-publisher-tag "${adId} (${placement})": width and height must be numbers`, typeof width === 'number' && typeof height === 'number');

        let style = `width:${width}px; height:${height}px;`;
        set(this, 'style', htmlSafe(style));
    },
    didInsertElement() {
        this._super(...arguments);

        let {
          shouldWatchViewport,
          viewportEntered,
          width,
          height
        } = getProperties(this,
          'shouldWatchViewport',
          'viewportEntered',
          'width',
          'height'
        );

        setProperties(this, {
          viewportEnabled: shouldWatchViewport,
          viewportSpy: true,
          viewportTolerance: getViewportTolerance(width, height, 0.5)
        });

        scheduleOnce('afterRender', () => {
          if (!shouldWatchViewport || viewportEntered) {
            this.initAd();
          } else {
            this.trace('ad hidden on load, not initialized');
          }
        });
    },

    initAd() {
      get(this, 'adQueue').push(this);

      this.trace('ad initialized');

      set(this, 'isAdInitialized', true);

      this.waitForRefresh();
    },

    addTargeting(slot) { // jshint ignore:line
        // override this in child components, if needed, but an example is:
        // slot.setTargeting('placement', get(this, 'placement'));
        // slot.setTargeting('refresh_count', get(this, 'refreshCount'));
        // slot.setTargeting('planet', 'Earth');
    },
    waitForRefresh() {
        let duration = get(this, 'refresh');
        if (duration > 0) {
            this.trace(`will refresh in ${duration} seconds`);

            // give the tests a moment to release wait handlers
            setTimeout(() => {
              run(() => {
                get(this, 'refreshWaitTask').perform(duration);
              });
            });
        }
    },
    trace() {
        if (get(this, 'tracing')) {
            let {adId, placement} = getProperties(this, 'adId', 'placement');
            log(`${adId} (${placement}): `, ...arguments);
        }
    },

    refreshWaitTask: task(function * (duration) {
        this.incrementProperty('refreshCount');

        yield timeout(duration * 1000);

        let {
          shouldWatchViewport,
          viewportEntered
        } = getProperties(this,
          'shouldWatchViewport',
          'viewportEntered'
        );

        if (shouldWatchViewport && !viewportEntered) {
          this.trace('ad not in view, skipped refresh');

          return set(this, 'isRefreshOverdue', true);
        }

        this.doRefresh();
    }).restartable(),

    doRefresh() {
        let googletag = window.googletag;
        googletag.cmd.push( () => {
            let slot = get(this, 'slot');
            this.trace('refreshing now');
            this.addTargeting(slot);
            googletag.pubads().refresh([slot]);
            this.waitForRefresh();
        });
    },

    didEnterViewport() {
      this.trace('entered viewport');

      let isAdInitialized = get(this, 'isAdInitialized');
      if (!isAdInitialized) {
        this.initAd();
      } else {
        let isRefreshOverdue = get(this, 'isRefreshOverdue');
        if (isRefreshOverdue) {
          this.doRefresh();

          set(this, 'isRefreshOverdue', false);
        }
      }
    }
});
<commit_msg>fix double-init error (non-breaking error)<commit_after>// for Google Publisher Tag ads
//
// required props:
//    - adId: eg, '/6355419/Travel/Europe/France/Paris'
//    - height: a css size in pixels
//    - width: ditto
//
// optional props:
//    - placement: only useful if the same `adId` is used more than once on a
//      page, use this to distinguish between them: call one "1" and the other
//      "2", or call them "top-left" and "bottom-right", etc
//    - refresh: number of seconds between refreshes
//    - shouldWatchViewport: turn off checks for ad in view
//    - tracing: verbose messages in console.log via Ember.Logger.log

import Ember from 'ember';
import {task, timeout} from 'ember-concurrency';
import InViewportMixin from 'ember-in-viewport';
import getViewportTolerance from '../utils/get-viewport-tolerance';

const {
    Component,
    assert,
    get, set, getProperties, setProperties,
    String: { htmlSafe },
    Logger: { log },
    inject: { service },
    run,
    run: { scheduleOnce }
} = Ember;

export default Component.extend(InViewportMixin, {
    classNames: ['google-publisher-tag'],
    attributeBindings: ['style'],

    adQueue: service(),

    placement: 0,
    refresh: 0,
    refreshCount: 0,
    tracing: false,
    shouldWatchViewport: true,

    didReceiveAttrs() {
        this._super(...arguments);

        let {adId, width, height, placement} = getProperties(this, 'adId', 'width', 'height', 'placement');

        // width and height are also passed into .defineSlot(), which will
        // silently fail unless they are actually numbers
        assert(`google-publisher-tag "${adId} (${placement})": width and height must be numbers`, typeof width === 'number' && typeof height === 'number');

        let style = `width:${width}px; height:${height}px;`;
        set(this, 'style', htmlSafe(style));
    },
    didInsertElement() {
        this._super(...arguments);

        let {
          shouldWatchViewport,
          viewportEntered,
          width,
          height
        } = getProperties(this,
          'shouldWatchViewport',
          'viewportEntered',
          'width',
          'height'
        );

        setProperties(this, {
          viewportEnabled: shouldWatchViewport,
          viewportSpy: true,
          viewportTolerance: getViewportTolerance(width, height, 0.5)
        });

        scheduleOnce('afterRender', () => {
          if (!shouldWatchViewport || viewportEntered) {
            this.initAd();
          } else {
            this.trace('ad hidden on load, not initialized');
          }
        });
    },

    initAd() {
      if (!get(this, 'isAdInitialized')) {
        this.trace('initializing');
        get(this, 'adQueue').push(this);
        set(this, 'isAdInitialized', true);
      }
      this.waitForRefresh();
    },

    addTargeting(slot) { // jshint ignore:line
        // override this in child components, if needed, but an example is:
        // slot.setTargeting('placement', get(this, 'placement'));
        // slot.setTargeting('refresh_count', get(this, 'refreshCount'));
        // slot.setTargeting('planet', 'Earth');
    },
    waitForRefresh() {
        let duration = get(this, 'refresh');
        if (duration > 0) {
            this.trace(`will refresh in ${duration} seconds`);

            // give the tests a moment to release wait handlers
            setTimeout(() => {
              run(() => {
                get(this, 'refreshWaitTask').perform(duration);
              });
            });
        }
    },
    trace() {
        if (get(this, 'tracing')) {
            let {adId, placement} = getProperties(this, 'adId', 'placement');
            log(`${adId} (${placement}): `, ...arguments);
        }
    },

    refreshWaitTask: task(function * (duration) {
        this.incrementProperty('refreshCount');

        yield timeout(duration * 1000);

        let {
          shouldWatchViewport,
          viewportEntered
        } = getProperties(this,
          'shouldWatchViewport',
          'viewportEntered'
        );

        if (shouldWatchViewport && !viewportEntered) {
          this.trace('ad not in view, skipped refresh');

          return set(this, 'isRefreshOverdue', true);
        }

        this.doRefresh();
    }).restartable(),

    doRefresh() {
        let googletag = window.googletag;
        googletag.cmd.push( () => {
            let slot = get(this, 'slot');
            this.trace('refreshing now');
            this.addTargeting(slot);
            googletag.pubads().refresh([slot]);
            this.waitForRefresh();
        });
    },

    didEnterViewport() {
      this.trace('entered viewport');

      this.initAd();
      if (get(this, 'isRefreshOverdue')) {
        this.doRefresh();
        set(this, 'isRefreshOverdue', false);
      }
    }
});
<|endoftext|>


<commit_before>window.the_second_coming_of_jesus=null;
window.current_plot_data=null;
window.current_plot_obj=null;
window.current_instrument_list=null;
window.current_instrument_types={"Hiseq":[],"Miseq":[],"HiseqX":[]};

$(function(){
    init_page_js();
});

function obtain_data(start_date, end_date, group_level, display_type){
     get_plot_data(start_date, end_date, group_level, display_type).then(function(data){return get_instrument_lists(data)});

}
function refresh_plot(){
    var params=get_parameters();
    get_plot_data(start_date=params[0], end_date=params[1], group_level=params[2], display_type=params[3]).done(function(data){
     get_instrument_lists(data).done(function(data){
         make_plot(start_date=params[0], end_date=params[1], group_level=params[2], display_type=params[3])})
    });
}
function make_plot(start_date, end_date, group_level,display_type){
    var x_title = null;
    var time_labels = null;
    var x_date_format = null;
    switch(group_level){
      case 2:
          x_title = "Year";
          time_labels={millisecond: '%Y'};
          x_date_format = '%Y';
          break;
      case 3:
          x_title = "Month";
          time_labels={month: '%Y-%m'};
          x_date_format = '%Y-%m';
          break;
      case 5:
          x_title = "Day";
          time_labels={month: '%Y-%m-%d'};
          x_date_format = '%Y-%m-%d';
          break;
      default:
          x_title = "Week Number";
          time_labels={month: '%Y-%m'};
          x_date_format = '%Y-%m-%d';
          break;
    }
    var toplot={
        chart: {
            type : 'bar'
        },
        title: {
            text : ' Number of the flowcells per '+display_type
        },
        legend : {
             layout: 'vertical',
             align: 'right',
             verticalAlign: 'middle'
        },
        yAxis: {
            min : 0,
            title: "Number of flowcells"
        },
        plotOptions : {
            series : {
                stacking:'normal',
                turboThreshold: 0
            },

        },
        tooltip: {
            useHTML: true,
            xDateFormat: x_date_format,
            shared: true,
            formatter: function () {
              var points = this.points;
              var pointsLength = points.length;
              var tooltipMarkup = '';
              for(var i = 0; i < pointsLength; i += 1) {
                tooltipMarkup += '\u25CF'+points[i].series.name+': '+points[i].y+'
';
              }
              return tooltipMarkup;
            }
        },
        credits: {
            enabled : false
        },
        xAxis: {
            type: 'datetime',
            dateTimeLabelFormats:time_labels,
            title : x_title,
        },
        series: [{
            name : name,
            data:[]
        }],
    };
    if (display_type == "instrument"){
      series=build_instrument_series(start_date, end_date, group_level);
    }else{
      series=build_type_series(start_date, end_date, group_level);
    }
    toplot.series=series;
    $("#main_plot").highcharts(toplot);
    window.current_plot_obj=toplot;
}
function build_type_series(start_date, end_date, group_level){
    var data=window.current_plot_data;
    var categories=[];
    var series=[];
    var holder={'Hiseq':{}, 'Miseq':{}, 'HiseqX':{}, 'NovaSeq':{}}
    var key = null;
  for (d in data){
      try {
          key = get_date_key(data[d], group_level);
          holder_object = holder[window.current_instrument_types[data[d][0]]];
          if (key in holder_object){
              holder_object[key]= holder_object[key] + data[d][group_level];
          }else{
              holder_object[key]= data[d][group_level];
          }
      }
      catch(err) {
          console.log(err);
      }
    }
    var series = [];
    if (Object.keys(holder.Hiseq).length !== 0 && holder.Hiseq.constructor === Object){
    series.push({'name':'Hiseq', data:build_points(holder.Hiseq), marker:{enabled : true}});
    }
    if (Object.keys(holder.Miseq).length !== 0 && holder.Miseq.constructor === Object){
    series.push({'name':'Miseq', data:build_points(holder.Miseq), marker:{enabled : true}});
    }
    if (Object.keys(holder.HiseqX).length !== 0 && holder.HiseqX.constructor === Object){
    series.push({'name':'HiseqX', data:build_points(holder.HiseqX), marker:{enabled : true}});
    }
    if (Object.keys(holder.NovaSeq).length !== 0 && holder.NovaSeq.constructor === Object){
    series.push({'name':'NovaSeq', data:build_points(holder.NovaSeq), marker:{enabled : true}});
    }
    return series;
}
function compare_points(a,b){
    return a.x-b.x;
}
function build_points(obj){
    points=[];
    for (key in obj){
        points.push({y:obj[key], x:parseInt(key,10)});
    }
    points.sort(compare_points);
    return points;

}
function get_date_key(row, group_level){
    var key = null;
    if (group_level == 5){
        key = new Date(parseInt(row[1],10), parseInt(row[2],10)-1, parseInt(row[4],10));
    }else if (group_level == 3 ){
        key = new Date(parseInt(row[1],10), parseInt(row[2],10)-1, 2);
    }else if (group_level == 2 ){
        key = new Date(parseInt(row[1],10),1,1);
    }else{
        var day = (1 + (parseInt(row[3],10) - 1) * 7);
        key = new Date(parseInt(row[1],10), 0, day);
        var dow = key.getDay();
        if (dow <= 4){
            key.setDate(key.getDate() - key.getDay() +1);
        }else{
            key.setDate(key.getDate() - key.getDay() +8);
        }
    }
    return key.getTime();
}
function build_instrument_series(start_date, end_date, group_level){
    data = window.current_plot_data;
    var series=[];
    var holder={}
    var key = null;
    for (d in data){
        key = get_date_key(data[d], group_level);
        instrument_name = window.current_instrument_list[data[d][0]];
        if (instrument_name == undefined){
            instrument_name = data[d][0];
            console.log("Please update the instruments database with " +data[d][0]);
        }

        if (!(instrument_name in holder)){
        holder[instrument_name] = [];
        }
        holder[instrument_name].push({y:data[d][group_level], x:key});
    }
    for (r in holder){
        holder[r].sort(compare_points);
        series.push({'name':r, data:holder[r]})
    }
    return series;
}

function get_plot_data(start_date, end_date, group_level, display_type){
            return $.getJSON('/api/v1/flowcell_count/?group_level='+group_level+'&start_date='+start_date+'&end_date='+end_date+'&display_type='+display_type, function(data) {
                window.current_plot_data=data;
                return data
            });
}

function get_parameters(){
     var first_half;
     var first_date;
     var second_half;
     var second_date;
     var dp=$('#inp_date_1').val();
     if (dp != ''){
         start_date=dp;
     }else{
         first_date=new Date();
         first_date.setYear(first_date.getYear()-1);
         start_date=first_date.toISOString().substr(0,10);
     }
     dp=$('#inp_date_2').val();
     if (dp != ''){
         end_date=dp;
     }else{
        second_date=new Date();
        end_date=second_date.toISOString().substr(0,10);
     }

     //then, the display type
     var display_type;
     var display_type = $( "#display_select option:selected" ).val();
     var group_level = parseInt($( "#display_time_select option:selected" ).val(),10);

     var ret=[start_date, end_date, group_level, display_type];

     return ret;
}

function init_page_js(){
    $('#datepick1').datepicker({autoclose: true,
    format: 'yyyy-mm-dd',
    todayBtn: true,
    todayHighlight: true,
    weekStart: 1,
    daysOfWeekHighlighted: "0,6" });
    $('#datepick2').datepicker({autoclose: true,
    format: 'yyyy-mm-dd',
    todayBtn: true,
    todayHighlight: true,
    weekStart: 1,
    daysOfWeekHighlighted: "0,6" });
     var my_date=new Date();
     $('#inp_date_2').val(my_date.toISOString().substr(0,10));
     my_date.setYear(my_date.getFullYear()-1);
     $('#inp_date_1').val(my_date.toISOString().substr(0,10));
    $('#submit_interval').click(function(e){
     e.preventDefault();
     window.current_plot_data=null;
     refresh_plot();
    });
    $("#display_type_buttons .btn").click(function(e){
        e.preventDefault();
        //datepicker messes up by adding eventlisteners to all buttons.
        e.stopImmediatePropagation()
        $("#display_type_buttons .btn").removeClass('active');
        $(this).addClass("active");
        if ($(this).text() == 'Lane'){
            $(".key_select_lane").each(function(){
                $(this).prop( "disabled", false);
            });
        } else{
            $(".key_select_lane").each(function(){
                $(this).prop( "disabled", true);
            });
        }
        refresh_plot();
    });
    $("#display_select_form").change(function(e){
        e.preventDefault();
        e.stopImmediatePropagation()
        refresh_plot();

    });
    refresh_plot();
}

function get_instrument_lists(plot_data){
        return $.getJSON("/api/v1/instrument_names", function(data){
            current_instrument_list = {};
            current_instrument_types={};
            for (d in plot_data){
                if (!(plot_data[d][0] in current_instrument_list)){
                    for (r in data){
                      if (data[r].key == plot_data[d][0]){
                        current_instrument_list[plot_data[d][0]]=data[r].value;
                      }
                    }
                }
                if (plot_data[d][0].indexOf("D") != -1){
                    current_instrument_types[plot_data[d][0]] = 'Hiseq';
                }
                else if (plot_data[d][0].indexOf("M") != -1){
                    current_instrument_types[plot_data[d][0]] = 'Miseq';
                }
                else if (plot_data[d][0].indexOf("E") != -1){
                    current_instrument_types[plot_data[d][0]] = 'HiseqX';
                }
                else if (plot_data[d][0].indexOf("A") != -1){
                    current_instrument_types[plot_data[d][0]] = 'NovaSeq';
                }
            }
        window.current_instrument_list=current_instrument_list;
        window.current_instrument_types=current_instrument_types;
        return [current_instrument_list, current_instrument_types]
        });
}
<commit_msg>Make the tooltip less jumpy<commit_after>window.the_second_coming_of_jesus=null;
window.current_plot_data=null;
window.current_plot_obj=null;
window.current_instrument_list=null;
window.current_instrument_types={"Hiseq":[],"Miseq":[],"HiseqX":[]};

$(function(){
    init_page_js();
});

function obtain_data(start_date, end_date, group_level, display_type){
     get_plot_data(start_date, end_date, group_level, display_type).then(function(data){return get_instrument_lists(data)});

}
function refresh_plot(){
    var params=get_parameters();
    get_plot_data(start_date=params[0], end_date=params[1], group_level=params[2], display_type=params[3]).done(function(data){
     get_instrument_lists(data).done(function(data){
         make_plot(start_date=params[0], end_date=params[1], group_level=params[2], display_type=params[3])})
    });
}
function make_plot(start_date, end_date, group_level,display_type){
    var x_title = null;
    var time_labels = null;
    var x_date_format = null;
    switch(group_level){
      case 2:
          x_title = "Year";
          time_labels={millisecond: '%Y'};
          x_date_format = '%Y';
          break;
      case 3:
          x_title = "Month";
          time_labels={month: '%Y-%m'};
          x_date_format = '%Y-%m';
          break;
      case 5:
          x_title = "Day";
          time_labels={month: '%Y-%m-%d'};
          x_date_format = '%Y-%m-%d';
          break;
      default:
          x_title = "Week Number";
          time_labels={month: '%Y-%m'};
          x_date_format = '%Y-%m-%d';
          break;
    }
    var toplot={
        chart: {
            type : 'bar'
        },
        title: {
            text : ' Number of the flowcells per '+display_type
        },
        legend : {
             layout: 'vertical',
             align: 'right',
             verticalAlign: 'middle'
        },
        yAxis: {
            min : 0,
            title: "Number of flowcells"
        },
        plotOptions : {
            series : {
                stacking:'normal',
                turboThreshold: 0
            },

        },
        tooltip: {
            useHTML: true,
            xDateFormat: x_date_format,
            shared: true,
            followPointer: true,
            formatter: function () {
              var points = this.points;
              var pointsLength = points.length;
              var tooltipMarkup = '
';
              for(var i = 0; i < pointsLength; i += 1) {
                tooltipMarkup += '
\u25CF '+points[i].series.name+': 	'+points[i].y+'
';
              }
              return tooltipMarkup+"
";
            }
        },
        credits: {
            enabled : false
        },
        xAxis: {
            type: 'datetime',
            dateTimeLabelFormats:time_labels,
            title : x_title,
        },
        series: [{
            name : name,
            data:[]
        }],
    };
    if (display_type == "instrument"){
      series=build_instrument_series(start_date, end_date, group_level);
    }else{
      series=build_type_series(start_date, end_date, group_level);
    }
    toplot.series=series;
    $("#main_plot").highcharts(toplot);
    window.current_plot_obj=toplot;
}
function build_type_series(start_date, end_date, group_level){
    var data=window.current_plot_data;
    var categories=[];
    var series=[];
    var holder={'Hiseq':{}, 'Miseq':{}, 'HiseqX':{}, 'NovaSeq':{}}
    var key = null;
  for (d in data){
      try {
          key = get_date_key(data[d], group_level);
          holder_object = holder[window.current_instrument_types[data[d][0]]];
          if (key in holder_object){
              holder_object[key]= holder_object[key] + data[d][group_level];
          }else{
              holder_object[key]= data[d][group_level];
          }
      }
      catch(err) {
          console.log(err);
      }
    }
    var series = [];
    if (Object.keys(holder.Hiseq).length !== 0 && holder.Hiseq.constructor === Object){
    series.push({'name':'Hiseq', data:build_points(holder.Hiseq), marker:{enabled : true}});
    }
    if (Object.keys(holder.Miseq).length !== 0 && holder.Miseq.constructor === Object){
    series.push({'name':'Miseq', data:build_points(holder.Miseq), marker:{enabled : true}});
    }
    if (Object.keys(holder.HiseqX).length !== 0 && holder.HiseqX.constructor === Object){
    series.push({'name':'HiseqX', data:build_points(holder.HiseqX), marker:{enabled : true}});
    }
    if (Object.keys(holder.NovaSeq).length !== 0 && holder.NovaSeq.constructor === Object){
    series.push({'name':'NovaSeq', data:build_points(holder.NovaSeq), marker:{enabled : true}});
    }
    return series;
}
function compare_points(a,b){
    return a.x-b.x;
}
function build_points(obj){
    points=[];
    for (key in obj){
        points.push({y:obj[key], x:parseInt(key,10)});
    }
    points.sort(compare_points);
    return points;

}
function get_date_key(row, group_level){
    var key = null;
    if (group_level == 5){
        key = new Date(parseInt(row[1],10), parseInt(row[2],10)-1, parseInt(row[4],10));
    }else if (group_level == 3 ){
        key = new Date(parseInt(row[1],10), parseInt(row[2],10)-1, 2);
    }else if (group_level == 2 ){
        key = new Date(parseInt(row[1],10),1,1);
    }else{
        var day = (1 + (parseInt(row[3],10) - 1) * 7);
        key = new Date(parseInt(row[1],10), 0, day);
        var dow = key.getDay();
        if (dow <= 4){
            key.setDate(key.getDate() - key.getDay() +1);
        }else{
            key.setDate(key.getDate() - key.getDay() +8);
        }
    }
    return key.getTime();
}
function build_instrument_series(start_date, end_date, group_level){
    data = window.current_plot_data;
    var series=[];
    var holder={}
    var key = null;
    for (d in data){
        key = get_date_key(data[d], group_level);
        instrument_name = window.current_instrument_list[data[d][0]];
        if (instrument_name == undefined){
            instrument_name = data[d][0];
            console.log("Please update the instruments database with " +data[d][0]);
        }

        if (!(instrument_name in holder)){
        holder[instrument_name] = [];
        }
        holder[instrument_name].push({y:data[d][group_level], x:key});
    }
    for (r in holder){
        holder[r].sort(compare_points);
        series.push({'name':r, data:holder[r]})
    }
    return series;
}

function get_plot_data(start_date, end_date, group_level, display_type){
            return $.getJSON('/api/v1/flowcell_count/?group_level='+group_level+'&start_date='+start_date+'&end_date='+end_date+'&display_type='+display_type, function(data) {
                window.current_plot_data=data;
                return data
            });
}

function get_parameters(){
     var first_half;
     var first_date;
     var second_half;
     var second_date;
     var dp=$('#inp_date_1').val();
     if (dp != ''){
         start_date=dp;
     }else{
         first_date=new Date();
         first_date.setYear(first_date.getYear()-1);
         start_date=first_date.toISOString().substr(0,10);
     }
     dp=$('#inp_date_2').val();
     if (dp != ''){
         end_date=dp;
     }else{
        second_date=new Date();
        end_date=second_date.toISOString().substr(0,10);
     }

     //then, the display type
     var display_type;
     var display_type = $( "#display_select option:selected" ).val();
     var group_level = parseInt($( "#display_time_select option:selected" ).val(),10);

     var ret=[start_date, end_date, group_level, display_type];

     return ret;
}

function init_page_js(){
    $('#datepick1').datepicker({autoclose: true,
    format: 'yyyy-mm-dd',
    todayBtn: true,
    todayHighlight: true,
    weekStart: 1,
    daysOfWeekHighlighted: "0,6" });
    $('#datepick2').datepicker({autoclose: true,
    format: 'yyyy-mm-dd',
    todayBtn: true,
    todayHighlight: true,
    weekStart: 1,
    daysOfWeekHighlighted: "0,6" });
     var my_date=new Date();
     $('#inp_date_2').val(my_date.toISOString().substr(0,10));
     my_date.setYear(my_date.getFullYear()-1);
     $('#inp_date_1').val(my_date.toISOString().substr(0,10));
    $('#submit_interval').click(function(e){
     e.preventDefault();
     window.current_plot_data=null;
     refresh_plot();
    });
    $("#display_type_buttons .btn").click(function(e){
        e.preventDefault();
        //datepicker messes up by adding eventlisteners to all buttons.
        e.stopImmediatePropagation()
        $("#display_type_buttons .btn").removeClass('active');
        $(this).addClass("active");
        if ($(this).text() == 'Lane'){
            $(".key_select_lane").each(function(){
                $(this).prop( "disabled", false);
            });
        } else{
            $(".key_select_lane").each(function(){
                $(this).prop( "disabled", true);
            });
        }
        refresh_plot();
    });
    $("#display_select_form").change(function(e){
        e.preventDefault();
        e.stopImmediatePropagation()
        refresh_plot();

    });
    refresh_plot();
}

function get_instrument_lists(plot_data){
        return $.getJSON("/api/v1/instrument_names", function(data){
            current_instrument_list = {};
            current_instrument_types={};
            for (d in plot_data){
                if (!(plot_data[d][0] in current_instrument_list)){
                    for (r in data){
                      if (data[r].key == plot_data[d][0]){
                        current_instrument_list[plot_data[d][0]]=data[r].value;
                      }
                    }
                }
                if (plot_data[d][0].indexOf("D") != -1){
                    current_instrument_types[plot_data[d][0]] = 'Hiseq';
                }
                else if (plot_data[d][0].indexOf("M") != -1){
                    current_instrument_types[plot_data[d][0]] = 'Miseq';
                }
                else if (plot_data[d][0].indexOf("E") != -1){
                    current_instrument_types[plot_data[d][0]] = 'HiseqX';
                }
                else if (plot_data[d][0].indexOf("A") != -1){
                    current_instrument_types[plot_data[d][0]] = 'NovaSeq';
                }
            }
        window.current_instrument_list=current_instrument_list;
        window.current_instrument_types=current_instrument_types;
        return [current_instrument_list, current_instrument_types]
        });
}
<|endoftext|>


<commit_before>import Ember from 'ember';

export function initialize(application) {
	var transitionOptions = null;
	var transitionType = null;
  console.log(application);
	// if(application.get("nptTransition")){
	// 	transitionOptions = application.get("nptTransition.transitionOptions");
	// 	transitionType = application.get("nptTransition.transitionType");
	// }
  	Ember.LinkComponent.reopen({
  		/**
  		    Sets the `transitionOptions` attribute of the `LinkComponent`'s HTML element.
  		    @property transitionOptions
  		    @default null (using native-page-transition default values)
  		    @public
  		**/
    	transitionOptions: {
        "direction"        : "left",
          "duration"         :  400,
          "slowdownfactor"   :    1,
          "iosdelay"         :  -1,
          "androiddelay"     :  -1,
          "winphonedelay"    :  -1,
          "fixedPixelsTop"   :    0,
          "fixedPixelsBottom":   0
      },

    	/**
  		    Sets the `transitionType` attribute of the `LinkComponent`'s HTML element.
  		    @property transitionType
  		    @default null (no transition by default)
  		    @public
  		**/
    	transitionType: "slide",

    	/**
    		Override
    	**/
    	// qualifiedRouteName: function() {
     //    console.log("npt - qualifiedRouteName");
     //    return {
     //      routeName:this._super(...arguments),
     //      transition:{
     //        transitionOptions:transitionOptions,
     //        transitionType:transitionType
     //      }
     //    };
     //  },
    	init: function(){
    		this._super(...arguments);
        var that = this;
    		this.get("_routing").reopen({
          transitionType:that.get("transitionType"),
          transitionOptions:that.get("transitionOptions"),
    			back: function(){
    				console.log("npt - routing back");
    				var transitionType = this.get("transitionType");
    				if(transitionType !== null && transitionType !== null){
    					//Update router routes to pop the last two routes

    					//Transition to the previous page
    					this.get("router");
    				}
    			},
    			transitionTo: function(routeName, models, queryParams, shouldReplace) {
    				console.log("npt - routing transitionTo " + JSON.stringify(routeName));
            var that = this;
    				if(this.get("transitionType") !== null){
						//Generate the url
    					var url = this.generateURL(routeName, models, queryParams);
              console.log("npt - Transition url " + url);
              console.log("npt - Transition options " + JSON.stringify(that.get("transitionOptions")));
    					//Do the transition
    					// window.plugins.nativepagetransitions.slide({
    					//     options: that.get("transitionOptions"),
    					//     "href" : url
    					// });
    				}

    				this._super(routeName, models, queryParams, shouldReplace);
    			}
    		});
    	}
    });

    Ember.Router.reopen({
    	/**
  		    Sets the `transitionActivated` attribute of the `LinkComponent`'s HTML element.
  		    @property transitionActivated
  		    @default false (no transition by default)
  		    @public
  		**/
    	transitionActivated:false,
    	/**
  		    Sets the `routes` attribute of the `LinkComponent`'s HTML element.
  		    @property routes
  		    @default false (no transition by default)
  		    @public
  		**/
    	routes:[],
    	/**
    		@override
    	**/
    	didTransition: function() {
    		console.log("npt - router didTransition");
    		//Update local route history
        this.get("routes").push(this.get("url"));

        console.log(this.get("routes"));
  	    if(this.get("transitionActivated")){
  	    	// window.plugins.nativepagetransitions.executePendingTransition(
  	    	// 	function (msg) {console.log("success: " + msg);}, // called when the animation has finished
  	    	//  	function (msg) {alert("error: " + msg);} // called in case you pass in weird values
  	    	// );
  	    }
  	    this._super(...arguments);
    	},
    	/**
			Allow to transition back to the previous url
    		@public
    	**/
    	back:function(){
    		console.log("npt - router back");
    		//Transition to the previous page

    		//Remove the last two routes from the route history
    		this.get("routes").pop();
    	}
    });

}

export default {
  name: 'npt-link-component',
  initialize
};
<commit_msg>change<commit_after>import Ember from 'ember';

export function initialize(application) {
  var transitionOptions = null;
  var transitionType = null;
  console.log(application);
  // if(application.get("nptTransition")){
  //  transitionOptions = application.get("nptTransition.transitionOptions");
  //  transitionType = application.get("nptTransition.transitionType");
  // }
    Ember.LinkComponent.reopen({
      /**
          Sets the `transitionOptions` attribute of the `LinkComponent`'s HTML element.
          @property transitionOptions
          @default null (using native-page-transition default values)
          @public
      **/
      // transitionOptions: {
     //    "direction"        : "left",
     //      "duration"         :  400,
     //      "slowdownfactor"   :    1,
     //      "iosdelay"         :  -1,
     //      "androiddelay"     :  -1,
     //      "winphonedelay"    :  -1,
     //      "fixedPixelsTop"   :    0,
     //      "fixedPixelsBottom":   0
     //  },
      transitionOptions:transitionOptions,
      /**
          Sets the `transitionType` attribute of the `LinkComponent`'s HTML element.
          @property transitionType
          @default null (no transition by default)
          @public
      **/
      // transitionType: "slide",
      transitionType: transitionType,

      // /**
      //  Override
      // **/
      // init: function(){
      //  this._super(...arguments);
     //    var transitionType = this.get("transitionType");
     //    var transitionOptions = this.get("transitionOptions");

      // }
    });

    Ember.inject.service('-routing').reopen({
          transitionType:transitionType,
          transitionOptions:transitionOptions,
          back: function(){
            console.log("npt - routing back");
            var transitionType = this.get("transitionType");
            if(transitionType !== null && transitionType !== null){
              //Update router routes to pop the last two routes

              //Transition to the previous page
              this.get("router");
            }
          },
          transitionTo: function(routeName, models, queryParams, shouldReplace) {
            console.log(transitionType);
            console.log("npt - routing transitionTo " + JSON.stringify(routeName));
            if(this.get("transitionType") !== null){
            //Generate the url
              var url = this.generateURL(routeName, models, queryParams);
              console.log("npt - Transition url " + url);
              console.log("npt - Transition options " + JSON.stringify(transitionOptions));
              //Do the transition
              // window.plugins.nativepagetransitions.slide({
              //     options: that.get("transitionOptions"),
              //     "href" : url
              // });
            }
            else {
              this._super(routeName, models, queryParams, shouldReplace);
            }
          }
        });

    Ember.Router.reopen({
      /**
          Sets the `transitionActivated` attribute of the `LinkComponent`'s HTML element.
          @property transitionActivated
          @default false (no transition by default)
          @public
      **/
      transitionActivated:false,
      /**
          Sets the `routes` attribute of the `LinkComponent`'s HTML element.
          @property routes
          @default false (no transition by default)
          @public
      **/
      routes:[],
      /**
        @override
      **/
      didTransition: function() {
        console.log("npt - router didTransition");
        //Update local route history
        this.get("routes").push(this.get("url"));

        console.log(this.get("routes"));
        if(this.get("transitionActivated")){
          window.plugins.nativepagetransitions.executePendingTransition(
            function (msg) {console.log("success: " + msg);}, // called when the animation has finished
            function (msg) {alert("error: " + msg);} // called in case you pass in weird values
          );
        }
        this._super(...arguments);
      },
      /**
      Allow to transition back to the previous url
        @public
      **/
      back:function(){
        console.log("npt - router back");
        //Transition to the previous page

        //Remove the last two routes from the route history
        this.get("routes").pop();
      }
    });

}

export default {
  name: 'npt-link-component',
  initialize
};
<|endoftext|>


<commit_before>/*---------------------------------------------------------
 * OpenERP base_gantt
 *---------------------------------------------------------*/

openerp.base_gantt = function (openerp) {
QWeb.add_template('/base_gantt/static/src/xml/base_gantt.xml');
openerp.base.views.add('gantt', 'openerp.base_gantt.GanttView');
openerp.base_gantt.GanttView = openerp.base.Controller.extend({

init: function(view_manager, session, element_id, dataset, view_id) {

        this._super(session, element_id);
        this.view_manager = view_manager;
        this.dataset = dataset;
        this.model = dataset.model;
        this.view_id = view_id;
        this.fields_views = {};
        this.widgets = {};
        this.widgets_counter = 0;
        this.fields = this.dataset.fields ? this.dataset.fields: {};
        this.ids = this.dataset.ids;
        this.name = "";
        this.date_start = "";
        this.date_delay = "";
        this.date_stop = "";
        this.color_field = "";
        this.colors = [];
        this.color_values = [];
        this.calendar_fields = {};
        this.info_fields = [];
        this.domain = this.dataset._domain ? this.dataset._domain: [];
        this.context = {};
    },

    start: function() {
        this.rpc("/base_gantt/ganttview/load",
        {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },

    on_loaded: function(data) {

        var self = this;
        this.fields_view = data.fields_view;

        this.name =  this.fields_view.arch.attrs.string;
        this.view_id = this.fields_view.view_id;

        this.date_start = this.fields_view.arch.attrs.date_start;
        this.date_delay = this.fields_view.arch.attrs.date_delay;
        this.date_stop = this.fields_view.arch.attrs.date_stop;

        this.color_field = this.fields_view.arch.attrs.color;
        this.day_length = this.fields_view.arch.attrs.day_length || 8;
        this.colors = this.fields_view.arch.attrs.colors;

        this.text = this.fields_view.arch.children[0].children[0].attrs.name;
        this.parent = this.fields_view.arch.children[0].attrs.link;

        this.format = "yyyy-MM-dd";

        self.create_gantt();
        self.get_events();

        this.$element.html(QWeb.render("GanttView", {"view": this, "fields_view": this.fields_view}));

    },

    create_gantt: function() {

        ganttChartControl = new GanttChart(this.day_length);
        ganttChartControl.setImagePath("/base_gantt/static/lib/dhtmlxGantt/codebase/imgs/");
        ganttChartControl.setEditable(true);
        ganttChartControl.showTreePanel(true);
        ganttChartControl.showContextMenu(true);
        ganttChartControl.showDescTask(true,'d,s-f');
        ganttChartControl.showDescProject(true,'n,d');

    },

    get_events: function() {

        var self = this;
        this.dataset.read_ids(this.dataset.ids, {}, function(result) {
            self.load_event(result);
        });

    },

    load_event: function(events) {

        var self = this;
        var result = events;
        var smalldate = "";

        COLOR_PALETTE = ['#ccccff', '#cc99ff', '#75507b', '#3465a4', '#73d216', '#c17d11', '#edd400',
                 '#fcaf3e', '#ef2929', '#ff00c9', '#ad7fa8', '#729fcf', '#8ae234', '#e9b96e', '#fce94f',
                 '#ff8e00', '#ff0000', '#b0008c', '#9000ff', '#0078ff', '#00ff00', '#e6ff00', '#ffff00',
                 '#905000', '#9b0000', '#840067', '#510090', '#0000c9', '#009b00', '#9abe00', '#ffc900']

        if (result.length != 0){
            var show_event = [];
            for (i in result){
                var res = result[i];
                if (res[this.date_start] != false){

                    var start_date = this.convert_str_date(res[this.date_start]);
                    res[this.date_start] = start_date;
                    show_event.push(res);
                    if (smalldate == ""){
                        smalldate = start_date;
                    }
                    else{
                        if (start_date < smalldate){
                            smalldate = start_date;
                        }
                    }
                }
            }
        project = new GanttProjectInfo(1, self.name, smalldate);
        task = new GanttTaskInfo(111, "temp", smalldate, 1, 100, "", "red");
        project.addTask(task);
        ganttChartControl.addProject(project);
        }

        //create child
        var k = 0;
        var color_box = {};
        var parents = {};
        var all_events = {};
        var child_event = {};
        var temp_id = "";
        var final_events = [];
        for (i in show_event) {

            var res = show_event[i];

            var id = res['id'];
            var text = res[this.text];
            var start_date = res[this.date_start];

            var color = res[this.color_field][0] || res[this.color_field];
            if (color_box[color] == undefined){
                color_box[color] = COLOR_PALETTE[k];
                k = k + 1;
            }

            if (this.date_stop != undefined){
                if (res[this.date_stop] != false){
                    var stop_date = this.convert_str_date(res[this.date_stop]);
                    var duration= self.hours_between(start_date, stop_date);
                }
                else{
                    var duration = 0;
                }
            }
            else{
                var duration = res[this.date_delay];
            }
            if (duration == false)
                duration = 0

            if (self.grp != undefined){
                for (j in self.grp){
                    var grp_key = res[self.grp[j]['group_by']];

                    if (typeof(grp_key) == "object"){
                        grp_key = res[self.grp[j]['group_by']][1];
                    }
                    else{
                        grp_key = res[self.grp[j]['group_by']];
                    }

                    if (grp_key == false){
                        grp_key = "False";
                    }

                    if (j == 0){
                        if (parents[grp_key] == undefined){
                            var mod_id = i+ "_" +j;
                            parents[grp_key] = mod_id;
                            child_event[mod_id] = {};
                            all_events[mod_id] = {'parent': "", 'evt':[mod_id , grp_key, start_date, start_date, 100, "", "white"]};
                        }
                        else{
                            mod_id = parents[grp_key];
                        }
                        temp_id = mod_id;
                    }else{
                        if (child_event[mod_id][grp_key] == undefined){
                            var ch_mod_id = i+ "_" +j;
                            child_event[mod_id][grp_key] = ch_mod_id;
                            child_event[ch_mod_id] = {};
                            temp_id = ch_mod_id;
                            all_events[ch_mod_id] = {'parent': mod_id, 'evt':[ch_mod_id , grp_key, start_date, start_date, 100, "","white"]};
                            mod_id = ch_mod_id;
                        }
                        else{
                            mod_id = child_event[mod_id][grp_key];
                            temp_id = mod_id;
                        }
                    }
                }
                all_events[id] = {'parent': temp_id, 'evt':[id , text, start_date, duration, 100, "", color_box[color]]};
                final_events.push(id);
            }
        }

        ganttChartControl.create("GanttDiv");
        ganttChartControl.attachEvent("onTaskStartDrag", function(task) {self.on_drag_start(task);});
        ganttChartControl.attachEvent("onTaskEndResize", function(task) {self.on_resize_drag_end(task, "resize");});
        ganttChartControl.attachEvent("onTaskEndDrag", function(task) {self.on_resize_drag_end(task, "drag");});
        ganttChartControl.attachEvent("onTaskDblClick", function(task) {self.open_popup(task);});

        project = ganttChartControl.getProjectById(1);
        project.deleteTask(111);

        for (i in final_events){
            var evt_id = final_events[i];
            var evt_date = all_events[evt_id]['evt'][2];
            while (all_events[evt_id]['parent'] != "") {
               var parent_id =all_events[evt_id]['parent'];
               if (all_events[parent_id]['evt'][2] > evt_date){
                    all_events[parent_id]['evt'][2] = evt_date;
               }
               evt_id = parent_id;
            }
        }
        var evt_id = [];
        var evt_date = "";
        var evt_duration = "";
        var evt_end_date = "";

        for (i in final_events){
            evt_id = final_events[i];
            evt_date = all_events[evt_id]['evt'][2];
            evt_duration = all_events[evt_id]['evt'][3];

            evt_str_date = this.convert_date_str(evt_date);
            evt_end_date = this.end_date(evt_str_date, evt_duration);

            while (all_events[evt_id]['parent'] != "") {
               var parent_id =all_events[evt_id]['parent'];
               if (all_events[parent_id]['evt'][3] < evt_end_date){
                    all_events[parent_id]['evt'][3] = evt_end_date;
               }
               evt_id = parent_id;
            }
        }

        for (i in all_events){
            res = all_events[i];

            if ((typeof(res['evt'][3])) == "object"){
                res['evt'][3] = self.hours_between(res['evt'][2],res['evt'][3]);
            }

            project.insertTask(res['evt'][0], res['evt'][1], res['evt'][2], res['evt'][3], 100, "",res['evt'][6], res['parent']);
        }
    },

    end_date: function(dat, duration) {

         var self = this;

         dat = this.convert_str_date(dat);

         var day = Math.floor(duration/self.day_length);
         var hrs = duration % self.day_length;

         dat.add(day).days();
         dat.add(hrs).hour();

         return dat;
    },

    hours_between: function(date1, date2) {

        var ONE_DAY = 1000 * 60 * 60 * 24;
        var date1_ms = date1.getTime();
        var date2_ms = date2.getTime();
        var difference_ms = Math.abs(date1_ms - date2_ms);

        d = Math.round(difference_ms / ONE_DAY);
        h = Math.round((difference_ms % ONE_DAY)/(1000 * 60 * 60));

        return (d * this.day_length) + h;

    },

    open_popup : function(task) {
        var event_id = task.getId();
        if (event_id) {
            event_id = parseInt(event_id, 10);
            var dataset_event_index = jQuery.inArray(event_id, this.ids);
        } else  {
            var dataset_event_index = null;
        }
        this.dataset.index = dataset_event_index;
        var element_id = _.uniqueId("act_window_dialog");
        var dialog = jQuery('<div>',
                        {'id': element_id
                    }).dialog({
                        title: 'Gantt Chart',
                        modal: true,
                        minWidth: 800,
                        position: 'top'
                    });
        var event_form = new openerp.base.FormView(this.view_manager, this.session, element_id, this.dataset, false);
        event_form.start();
    },

    on_drag_start : function(task){
        st_date = task.getEST();
        if(st_date.getHours()){
            self.hh = st_date.getHours();
            self.mm = st_date.getMinutes();
        }
    },

    on_resize_drag_end : function(task, evt){

        var event_id = task.getId();
        var data = {};

        if (evt == "drag"){
            full_date = task.getEST().set({hour: self.hh, minute : self.mm, second:0});
            data[this.date_start] = this.convert_date_str(full_date);
        }
        if (this.date_stop != undefined){
            tm = (task.getDuration() % this.day_length);
            stp = task.getFinishDate().add(tm).hour();
            data[this.date_stop] = this.convert_date_str(stp);
        }else{
            data[this.date_delay] = task.getDuration();
        }
        this.dataset.write(event_id, data, function(result) {});

    },

    do_show: function () {
        this.$element.show();
    },

    do_hide: function () {
        this.$element.hide();
    },

    convert_str_date: function (str){
        if (str.length == 19){
            this.format = "yyyy-MM-dd HH:mm:ss";
            return openerp.base.parse_datetime(str);
        } else if (str.length == 10){
            this.format = "yyyy-MM-dd";
            return openerp.base.parse_date(str);
        } else if (str.length == 8){
            this.format = "HH:mm:ss";
            return openerp.base.parse_time(str);
        }
        throw "Unrecognized date/time format";
    },

    convert_date_str: function(full_date) {
        if (this.format == "yyyy-MM-dd HH:mm:ss"){
            return openerp.base.format_datetime(full_date);
        } else if (this.format == "yyyy-MM-dd"){
            return openerp.base.format_date(full_date);
        } else if (this.format == "HH:mm:ss"){
            return openerp.base.format_time(full_date);
        }
        throw "Unrecognized date/time format";
    },

    reload_gantt: function() {
        var self = this;
        var ajax = {
                url: '/base/dataset/search_read',
                async: false
            };
            this.rpc(ajax, {
                model: this.dataset.model,
                domain: self.dataset.domain,
                context :self.dataset.context
            }, function(response) {
                ganttChartControl.clearAll();
                jQuery("#GanttDiv").children().remove();
                self.load_event(response);
            });
    },

    do_search: function (domains, contexts, groupbys) {

        var self = this;
        this.grp = groupbys;
        return this.rpc('/base/session/eval_domain_and_context', {
            domains: domains,
            contexts: contexts,
            group_by_seq: groupbys
        }, function (results) {
            self.dataset.context = results.context;
            self.dataset.domain = results.domain;
            return self.reload_gantt();
        });
    }

});

// here you may tweak globals object, if any, and play with on_* or do_* callbacks on them

};
// vim:et fdc=0 fdl=0:
<commit_msg>[FIX] Set event hour when less then day_langth, use addChildTask instand of inseartTask.<commit_after>/*---------------------------------------------------------
 * OpenERP base_gantt
 *---------------------------------------------------------*/

openerp.base_gantt = function (openerp) {
QWeb.add_template('/base_gantt/static/src/xml/base_gantt.xml');
openerp.base.views.add('gantt', 'openerp.base_gantt.GanttView');
openerp.base_gantt.GanttView = openerp.base.Controller.extend({

init: function(view_manager, session, element_id, dataset, view_id) {

        this._super(session, element_id);
        this.view_manager = view_manager;
        this.dataset = dataset;
        this.model = dataset.model;
        this.view_id = view_id;
        this.fields_views = {};
        this.widgets = {};
        this.widgets_counter = 0;
        this.fields = this.dataset.fields ? this.dataset.fields: {};
        this.ids = this.dataset.ids;
        this.name = "";
        this.date_start = "";
        this.date_delay = "";
        this.date_stop = "";
        this.color_field = "";
        this.colors = [];
        this.color_values = [];
        this.calendar_fields = {};
        this.info_fields = [];
        this.domain = this.dataset._domain ? this.dataset._domain: [];
        this.context = {};
    },

    start: function() {
        this.rpc("/base_gantt/ganttview/load",
        {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },

    on_loaded: function(data) {

        var self = this;
        this.fields_view = data.fields_view;

        this.name =  this.fields_view.arch.attrs.string;
        this.view_id = this.fields_view.view_id;

        this.date_start = this.fields_view.arch.attrs.date_start;
        this.date_delay = this.fields_view.arch.attrs.date_delay;
        this.date_stop = this.fields_view.arch.attrs.date_stop;

        this.color_field = this.fields_view.arch.attrs.color;
        this.day_length = this.fields_view.arch.attrs.day_length || 8;
        this.colors = this.fields_view.arch.attrs.colors;

        this.text = this.fields_view.arch.children[0].children[0].attrs.name;
        this.parent = this.fields_view.arch.children[0].attrs.link;

        this.format = "yyyy-MM-dd";

        self.create_gantt();
        self.get_events();

        this.$element.html(QWeb.render("GanttView", {"view": this, "fields_view": this.fields_view}));

    },

    create_gantt: function() {

        ganttChartControl = new GanttChart(this.day_length);
        ganttChartControl.setImagePath("/base_gantt/static/lib/dhtmlxGantt/codebase/imgs/");
        ganttChartControl.setEditable(true);
        ganttChartControl.showTreePanel(true);
        ganttChartControl.showContextMenu(true);
        ganttChartControl.showDescTask(true,'d,s-f');
        ganttChartControl.showDescProject(true,'n,d');

    },

    get_events: function() {

        var self = this;
        this.dataset.read_ids(this.dataset.ids, {}, function(result) {
            self.load_event(result);
        });

    },

    load_event: function(events) {

        var self = this;
        var result = events;
        var smalldate = "";

        COLOR_PALETTE = ['#ccccff', '#cc99ff', '#75507b', '#3465a4', '#73d216', '#c17d11', '#edd400',
                 '#fcaf3e', '#ef2929', '#ff00c9', '#ad7fa8', '#729fcf', '#8ae234', '#e9b96e', '#fce94f',
                 '#ff8e00', '#ff0000', '#b0008c', '#9000ff', '#0078ff', '#00ff00', '#e6ff00', '#ffff00',
                 '#905000', '#9b0000', '#840067', '#510090', '#0000c9', '#009b00', '#9abe00', '#ffc900']

        if (result.length != 0){
            var show_event = [];
            for (i in result){
                var res = result[i];
                if (res[this.date_start] != false){

                    var start_date = this.convert_str_date(res[this.date_start]);
                    res[this.date_start] = start_date;
                    show_event.push(res);
                    if (smalldate == ""){
                        smalldate = start_date;
                    }
                    else{
                        if (start_date < smalldate){
                            smalldate = start_date;
                        }
                    }
                }
            }
        project = new GanttProjectInfo(1, self.name, smalldate);
        ganttChartControl.addProject(project);
        }

        //create child
        var k = 0;
        var color_box = {};
        var parents = {};
        var all_events = {};
        var child_event = {};
        var temp_id = "";
        var final_events = [];
        for (i in show_event) {

            var res = show_event[i];

            var id = res['id'];
            var text = res[this.text];
            var start_date = res[this.date_start];

            var color = res[this.color_field][0] || res[this.color_field];
            if (color_box[color] == undefined){
                color_box[color] = COLOR_PALETTE[k];
                k = k + 1;
            }

            if (this.date_stop != undefined){
                if (res[this.date_stop] != false){
                    var stop_date = this.convert_str_date(res[this.date_stop]);
                    var duration= self.hours_between(start_date, stop_date);
                }
                else{
                    var duration = 0;
                }
            }
            else{
                var duration = res[this.date_delay];
            }
            if (duration == false)
                duration = 0

            if (self.grp != undefined){
                for (j in self.grp){
                    var grp_key = res[self.grp[j]['group_by']];
                    if (typeof(grp_key) == "object"){
                        grp_key = res[self.grp[j]['group_by']][1];
                    }
                    else{
                        grp_key = res[self.grp[j]['group_by']];
                    }

                    if (grp_key == false){
                        grp_key = "False";
                    }

                    if (j == 0){
                        if (parents[grp_key] == undefined){
                            var mod_id = i+ "_" +j;
                            parents[grp_key] = mod_id;
                            child_event[mod_id] = {};
                            all_events[mod_id] = {'parent': "", 'evt':[mod_id , grp_key, start_date, start_date, 100, "", "white"]};
                        }
                        else{
                            mod_id = parents[grp_key];
                        }
                        temp_id = mod_id;
                    }else{
                        if (child_event[mod_id][grp_key] == undefined){
                            var ch_mod_id = i+ "_" +j;
                            child_event[mod_id][grp_key] = ch_mod_id;
                            child_event[ch_mod_id] = {};
                            temp_id = ch_mod_id;
                            all_events[ch_mod_id] = {'parent': mod_id, 'evt':[ch_mod_id , grp_key, start_date, start_date, 100, "","white"]};
                            mod_id = ch_mod_id;
                        }
                        else{
                            mod_id = child_event[mod_id][grp_key];
                            temp_id = mod_id;
                        }
                    }
                }
                all_events[id] = {'parent': temp_id, 'evt':[id , text, start_date, duration, 100, "", color_box[color]]};
                final_events.push(id);
            }
        }

        for (i in final_events){
            var evt_id = final_events[i];
            var evt_date = all_events[evt_id]['evt'][2];
            while (all_events[evt_id]['parent'] != "") {
               var parent_id =all_events[evt_id]['parent'];
               if (all_events[parent_id]['evt'][2] > evt_date){
                    all_events[parent_id]['evt'][2] = evt_date;
               }
               evt_id = parent_id;
            }
        }
        var evt_id = [];
        var evt_date = "";
        var evt_duration = "";
        var evt_end_date = "";

        for (i in final_events){
            evt_id = final_events[i];
            evt_date = all_events[evt_id]['evt'][2];
            evt_duration = all_events[evt_id]['evt'][3];

            evt_str_date = this.convert_date_str(evt_date);
            evt_end_date = this.end_date(evt_str_date, evt_duration);

            while (all_events[evt_id]['parent'] != "") {
               var parent_id =all_events[evt_id]['parent'];
               if (all_events[parent_id]['evt'][3] < evt_end_date){
                    all_events[parent_id]['evt'][3] = evt_end_date;
               }
               evt_id = parent_id;
            }
        }

        for (i in all_events){
            res = all_events[i];

            if ((typeof(res['evt'][3])) == "object"){
                res['evt'][3] = self.hours_between(res['evt'][2],res['evt'][3]);
            }

            if(res['parent'] == ""){
                task=new GanttTaskInfo(res['evt'][0], res['evt'][1], res['evt'][2], res['evt'][3], 100, "",res['evt'][6]);
                project.addTask(task);
            }else{
                task=new GanttTaskInfo(res['evt'][0], res['evt'][1], res['evt'][2], res['evt'][3], 100, "",res['evt'][6]);
                prt = project.getTaskById(res['parent']);
                prt.addChildTask(task);
            }

        }

        ganttChartControl.create("GanttDiv");
        ganttChartControl.attachEvent("onTaskStartDrag", function(task) {self.on_drag_start(task);});
        ganttChartControl.attachEvent("onTaskEndResize", function(task) {self.on_resize_drag_end(task, "resize");});
        ganttChartControl.attachEvent("onTaskEndDrag", function(task) {self.on_resize_drag_end(task, "drag");});
        ganttChartControl.attachEvent("onTaskDblClick", function(task) {self.open_popup(task);});

    },

    end_date: function(dat, duration) {

         var self = this;

         dat = this.convert_str_date(dat);

         var day = Math.floor(duration/self.day_length);
         var hrs = duration % self.day_length;

         dat.add(day).days();
         dat.add(hrs).hour();

         return dat;
    },

    hours_between: function(date1, date2) {

        var ONE_DAY = 1000 * 60 * 60 * 24;
        var date1_ms = date1.getTime();
        var date2_ms = date2.getTime();
        var difference_ms = Math.abs(date1_ms - date2_ms);

        d = Math.round(difference_ms / ONE_DAY);
        h = Math.round((difference_ms % ONE_DAY)/(1000 * 60 * 60));

        return (d * this.day_length) + h;

    },

    open_popup : function(task) {
        var event_id = task.getId();
        if (event_id) {
            event_id = parseInt(event_id, 10);
            var dataset_event_index = jQuery.inArray(event_id, this.ids);
        } else  {
            var dataset_event_index = null;
        }
        this.dataset.index = dataset_event_index;
        var element_id = _.uniqueId("act_window_dialog");
        var dialog = jQuery('<div>',
                        {'id': element_id
                    }).dialog({
                        title: 'Gantt Chart',
                        modal: true,
                        minWidth: 800,
                        position: 'top'
                    });
        var event_form = new openerp.base.FormView(this.view_manager, this.session, element_id, this.dataset, false);
        event_form.start();
    },

    on_drag_start : function(task){
        st_date = task.getEST();
        if(st_date.getHours()){
            self.hh = st_date.getHours();
            self.mm = st_date.getMinutes();
        }
    },

    on_resize_drag_end : function(task, evt){

        var event_id = task.getId();
        var data = {};

        if (evt == "drag"){
            full_date = task.getEST().set({hour: self.hh, minute : self.mm, second:0});
            data[this.date_start] = this.convert_date_str(full_date);
        }
        if (this.date_stop != undefined){
            tm = (task.getDuration() % this.day_length);
            stp = task.getFinishDate().add(tm).hour();
            data[this.date_stop] = this.convert_date_str(stp);
        }else{
            data[this.date_delay] = task.getDuration();
        }
        this.dataset.write(event_id, data, function(result) {});

    },

    do_show: function () {
        this.$element.show();
    },

    do_hide: function () {
        this.$element.hide();
    },

    convert_str_date: function (str){
        if (str.length == 19){
            this.format = "yyyy-MM-dd HH:mm:ss";
            return openerp.base.parse_datetime(str);
        } else if (str.length == 10){
            this.format = "yyyy-MM-dd";
            return openerp.base.parse_date(str);
        } else if (str.length == 8){
            this.format = "HH:mm:ss";
            return openerp.base.parse_time(str);
        }
        throw "Unrecognized date/time format";
    },

    convert_date_str: function(full_date) {
        if (this.format == "yyyy-MM-dd HH:mm:ss"){
            return openerp.base.format_datetime(full_date);
        } else if (this.format == "yyyy-MM-dd"){
            return openerp.base.format_date(full_date);
        } else if (this.format == "HH:mm:ss"){
            return openerp.base.format_time(full_date);
        }
        throw "Unrecognized date/time format";
    },

    reload_gantt: function() {
        var self = this;
        var ajax = {
                url: '/base/dataset/search_read',
                async: false
            };
            this.rpc(ajax, {
                model: this.dataset.model,
                domain: self.dataset.domain,
                context :self.dataset.context
            }, function(response) {
                ganttChartControl.clearAll();
                jQuery("#GanttDiv").children().remove();
                self.load_event(response);
            });
    },

    do_search: function (domains, contexts, groupbys) {

        var self = this;
        this.grp = groupbys;
        return this.rpc('/base/session/eval_domain_and_context', {
            domains: domains,
            contexts: contexts,
            group_by_seq: groupbys
        }, function (results) {
            self.dataset.context = results.context;
            self.dataset.domain = results.domain;
            return self.reload_gantt();
        });
    }

});

// here you may tweak globals object, if any, and play with on_* or do_* callbacks on them

};
// vim:et fdc=0 fdl=0:
<|endoftext|>


<commit_before>/*---------------------------------------------------------
 * OpenERP base_graph
 *---------------------------------------------------------*/

openerp.base_graph = function (openerp) {
QWeb.add_template('/base_graph/static/src/xml/base_graph.xml');
openerp.base.views.add('graph', 'openerp.base_graph.GraphView');
openerp.base_graph.GraphView = openerp.base.Controller.extend({

	init: function(view_manager, session, element_id, dataset, view_id) {

        this._super(session, element_id);
        this.view_manager = view_manager;
        this.dataset = dataset;
        this.model = this.dataset.model;
        this.view_id = view_id;
    },
    do_show: function () {
        // TODO: re-trigger search
        this.$element.show();
    },
    do_hide: function () {
        this.$element.hide();
    },
    start: function() {
        this.rpc("/base_graph/graphview/load", {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },
    on_loaded: function(data) {
        var self = this;
        this.fields_view = data.fields_view;
        this.name = this.fields_view.name || this.fields_view.arch.attrs.string;
        this.view_id = this.fields_view.view_id;
        this.chart = this.fields_view.arch.attrs.type || 'pie';
        this.fields = this.fields_view.fields;
        this.chart_info_fields = [];
        this.operator_field = '';
        this.group_field = '';
        this.orientation = this.fields_view.arch.attrs.orientation || '';

        for(fld in this.fields_view.arch.children) {
            if (this.fields_view.arch.children[fld].attrs.operator) {
                this.operator_field = this.fields_view.arch.children[fld].attrs.name;
            }
            else if (this.fields_view.arch.children[fld].attrs.group) {
                this.group_field = this.fields_view.arch.children[fld].attrs.name;
            }
            else {
                this.chart_info_fields.push(this.fields_view.arch.children[fld].attrs.name);
            }
        }
        if(this.operator_field == ''){
            this.operator_field = this.chart_info_fields[1];
        }
        this.chart_info = this.chart_info_fields[0];
        this.load_chart();
    },

    load_chart: function(result) {
        var self = this;
        if(result){
            self.schedule_chart(result);
        }else{
            this.dataset.read_ids(
                this.dataset.ids,
                {},
                function(result) {
                    self.schedule_chart(result);
                }
            )
        }
    },

    schedule_chart: function(result) {
        this.$element.html(QWeb.render("GraphView", {"fields_view": this.fields_view, "chart": this.chart}));

        if (result.length){
            for(res in result) {
                for(fld in result[res]) {
                    if (typeof result[res][fld] == 'object') {
                        result[res][fld] = result[res][fld][result[res][fld].length - 1];
                    }
                }
            }

            if(this.chart == 'bar') {
                return this.schedule_bar(result);
            } else if(this.chart == "pie") {
                return this.schedule_pie(result);
            }
        }
    },

    schedule_bar: function(result) {
        var self = this;
        var view_chart = '';
        var xystr = {};
        var xyname = {};
        var res = [];
        var group_list = [];
        var opration_fld = {};

        for (i in result){
            var gen_key = result[i][self.chart_info_fields]+"_"+result[i][self.group_field]
            if (opration_fld[gen_key] == undefined){
                var map_val = {}
                map_val[self.operator_field] = result[i][self.operator_field];
                map_val[self.chart_info_fields] = result[i][self.chart_info_fields];
                if (this.group_field){
                    map_val[self.group_field] = result[i][self.group_field].replace(" ", "_");
                }else{
                    map_val[self.group_field] = result[i][self.group_field];
                }
                opration_fld[gen_key] = map_val;
            }else{
                map_val = opration_fld[gen_key];
                map_val[self.operator_field] = map_val[self.operator_field] + result[i][self.operator_field];
                opration_fld[gen_key] = map_val;
            }
        }

        result = []
        for (i in opration_fld){
            result.push(opration_fld[i]);
        }

        var COLOR_PALETTE = ['#ff8e00', '#ff0000', '#b0008c', '#9000ff', '#0078ff', '#00ff00', '#e6ff00', '#ffff00',
                     '#905000', '#9b0000', '#840067', '#9abe00', '#ffc900', '#510090', '#0000c9', '#009b00',
                     '#75507b', '#3465a4', '#73d216', '#c17d11', '#edd400', '#fcaf3e', '#ef2929', '#ff00c9',
                     '#ad7fa8', '#729fcf', '#8ae234', '#e9b96e', '#fce94f', '#f57900', '#cc0000', '#d400a8'];

        if(this.group_field){
            view_chart = this.orientation == 'horizontal'? 'stackedBarH' : 'stackedBar';
        }else{
            view_chart = this.orientation == 'horizontal'? 'barH' : 'bar';
        }

        for (i in result){
            if (this.group_field){
                var newkey =result[i][this.group_field].replace(" ", "_");
            }else{
                var newkey =result[i][this.group_field];
            }
            if (jQuery.inArray(newkey, group_list) == -1){
                group_list.push(newkey);
            }
        }

        for (i in result){
            var xystring = result[i][this.chart_info_fields];
             if (this.group_field){
                var newkey =result[i][this.group_field].replace(" ", "_");
            }else{
                var newkey =result[i][this.group_field];
            }
            if (xystr[xystring] == undefined){
                xyname = {};
                xyname['name'] = xystring;
                for (j in group_list){
                    xyname[group_list[j]] = 0.0001;
                }
                xyname[newkey] = result[i][this.operator_field];
                xystr[xystring] = xyname;
            }
            else{
                xyname = {};
                xyname = xystr[xystring];
                xyname[newkey] = result[i][this.operator_field];
                xystr[xystring] = xyname;
            }
        }

        for (i in xystr){
            res.push(xystr[i]);
        }

        //for legend color
        var grp_color = [];
        for (i in group_list){
            var legend = {};
            if (group_list[i] == undefined){
                legend['text'] = self.fields[self.operator_field]['string']
            }else{
                legend['text'] = group_list[i];
            }
            legend['color'] = COLOR_PALETTE[i];
            grp_color.push(legend);
        }

        var temp_ax = {};
        var oth_ax = {};

        temp_ax['template'] = "#name#";
        temp_ax['lines'] = true;

        oth_ax['lines'] = true;

        if (this.orientation == 'horizontal'){
             var x_ax = oth_ax;
             var y_ax = temp_ax;
        }else{
             var x_ax = temp_ax;
             var y_ax = oth_ax;
        }

        var bar_chart = new dhtmlxchartChart({
            view: view_chart,
            container: "barchart",
            value:"#"+group_list[0]+"#",
            gradient: "3d",
            border: false,
            width: 30,
            color:grp_color[0]['color'],
            origin:0,
            xAxis: x_ax,
            yAxis: y_ax,
            legend: {
                values: grp_color,
                align:"right",
                valign:"top",
                marker:{
                    type:"round",
                    width:12
                },
            }
        });
        for (var i = 1; i<group_list.length;i++){
            bar_chart.addSeries({
                value: "#"+grp_color[i]['text']+"#",
                color: grp_color[i]['color']
            });
        }
        bar_chart.parse(res,"json");

    },

    schedule_pie: function(result) {
        var chart =  new dhtmlxchartChart({
            view:"pie",
            container:"piechart",
            value:"#"+this.operator_field+"#",
            color:"#d2ed7e",
            label:"#"+this.chart_info_fields[0]+"#",
            pieInnerText:"#"+this.operator_field+"#",
            gradient:"3d",
            legend: {
                width: 100,
                align:"right",
                valign:"top",
                marker:{
                    type:"round",
                    width:12
                },
                template:"#"+this.chart_info_fields[0]+"#"
            }
        });
        chart.parse(result,"json");
    },

    do_search: function(domains, contexts, groupbys) {
        var self = this;

        this.rpc('/base/session/eval_domain_and_context', {
            domains: domains,
            contexts: contexts,
            group_by_seq: groupbys
        }, function (results) {
            // TODO: handle non-empty results.group_by with read_group
            if(contexts[0]['group_by']){
                self.chart_info_fields = contexts[0]['group_by'];
            }
            else{
                self.chart_info_fields = self.chart_info;
            }
            self.dataset.context = self.context = results.context;
            self.dataset.domain = self.domain = results.domain;
            self.dataset.read_slice(self.fields, 0, self.limit,function(result){
                self.load_chart(result);
            });
        });

    },

});

// here you may tweak globals object, if any, and play with on_* or do_* callbacks on them

};

// vim:et fdc=0 fdl=0:
<commit_msg>[IMP]code for piechart with default color and improved code for groupby.<commit_after>/*---------------------------------------------------------
 * OpenERP base_graph
 *---------------------------------------------------------*/

openerp.base_graph = function (openerp) {
QWeb.add_template('/base_graph/static/src/xml/base_graph.xml');
openerp.base.views.add('graph', 'openerp.base_graph.GraphView');
openerp.base_graph.GraphView = openerp.base.Controller.extend({

	init: function(view_manager, session, element_id, dataset, view_id) {

        this._super(session, element_id);
        this.view_manager = view_manager;
        this.dataset = dataset;
        this.model = this.dataset.model;
        this.view_id = view_id;
    },
    do_show: function () {
        // TODO: re-trigger search
        this.$element.show();
    },
    do_hide: function () {
        this.$element.hide();
    },
    start: function() {
        this.rpc("/base_graph/graphview/load", {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },
    on_loaded: function(data) {
        var self = this;
        this.fields_view = data.fields_view;
        this.name = this.fields_view.name || this.fields_view.arch.attrs.string;
        this.view_id = this.fields_view.view_id;
        this.chart = this.fields_view.arch.attrs.type || 'pie';
        this.fields = this.fields_view.fields;
        this.chart_info_fields = [];
        this.operator_field = '';
        this.group_field = '';
        this.orientation = this.fields_view.arch.attrs.orientation || '';

        for(fld in this.fields_view.arch.children) {
            if (this.fields_view.arch.children[fld].attrs.operator) {
                this.operator_field = this.fields_view.arch.children[fld].attrs.name;
            }
            else if (this.fields_view.arch.children[fld].attrs.group) {
                this.group_field = this.fields_view.arch.children[fld].attrs.name;
            }
            else {
                this.chart_info_fields.push(this.fields_view.arch.children[fld].attrs.name);
            }
        }
        if(this.operator_field == ''){
            this.operator_field = this.chart_info_fields[1];
        }
        this.chart_info = this.chart_info_fields[0];
        this.load_chart();
    },

    load_chart: function(result) {
        var self = this;
        if(result){
            self.schedule_chart(result);
        }else{
            this.dataset.read_ids(
                this.dataset.ids,
                {},
                function(result) {
                    self.schedule_chart(result);
                }
            )
        }
    },

    schedule_chart: function(result) {
        this.$element.html(QWeb.render("GraphView", {"fields_view": this.fields_view, "chart": this.chart}));
        this.opration_fld = {};
        this.group_list = [];

        if (result.length){
            for(res in result) {
                for(fld in result[res]) {
                    if (typeof result[res][fld] == 'object') {
                        result[res][fld] = result[res][fld][result[res][fld].length - 1];
                    }
                }
            }

            for (i in result){
                var gen_key = result[i][this.chart_info_fields]+"_"+result[i][this.group_field]
                if (this.opration_fld[gen_key] == undefined){
                    var map_val = {}
                    map_val[this.operator_field] = result[i][this.operator_field];
                    map_val[this.chart_info_fields] = result[i][this.chart_info_fields];
                    if (this.group_field){
                        map_val[this.group_field] = result[i][this.group_field].replace(" ", "_");
                    }else{
                        map_val[this.group_field] = result[i][this.group_field];
                    }
                    this.opration_fld[gen_key] = map_val;
                }else{
                    map_val = this.opration_fld[gen_key];
                    map_val[this.operator_field] = map_val[this.operator_field] + result[i][this.operator_field];
                    this.opration_fld[gen_key] = map_val;
                }
            }

            result = []
            for (i in this.opration_fld){
                result.push(this.opration_fld[i]);
            }

            if(this.chart == 'bar') {
                return this.schedule_bar(result);
            } else if(this.chart == "pie") {
                console.log("test");
                return this.schedule_pie(result);
            }
        }
    },

    schedule_bar: function(result) {
        var self = this;
        var view_chart = '';
        var xystr = {};
        var xyname = {};
        var res = [];

        var COLOR_PALETTE = ['#ff8e00', '#ff0000', '#b0008c', '#9000ff', '#0078ff', '#00ff00', '#e6ff00', '#ffff00',
                     '#905000', '#9b0000', '#840067', '#9abe00', '#ffc900', '#510090', '#0000c9', '#009b00',
                     '#75507b', '#3465a4', '#73d216', '#c17d11', '#edd400', '#fcaf3e', '#ef2929', '#ff00c9',
                     '#ad7fa8', '#729fcf', '#8ae234', '#e9b96e', '#fce94f', '#f57900', '#cc0000', '#d400a8'];

        if(self.group_field){
            view_chart = self.orientation == 'horizontal'? 'stackedBarH' : 'stackedBar';
        }else{
            view_chart = self.orientation == 'horizontal'? 'barH' : 'bar';
        }

        for (i in result){
            if (self.group_field){
                var newkey =result[i][self.group_field].replace(" ", "_");
            }else{
                var newkey =result[i][self.group_field];
            }
            if (jQuery.inArray(newkey, self.group_list) == -1){
                self.group_list.push(newkey);
            }
        }

        for (i in result){
            var xystring = result[i][self.chart_info_fields];
            if (self.group_field){
                var newkey =result[i][self.group_field].replace(" ", "_");
            }else{
                var newkey =result[i][self.group_field];
            }
            if (xystr[xystring] == undefined){
                xyname = {};
                xyname['name'] = xystring;
                for (j in self.group_list){
                    xyname[self.group_list[j]] = 0.0001;
                }
                xyname[newkey] = result[i][self.operator_field];
                xystr[xystring] = xyname;
            }
            else{
                xyname = {};
                xyname = xystr[xystring];
                xyname[newkey] = result[i][self.operator_field];
                xystr[xystring] = xyname;
            }
        }

        for (i in xystr){
            res.push(xystr[i]);
        }

        //for legend color
        var grp_color = [];
        for (i in self.group_list){
            var legend = {};
            if (self.group_list[i] == undefined){
                legend['text'] = self.fields[self.operator_field]['string']
            }else{
                legend['text'] = self.group_list[i];
            }
            legend['color'] = COLOR_PALETTE[i];
            grp_color.push(legend);
        }

        var temp_ax = {};
        var oth_ax = {};

        temp_ax['template'] = "#name#";
        oth_ax['lines'] = true;

        if (self.orientation == 'horizontal'){
             var x_ax = oth_ax;
             var y_ax = temp_ax;
        }else{
             var x_ax = temp_ax;
             var y_ax = oth_ax;
        }

        var bar_chart = new dhtmlxchartChart({
            view: view_chart,
            container: "barchart",
            value:"#"+self.group_list[0]+"#",
            gradient: "3d",
            border: false,
            width: 50,
            color:grp_color[0]['color'],
            origin:0,
            xAxis: x_ax,
            yAxis: y_ax,
            legend: {
                values: grp_color,
                align:"right",
                valign:"top",
                marker:{
                    type:"round",
                    width:12
                },
            }
        });
        for (var i = 1; i<self.group_list.length;i++){
            bar_chart.addSeries({
                value: "#"+grp_color[i]['text']+"#",
                color: grp_color[i]['color']
            });
        }
        bar_chart.parse(res,"json");

    },

    schedule_pie: function(result) {
        var self = this;

        var chart =  new dhtmlxchartChart({
            view:"pie3D",
            container:"piechart",
            value:"#"+self.operator_field+"#",
            pieInnerText:function(obj) {
                var sum = chart.sum("#"+self.operator_field+"#");
                var val = obj[self.operator_field] / sum * 100 ;
                return Math.round(val * 10)/10 + "%";
            },
            label:"#"+self.chart_info_fields[0]+"#",
            gradient:"3d",
            legend: {
                width: 300,
                align:"right",
                valign:"top",
                marker:{
                    type:"round",
                    width:12
                },
                template:"#"+self.chart_info_fields[0]+"#"
            }
        });
        chart.parse(result,"json");
    },

    do_search: function(domains, contexts, groupbys) {
        var self = this;

        this.rpc('/base/session/eval_domain_and_context', {
            domains: domains,
            contexts: contexts,
            group_by_seq: groupbys
        }, function (results) {
            // TODO: handle non-empty results.group_by with read_group
            if(contexts[0]['group_by'] && contexts[0]['group_by'] != ''){
                self.chart_info_fields[0] = contexts[0]['group_by'];
            }
            else{
                self.chart_info_fields[0] = self.chart_info;
            }
            self.dataset.context = self.context = results.context;
            self.dataset.domain = self.domain = results.domain;
            self.dataset.read_slice({}, 0, self.limit,function(result){
                self.load_chart(result);
            });
        });

    },

});

// here you may tweak globals object, if any, and play with on_* or do_* callbacks on them

};

// vim:et fdc=0 fdl=0:
<|endoftext|>