<commit_before>/*
 * grunt-symfony2
 * https://github.com/florianeckerstorfer/grunt-symfony2
 *
 * Copyright (c) 2014 Florian Eckerstorfer
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

    var exec = require('child_process').exec,
        execCmd = function (cmd, cb, execOpts) {
            grunt.verbose.writeln('Exec: ' + cmd);
            exec(cmd, execOpts, function (err, stdout, stderr) {
                grunt.verbose.writeln(stdout);
                if (stderr) {
                    grunt.fatal(stderr);
                }
                if (err && 127 === err.code) {
                    grunt.warn('Could not execute app/console.');
                }
                cb();
            });
        },
        prepareCmd = function (cmd, args, argOptions, options, target, done) {
            var bin = options.bin || 'app/console',
                execOpts = {},
                arg;

            if (options.cwd) {
                execOpts.cwd = options.cwd;
            }

            if (!argOptions.env && ('prod' === target || 'dev' === target || 'staging' === target)) {
                argOptions.env = target;
            }

            for (arg in args) {
                if (args.hasOwnProperty(arg)) {
                    cmd += ' ' + args[arg];
                }
            }

            for (arg in argOptions) {
                if (argOptions.hasOwnProperty(arg)) {
                    cmd += ' --' + arg;
                    if (argOptions[arg] && true !== argOptions[arg]) {
                        cmd += '=' + argOptions[arg];
                    }
                }
            }
            execCmd('php ' + bin + ' ' + cmd, done, execOpts);
        };

    grunt.registerMultiTask('sf2-console', 'Grunt task for running Symfony2 commands.', function () {
        var cmd = this.data.cmd || '',
            args = {},
            argOptions = this.data.args || {},
            options = this.options(),
            target = this.target || '';

        prepareCmd(cmd, args, argOptions, options, target, this.async());
    });

    grunt.registerMultiTask('sf2-cache-clear', 'Grunt task for running Symfony2 cache:clear commands.', function () {
        var args = {},
            argOptions = this.data.args || {},
            options = this.options(),
            target = this.target || '';

        prepareCmd('cache:clear', args, argOptions, options, target, this.async());
    });

    grunt.registerMultiTask('sf2-cache-warmup', 'Grunt task for running Symfony2 cache:warmup commands', function () {
        var args = {},
            argOptions = this.data.args || {},
            options = this.options(),
            target = this.target || '';

        prepareCmd('cache:warmup', args, argOptions, options, target, this.async());
    });

    grunt.registerMultiTask('sf2-assetic-dump', 'Grunt task for running Symfony2 assetic:dump commands.', function () {
        var args = {},
            argOptions = this.data.args || {},
            options = this.options(),
            target = this.target || '';

        prepareCmd('assetic:dump', args, argOptions, options, target, this.async());
    });

    grunt.registerMultiTask(
        'sf2-assets-install',
        'Grunt task for running Symfony2 assets:install commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('assets:install', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask('sf2-twig-lint', 'Grunt task for running Symfony2 twig:linkt commands.', function () {
        var args = {},
            argOptions = this.data.args || {},
            options = this.options(),
            target = this.target || '';

        prepareCmd('twig:lint', args, argOptions, options, target, this.async());
    });

    grunt.registerMultiTask(
        'sf2-translation-update',
        'Grunt task for running Symfony2 translation:update commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('translation:update', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-orm-convert-mapping',
        'Grunt task for running Symfony2 orm:convert:mapping commands.',
        function () {
            var args = { 'to-type': this.data['to-type'], 'dest-path': this.data['dest-path'] },
                argOptions = this.data.argOptions || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('orm:convert:mapping', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-cache-clear-metadata',
        'Grunt task for running Symfony2 doctrine:cache:clear-metadata commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:cache:clear-metadata', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-cache-clear-query',
        'Grunt task for running Symfony2 doctrine:cache:query commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:cache:clear-query', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-cache-clear-result',
        'Grunt task for running Symfony2 doctrine:cache:result commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:cache:clear-result', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-database-create',
        'Grunt task for running Symfony2 doctrine:database:create commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:database:create', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-database-drop',
        'Grunt task for running Symfony2 doctrine:database:drop commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:database:drop', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-ensure-production-settings',
        'Grunt task for running Symfony2 doctrine:ensure-production-settings commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:ensure-production-settings', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-fixtures-load',
        'Grunt task for running Symfony2 doctrine:fixtures:load commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:fixtures:load', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-schema-create',
        'Grunt task for running Symfony2 doctrine:schema:create commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:schema:create', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-schema-drop',
        'Grunt task for running Symfony2 doctrine:schema:drop commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:schema:drop', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-schema-update',
        'Grunt task for running Symfony2 doctrine:schema:update commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:schema:update', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-schema-validate',
        'Grunt task for running Symfony2 doctrine:schema:validate commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:schema:validate', args, argOptions, options, target, this.async());
        }
    );

};
<commit_msg>Added support for arguments in additional tasks<commit_after>/*
 * grunt-symfony2
 * https://github.com/florianeckerstorfer/grunt-symfony2
 *
 * Copyright (c) 2014 Florian Eckerstorfer
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

    var exec = require('child_process').exec,
        execCmd = function (cmd, cb, execOpts) {
            grunt.verbose.writeln('Exec: ' + cmd);
            exec(cmd, execOpts, function (err, stdout, stderr) {
                grunt.verbose.writeln(stdout);
                if (stderr) {
                    grunt.fatal(stderr);
                }
                if (err && 127 === err.code) {
                    grunt.warn('Could not execute app/console.');
                }
                cb();
            });
        },
        prepareCmd = function (cmd, args, argOptions, options, target, done) {
            var bin = options.bin || 'app/console',
                execOpts = {},
                arg;

            if (options.cwd) {
                execOpts.cwd = options.cwd;
            }

            if (!argOptions.env && ('prod' === target || 'dev' === target || 'staging' === target)) {
                argOptions.env = target;
            }

            for (arg in args) {
                if (args.hasOwnProperty(arg)) {
                    cmd += ' ' + args[arg];
                }
            }

            for (arg in argOptions) {
                if (argOptions.hasOwnProperty(arg)) {
                    cmd += ' --' + arg;
                    if (argOptions[arg] && true !== argOptions[arg]) {
                        cmd += '=' + argOptions[arg];
                    }
                }
            }
            execCmd('php ' + bin + ' ' + cmd, done, execOpts);
        };

    grunt.registerMultiTask('sf2-console', 'Grunt task for running Symfony2 commands.', function () {
        var cmd = this.data.cmd || '',
            args = {},
            argOptions = this.data.args || {},
            options = this.options(),
            target = this.target || '';

        prepareCmd(cmd, args, argOptions, options, target, this.async());
    });

    grunt.registerMultiTask('sf2-cache-clear', 'Grunt task for running Symfony2 cache:clear commands.', function () {
        var args = {},
            argOptions = this.data.args || {},
            options = this.options(),
            target = this.target || '';

        prepareCmd('cache:clear', args, argOptions, options, target, this.async());
    });

    grunt.registerMultiTask('sf2-cache-warmup', 'Grunt task for running Symfony2 cache:warmup commands', function () {
        var args = {},
            argOptions = this.data.args || {},
            options = this.options(),
            target = this.target || '';

        prepareCmd('cache:warmup', args, argOptions, options, target, this.async());
    });

    grunt.registerMultiTask('sf2-assetic-dump', 'Grunt task for running Symfony2 assetic:dump commands.', function () {
        var args = { write_to: this.data.write_to || '' },
            argOptions = this.data.args || {},
            options = this.options(),
            target = this.target || '';

        prepareCmd('assetic:dump', args, argOptions, options, target, this.async());
    });

    grunt.registerMultiTask(
        'sf2-assets-install',
        'Grunt task for running Symfony2 assets:install commands.',
        function () {
            var args = { target: this.data.target || '' },
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('assets:install', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask('sf2-twig-lint', 'Grunt task for running Symfony2 twig:linkt commands.', function () {
        var args = { filename: this.data.filename || '' },
            argOptions = this.data.args || {},
            options = this.options(),
            target = this.target || '';

        prepareCmd('twig:lint', args, argOptions, options, target, this.async());
    });

    grunt.registerMultiTask(
        'sf2-translation-update',
        'Grunt task for running Symfony2 translation:update commands.',
        function () {
            var args = { locale: this.data.locale, bundle: this.data.bundle },
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('translation:update', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-orm-convert-mapping',
        'Grunt task for running Symfony2 orm:convert:mapping commands.',
        function () {
            var args = { 'to-type': this.data['to-type'], 'dest-path': this.data['dest-path'] },
                argOptions = this.data.argOptions || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('orm:convert:mapping', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-cache-clear-metadata',
        'Grunt task for running Symfony2 doctrine:cache:clear-metadata commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:cache:clear-metadata', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-cache-clear-query',
        'Grunt task for running Symfony2 doctrine:cache:query commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:cache:clear-query', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-cache-clear-result',
        'Grunt task for running Symfony2 doctrine:cache:result commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:cache:clear-result', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-database-create',
        'Grunt task for running Symfony2 doctrine:database:create commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:database:create', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-database-drop',
        'Grunt task for running Symfony2 doctrine:database:drop commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:database:drop', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-ensure-production-settings',
        'Grunt task for running Symfony2 doctrine:ensure-production-settings commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:ensure-production-settings', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-fixtures-load',
        'Grunt task for running Symfony2 doctrine:fixtures:load commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:fixtures:load', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-schema-create',
        'Grunt task for running Symfony2 doctrine:schema:create commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:schema:create', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-schema-drop',
        'Grunt task for running Symfony2 doctrine:schema:drop commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:schema:drop', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-schema-update',
        'Grunt task for running Symfony2 doctrine:schema:update commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:schema:update', args, argOptions, options, target, this.async());
        }
    );

    grunt.registerMultiTask(
        'sf2-doctrine-schema-validate',
        'Grunt task for running Symfony2 doctrine:schema:validate commands.',
        function () {
            var args = {},
                argOptions = this.data.args || {},
                options = this.options(),
                target = this.target || '';

            prepareCmd('doctrine:schema:validate', args, argOptions, options, target, this.async());
        }
    );

};
<|endoftext|>


<commit_before>/*
 * grunt-twig-render
 * https://github.com/sullinger/grunt-twig-render
 *
 * Copyright (c) 2014 Stefan Ullinger
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('twig_render', 'Render twig templates', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      punctuation: '.',
      separator: ', '
    });

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      // Concat specified files.
      var src = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      }).join(grunt.util.normalizelf(options.separator));

      // Handle options.
      src += options.punctuation;

      // Write the destination file.
      grunt.file.write(f.dest, src);

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');
    });
  });

};
<commit_msg>Defined twig_render task.<commit_after>/*
 * grunt-twig-render
 * https://github.com/sullinger/grunt-twig-render
 *
 * Copyright (c) 2014 Stefan Ullinger
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  var Twig = require("twig"),

  DEFAULT_OPTIONS = {
    // nothing here yet
  };

  function GruntTwigRender(options) {
    this.options = options(DEFAULT_OPTIONS);
  }

  GruntTwigRender.prototype.render = function(data, template, dest) {
    var data = this._getData(data);

    template = Twig.twig({
      path: template,
      async: false
    });

    grunt.file.write(dest, template.render(data));
  }

  GruntTwigRender.prototype._getData = function(data)
  {
    var datatype = typeof data;

    if (datatype === "undefined" || data == null) {
      grunt.fail.fatal("Data can not be undefined or null.");
    }
    else if (datatype === "string") {
      return this._getDataFromFile(data);
    }
    else if (datatype !== "object") {
      grunt.log.warn("Received data of type '" + datatype + "'. Expected 'object' or 'string'. Use at your own risk!");
    }

    return data;
  }

  GruntTwigRender.prototype._getDataFromFile = function(dataPath) {
    if (/\.json/i.test(dataPath)) {
      return grunt.file.readJSON(dataPath);
    }
    else {
      grunt.log.warn("Data file does not seem to be JSON. Trying to evaluate the file's contents into an javascript object. Use at your own risk!");
      return eval( '(' + grunt.file.read(dataPath) + ')' );
    }
  }

  grunt.registerMultiTask('twig_render', 'Render twig templates', function() {

    var renderer = new GruntTwigRender(this.options);

    this.files.forEach(function(fileData) {
      renderer.render(fileData.data, fileData.template, fileData.dest);
    });

  });

};<|endoftext|>


<commit_before>
/*
 * Barchart for energy production
*/
function ready_graph_data(data,x_value,y_value){
    var graph_data = [];
    for (var i=0; i < data.length; i++)
    {
         var data_point = {y:data[i]["fields"][x_value],a:data[i]["fields"][y_value]};
     graph_data.push(data_point);
    }
    return graph_data;
  }

// energy production graph
/* NOTE commenting out for now, switching out nvd3 graphs
Morris.Bar({
      element: 'energy-production-last-5-days',
      data: ready_graph_data(power_data,'time','w_production'),
  xkey: 'y',
  ykeys: ['a'],
  labels: ['wh']
});

//cloudcover forecast
Morris.Bar({
  element: 'cloud-cover-forecast',
  data: ready_graph_data(weather_data,'date','cloud_cover'),
  xLabels : 'day',
  xkey: 'y',
  ykeys: ['a'],
  labels: ['Cloud Cover %']
});
*/
//nano bar

/*
 High Chart Draw Function
*/
function get_high_chart(date,pv,cloud)
{

$('#containerhigh').highcharts({
        chart: {
            zoomType: 'xy'
        },
        title: {
            text: ' Daily PV Production with Cloud cover forecast In High Chart'
        },
        xAxis: [{
            categories:date,
            crosshair: true
        }],
        yAxis: [{ // Primary yAxis
            labels: {
                format: '{value}%',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            },
            title: {
                text: 'Cloud Cover',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            }
        }, { // Secondary yAxis
            title: {
                text: 'PV Production',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            },
            labels: {
                format: '{value} Wh',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            },
            opposite: true
        }],
        tooltip: {
            shared: true
        },
        legend: {
            layout: 'vertical',
            align: 'left',
            x: 120,
            verticalAlign: 'top',
            y: 100,
            floating: true,
            backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
        },
        series: [{
            name: 'PV Production',
            type: 'column',
            yAxis: 1,
            data:pv,
            tooltip: {
                valueSuffix: ' Wh'
            }

        }, {
            name: 'Percent Cloud Cover',
            type: 'spline',
            data: cloud,
            tooltip: {
                valueSuffix: ' % '
            }
        }]
    });

}

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies;
        cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');

// Get high chart data here

get_high_chart( date, HighChartHighPvProduction, HighChartHighCloudCover);

/* Alerts modal toggle script */

  var  modal = $('#alert-modal'),
       modalToggle = $('.modal-toggle'),
       alertDataPointInfo = $('.alert-data-point-info'),
       silenceAlert = $('.silence-alert'),
       initiatingModalTime = 5000;

  setTimeout(setModalLoad, initiatingModalTime);

/*ALerts Notifoication modal */

    $(document).ready(function(){
    alertId = $(this).attr('classid');

    var jsonData = {"alertId" : alertId,
                      csrfmiddlewaretoken: csrftoken};
     $.post('/notifications',jsonData, function(data){

          var alertData = JSON.parse(data);

          var out= $("#alert-notification-table");
          var element = '';
          var i;
          var sum_of_counters = 0;

          for(i=0 ; i<alertData.length ; i++){

                 sum_of_counters += alertData[i].counter;
                 $('#pop').html(sum_of_counters);
                 if (sum_of_counters > 0){
                     $('#pop').show();
                  }

                   element += '
' +
                               ''+ alertData[i].site +  '	' +
                               ''+ alertData[i].counter + '	' +
                               '
';

                   out.append(element);
                   }

                $('.clickable-row').click(function(){
                   window.location.href =$(this).data("href");
                 });
             });
        });

  function setModalLoad() {

      $('.modal-toggle').click(function()  {
          // Get necessary data for the get_alert_sort
          alertId = $(this).attr('classid');
          // Constructing the json
          var jsonData = {"alertId" : alertId,
                          csrfmiddlewaretoken: csrftoken};

          $.post('/get-alert-data', jsonData, function(data){

              var alertData = JSON.parse(data);
              alertValue = alertData.alert_value; // Getting the property that is triggering the alert

                  for (var value in alertData) {

                      if(value == 'alert_id'){ // Checking for alert_id so that it is not displayed
                          element = '
' + alertData[value] + '
';
                          alertDataPointInfo.append(element)
                          continue;
                      }
                      else if(value == 'alert_value') {
                          continue;
                      }
                      else if(value == alertValue) {
                          element = '
 ' + value + '	  ' + alertData[value] + '
';
                          alertDataPointInfo.append(element);
                          continue;
                      }
                element = '
' + value + '	  ' + alertData[value] + '
';
                      alertDataPointInfo.append(element);
                  }
          });
          modal.modal('show');
      });

      modal.on('hidden.bs.modal',function(){
          alertDataPointInfo.html('');
      });

      silenceAlert.click(function(){
          alertId = parseInt($('.alert-id').text());
          jsonData = {
                      alert_id : alertId,
                      csrfmiddlewaretoken: csrftoken
                     };

          $.post('/silence-alert', jsonData, function(data) {
               modal.modal('hide');
          });
      });

                  }

      /* Auto compete on search*/
var i;
var textid;
var textinput;
var option;
var matched;
var siteid = [];
var sitename = [];
/* post request to retrieve all sitename and site id */
$.post("/search",{csrfmiddlewaretoken: csrftoken},function(data){
    option = JSON.parse(data);
    /* extracting site name array from response dict */
   for (i=0;i < option.length;i++){
    sitename.push(option[i].value)
   }
   /* extracting site id array from response dict */
   for (i=0; i< option.length; i++){
    siteid.push(option[i].key)
   }
   var input = document.getElementById('search');
   /* proving an array of options to be suggested when a user types using awesomplete plugin */
   new Awesomplete(input,{list: sitename});
});
/* checking if ENTER button is pressed */
$('.form-control').keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    var matched = false;
    if(keycode == '13'){
        textinput = $(".form-control").val();
        for (i=0;i<sitename.length;i++){
            /* checking if entered value exists in a sitename array */
             if (sitename[i] == textinput){
                  matched = true;
                  for (i=0 ;i < option.length; i++){
                    /* finding the id of the entered sitename */
                       if (option[i].value == textinput){
                             textid = option[i].key;
                             /* Linking to the asked sitename`s page */
                             window.location.replace("/dash/" + textid);
                        }
                  }
             { break; }
             }
        }
        if (!matched){
          document.getElementById("search").className = document.getElementById("search").className + " error";
        }
    }
});
/* search button */
$(".btn-default").click(function(){
        textinput = $(".form-control").val();
        for (i=0;i<sitename.length;i++){
            /* checking if entered value exists in a sitename array */
             if (sitename[i] == textinput){
                  matched = true;
                  for (i=0 ;i < option.length; i++){
                    /* finding the id of the entered sitename */
                       if (option[i].value == textinput){
                             textid = option[i].key;
                             /* Linking to the asked sitename`s page */
                             window.location.replace("/dash/" + textid);
                        }
                  }
             { break; }

             }
        }
        if (!matched){
          document.getElementById("search").className = document.getElementById("search").className + " error";
        }
});

<commit_msg>removing the condition in the loop<commit_after>
/*
 * Barchart for energy production
*/
function ready_graph_data(data,x_value,y_value){
    var graph_data = [];
    for (var i=0; i < data.length; i++)
    {
         var data_point = {y:data[i]["fields"][x_value],a:data[i]["fields"][y_value]};
     graph_data.push(data_point);
    }
    return graph_data;
  }

// energy production graph
/* NOTE commenting out for now, switching out nvd3 graphs
Morris.Bar({
      element: 'energy-production-last-5-days',
      data: ready_graph_data(power_data,'time','w_production'),
  xkey: 'y',
  ykeys: ['a'],
  labels: ['wh']
});

//cloudcover forecast
Morris.Bar({
  element: 'cloud-cover-forecast',
  data: ready_graph_data(weather_data,'date','cloud_cover'),
  xLabels : 'day',
  xkey: 'y',
  ykeys: ['a'],
  labels: ['Cloud Cover %']
});
*/
//nano bar

/*
 High Chart Draw Function
*/
function get_high_chart(date,pv,cloud)
{

$('#containerhigh').highcharts({
        chart: {
            zoomType: 'xy'
        },
        title: {
            text: ' Daily PV Production with Cloud cover forecast In High Chart'
        },
        xAxis: [{
            categories:date,
            crosshair: true
        }],
        yAxis: [{ // Primary yAxis
            labels: {
                format: '{value}%',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            },
            title: {
                text: 'Cloud Cover',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            }
        }, { // Secondary yAxis
            title: {
                text: 'PV Production',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            },
            labels: {
                format: '{value} Wh',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            },
            opposite: true
        }],
        tooltip: {
            shared: true
        },
        legend: {
            layout: 'vertical',
            align: 'left',
            x: 120,
            verticalAlign: 'top',
            y: 100,
            floating: true,
            backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
        },
        series: [{
            name: 'PV Production',
            type: 'column',
            yAxis: 1,
            data:pv,
            tooltip: {
                valueSuffix: ' Wh'
            }

        }, {
            name: 'Percent Cloud Cover',
            type: 'spline',
            data: cloud,
            tooltip: {
                valueSuffix: ' % '
            }
        }]
    });

}

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies;
        cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');

// Get high chart data here

get_high_chart( date, HighChartHighPvProduction, HighChartHighCloudCover);

/* Alerts modal toggle script */

  var  modal = $('#alert-modal'),
       modalToggle = $('.modal-toggle'),
       alertDataPointInfo = $('.alert-data-point-info'),
       silenceAlert = $('.silence-alert'),
       initiatingModalTime = 5000;

  setTimeout(setModalLoad, initiatingModalTime);

/*ALerts Notifoication modal */

    $(document).ready(function(){
    alertId = $(this).attr('classid');

    var jsonData = {"alertId" : alertId,
                      csrfmiddlewaretoken: csrftoken};
     $.post('/notifications',jsonData, function(data){

          var alertData = JSON.parse(data);

          var out= $("#alert-notification-table");
          var element = '';
          var i;
          var sum_of_counters = 0;

          for(i=0 ; i<alertData.length ; i++){

              sum_of_counters += alertData[i].counter;                                                                                element += '
' +
                               ''+ alertData[i].site +  '	' +
                               ''+ alertData[i].counter + '	' +
                               '
';

                   out.append(element);
                   }

                 $('#pop').html(sum_of_counters);
                 if (sum_of_counters > 0){
                     $('#pop').show();
                  }

                $('.clickable-row').click(function(){
                   window.location.href =$(this).data("href");
                 });
             });
        });

  function setModalLoad() {

      $('.modal-toggle').click(function()  {
          // Get necessary data for the get_alert_sort
          alertId = $(this).attr('classid');
          // Constructing the json
          var jsonData = {"alertId" : alertId,
                          csrfmiddlewaretoken: csrftoken};

          $.post('/get-alert-data', jsonData, function(data){

              var alertData = JSON.parse(data);
              alertValue = alertData.alert_value; // Getting the property that is triggering the alert

                  for (var value in alertData) {

                      if(value == 'alert_id'){ // Checking for alert_id so that it is not displayed
                          element = '
' + alertData[value] + '
';
                          alertDataPointInfo.append(element)
                          continue;
                      }
                      else if(value == 'alert_value') {
                          continue;
                      }
                      else if(value == alertValue) {
                          element = '
 ' + value + '	  ' + alertData[value] + '
';
                          alertDataPointInfo.append(element);
                          continue;
                      }
                element = '
' + value + '	  ' + alertData[value] + '
';
                      alertDataPointInfo.append(element);
                  }
          });
          modal.modal('show');
      });

      modal.on('hidden.bs.modal',function(){
          alertDataPointInfo.html('');
      });

      silenceAlert.click(function(){
          alertId = parseInt($('.alert-id').text());
          jsonData = {
                      alert_id : alertId,
                      csrfmiddlewaretoken: csrftoken
                     };

          $.post('/silence-alert', jsonData, function(data) {
               modal.modal('hide');
          });
      });

                  }

      /* Auto compete on search*/
var i;
var textid;
var textinput;
var option;
var matched;
var siteid = [];
var sitename = [];
/* post request to retrieve all sitename and site id */
$.post("/search",{csrfmiddlewaretoken: csrftoken},function(data){
    option = JSON.parse(data);
    /* extracting site name array from response dict */
   for (i=0;i < option.length;i++){
    sitename.push(option[i].value)
   }
   /* extracting site id array from response dict */
   for (i=0; i< option.length; i++){
    siteid.push(option[i].key)
   }
   var input = document.getElementById('search');
   /* proving an array of options to be suggested when a user types using awesomplete plugin */
   new Awesomplete(input,{list: sitename});
});
/* checking if ENTER button is pressed */
$('.form-control').keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    var matched = false;
    if(keycode == '13'){
        textinput = $(".form-control").val();
        for (i=0;i<sitename.length;i++){
            /* checking if entered value exists in a sitename array */
             if (sitename[i] == textinput){
                  matched = true;
                  for (i=0 ;i < option.length; i++){
                    /* finding the id of the entered sitename */
                       if (option[i].value == textinput){
                             textid = option[i].key;
                             /* Linking to the asked sitename`s page */
                             window.location.replace("/dash/" + textid);
                        }
                  }
             { break; }
             }
        }
        if (!matched){
          document.getElementById("search").className = document.getElementById("search").className + " error";
        }
    }
});
/* search button */
$(".btn-default").click(function(){
        textinput = $(".form-control").val();
        for (i=0;i<sitename.length;i++){
            /* checking if entered value exists in a sitename array */
             if (sitename[i] == textinput){
                  matched = true;
                  for (i=0 ;i < option.length; i++){
                    /* finding the id of the entered sitename */
                       if (option[i].value == textinput){
                             textid = option[i].key;
                             /* Linking to the asked sitename`s page */
                             window.location.replace("/dash/" + textid);
                        }
                  }
             { break; }

             }
        }
        if (!matched){
          document.getElementById("search").className = document.getElementById("search").className + " error";
        }
});

<|endoftext|>


<commit_before>function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies;
        cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
       }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');
/*
 * Barchart for energy production
*/

      /* Auto compete on search*/
var i;
var textid;
var textinput;
var option;
var matched;
var siteid = [];
var sitename = [];
/* post request to retrieve all sitename and site id */
$.post("/search",{csrfmiddlewaretoken: csrftoken},function(data){
    option = JSON.parse(data);
    //console.log(option)
    /* extracting site name array from response dict */
   for (i=0;i < option.length;i++){
    sitename.push(option[i].value)
   }
   /* extracting site id array from response dict */
   for (i=0; i< option.length; i++){
    siteid.push(option[i].key)
   }
   var input = document.getElementById('search');
   /* proving an array of options to be suggested when a user types using awesomplete plugin */
   new Awesomplete(input,{list: sitename});
});
/* checking if ENTER button is pressed */
$('.form-control').keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    var matched = false;
    if(keycode == '13'){
        textinput = $(".form-control").val();
        for (i=0;i<sitename.length;i++){
            /* checking if entered value exists in a sitename array */
             if (sitename[i] == textinput){
                  matched = true;
                  for (i=0 ;i < option.length; i++){
                    /* finding the id of the entered sitename */
                       if (option[i].value == textinput){
                             textid = option[i].key;
                             /* Linking to the asked sitename`s page */
                             window.location.replace("/dash/" + textid);
                        }
                  }
             { break; }
             }
        }
        if (!matched){
          document.getElementById("search").className = document.getElementById("search").className + " error";
        }
    }
});
/* search button */
$(".btn-default").click(function(){
        textinput = $(".form-control").val();
        for (i=0;i<sitename.length;i++){
            /* checking if entered value exists in a sitename array */
             if (sitename[i] == textinput){
                  matched = true;
                  for (i=0 ;i < option.length; i++){
                    /* finding the id of the entered sitename */
                       if (option[i].value == textinput){
                             textid = option[i].key;
                             /* Linking to the asked sitename`s page */
                             window.location.replace("/dash/" + textid);
                        }
                  }
             { break; }

             }
        }
        if (!matched){
          document.getElementById("search").className = document.getElementById("search").className + " error";
        }
});

function ready_graph_data(data,x_value,y_value){
    var graph_data = [];
    for (var i=0; i < data.length; i++)
    {
         var data_point = {y:data[i]["fields"][x_value],a:data[i]["fields"][y_value]};
     graph_data.push(data_point);
    }
    return graph_data;
  }

// energy production graph
/* NOTE commenting out for now, switching out nvd3 graphs
Morris.Bar({
      element: 'energy-production-last-5-days',
      data: ready_graph_data(power_data,'time','w_production'),
  xkey: 'y',
  ykeys: ['a'],
  labels: ['wh']
});

//cloudcover forecast
Morris.Bar({
  element: 'cloud-cover-forecast',
  data: ready_graph_data(weather_data,'date','cloud_cover'),
  xLabels : 'day',
  xkey: 'y',
  ykeys: ['a'],
  labels: ['Cloud Cover %']
});
*/
//nano bar

/* Alerts modal toggle script */

  var  modal = $('#alert-modal'),
       modalToggle = $('.modal-toggle'),
       alertDataPointInfo = $('.alert-data-point-info'),
       silenceAlert = $('.silence-alert'),
       initiatingModalTime = 5000;

  setTimeout(setModalLoad, initiatingModalTime);

/*ALerts Notifoication modal */

    $(document).ready(function(){
    alertId = $(this).attr('classid');

    var jsonData = {"alertId" : alertId,
                      csrfmiddlewaretoken: csrftoken};
     $.post('/notifications',jsonData, function(data){

          var alertData = JSON.parse(data);

          var out= $("#alert-notification-table");
          var element = '';
          var i;
          var sum_of_counters = 0;

          for(i=0 ; i<alertData.length ; i++){

              sum_of_counters += alertData[i].counter;                                                                                element += '
' +
                               ''+ alertData[i].site +  '	' +
                               ''+ alertData[i].counter + '	' +
                               '
';

                   out.append(element);
                   }

                 $('#pop').html(sum_of_counters);
                 if (sum_of_counters > 0){
                     $('#pop').show();
                  }

                $('.clickable-row').click(function(){
                   window.location.href =$(this).data("href");
                 });
             });
        });

  function setModalLoad() {

      var alertDataContainer = $('#alert-data-container'),
          alertLoader = $('#alert-data-loader');

      $('.modal-toggle').click(function()  {

          alertLoader.show();
          alertDataContainer.hide();

          // Get necessary data for the get_alert_sort
          alertId = $(this).attr('classid');
          // Constructing the json
          var jsonData = {"alertId" : alertId,
                          csrfmiddlewaretoken: csrftoken};

          $.post('/get-alert-data', jsonData, function(data){

              alertLoader.hide();
              alertDataContainer.show();

              var alertData = JSON.parse(data);
              alertValue = alertData.alert_value; // Getting the property that is triggering the alert

                  for (var value in alertData) {

                      if(value == 'alert_id'){ // Checking for alert_id so that it is not displayed
                          element = '
' + alertData[value] + '
';
                          alertDataPointInfo.append(element)
                          continue;
                      }
                      else if(value == 'alert_value') {
                          continue;
                      }
                      else if(value == alertValue) {
                          element = '
 ' + value + '	  ' + alertData[value] + '
';
                          alertDataPointInfo.append(element);
                          continue;
                      }
                element = '
' + value + '	  ' + alertData[value] + '
';
                      alertDataPointInfo.append(element);
                  }
          });
          modal.modal('show');
      });

      modal.on('hidden.bs.modal',function(){
          alertDataPointInfo.html('');
      });

      silenceAlert.click(function(){
          alertId = parseInt($('.alert-id').text());
          jsonData = {
                      alert_id : alertId,
                      csrfmiddlewaretoken: csrftoken
                     };

          $.post('/silence-alert', jsonData, function(data) {
               modal.modal('hide');
          });
      });

}
<commit_msg>Made the panels draggable<commit_after>function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies;
        cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
       }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');
/*
 * Barchart for energy production
*/

      /* Auto compete on search*/
var i;
var textid;
var textinput;
var option;
var matched;
var siteid = [];
var sitename = [];
/* post request to retrieve all sitename and site id */
$.post("/search",{csrfmiddlewaretoken: csrftoken},function(data){
    option = JSON.parse(data);
    //console.log(option)
    /* extracting site name array from response dict */
   for (i=0;i < option.length;i++){
    sitename.push(option[i].value)
   }
   /* extracting site id array from response dict */
   for (i=0; i< option.length; i++){
    siteid.push(option[i].key)
   }
   var input = document.getElementById('search');
   /* proving an array of options to be suggested when a user types using awesomplete plugin */
   new Awesomplete(input,{list: sitename});
});
/* checking if ENTER button is pressed */
$('.form-control').keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    var matched = false;
    if(keycode == '13'){
        textinput = $(".form-control").val();
        for (i=0;i<sitename.length;i++){
            /* checking if entered value exists in a sitename array */
             if (sitename[i] == textinput){
                  matched = true;
                  for (i=0 ;i < option.length; i++){
                    /* finding the id of the entered sitename */
                       if (option[i].value == textinput){
                             textid = option[i].key;
                             /* Linking to the asked sitename`s page */
                             window.location.replace("/dash/" + textid);
                        }
                  }
             { break; }
             }
        }
        if (!matched){
          document.getElementById("search").className = document.getElementById("search").className + " error";
        }
    }
});
/* search button */
$(".btn-default").click(function(){
        textinput = $(".form-control").val();
        for (i=0;i<sitename.length;i++){
            /* checking if entered value exists in a sitename array */
             if (sitename[i] == textinput){
                  matched = true;
                  for (i=0 ;i < option.length; i++){
                    /* finding the id of the entered sitename */
                       if (option[i].value == textinput){
                             textid = option[i].key;
                             /* Linking to the asked sitename`s page */
                             window.location.replace("/dash/" + textid);
                        }
                  }
             { break; }

             }
        }
        if (!matched){
          document.getElementById("search").className = document.getElementById("search").className + " error";
        }
});

function ready_graph_data(data,x_value,y_value){
    var graph_data = [];
    for (var i=0; i < data.length; i++)
    {
         var data_point = {y:data[i]["fields"][x_value],a:data[i]["fields"][y_value]};
     graph_data.push(data_point);
    }
    return graph_data;
  }

// energy production graph
/* NOTE commenting out for now, switching out nvd3 graphs
Morris.Bar({
      element: 'energy-production-last-5-days',
      data: ready_graph_data(power_data,'time','w_production'),
  xkey: 'y',
  ykeys: ['a'],
  labels: ['wh']
});

//cloudcover forecast
Morris.Bar({
  element: 'cloud-cover-forecast',
  data: ready_graph_data(weather_data,'date','cloud_cover'),
  xLabels : 'day',
  xkey: 'y',
  ykeys: ['a'],
  labels: ['Cloud Cover %']
});
*/
//nano bar

/* Alerts modal toggle script */

  var  modal = $('#alert-modal'),
       modalToggle = $('.modal-toggle'),
       alertDataPointInfo = $('.alert-data-point-info'),
       silenceAlert = $('.silence-alert'),
       initiatingModalTime = 5000;

  setTimeout(setModalLoad, initiatingModalTime);

/*ALerts Notifoication modal */

    $(document).ready(function(){
    alertId = $(this).attr('classid');

    var jsonData = {"alertId" : alertId,
                      csrfmiddlewaretoken: csrftoken};
     $.post('/notifications',jsonData, function(data){

          var alertData = JSON.parse(data);

          var out= $("#alert-notification-table");
          var element = '';
          var i;
          var sum_of_counters = 0;

          for(i=0 ; i<alertData.length ; i++){

              sum_of_counters += alertData[i].counter;                                                                                element += '
' +
                               ''+ alertData[i].site +  '	' +
                               ''+ alertData[i].counter + '	' +
                               '
';

                   out.append(element);
                   }

                 $('#pop').html(sum_of_counters);
                 if (sum_of_counters > 0){
                     $('#pop').show();
                  }

                $('.clickable-row').click(function(){
                   window.location.href =$(this).data("href");
                 });
             });
        });

  function setModalLoad() {

      var alertDataContainer = $('#alert-data-container'),
          alertLoader = $('#alert-data-loader');

      $('.modal-toggle').click(function()  {

          alertLoader.show();
          alertDataContainer.hide();

          // Get necessary data for the get_alert_sort
          alertId = $(this).attr('classid');
          // Constructing the json
          var jsonData = {"alertId" : alertId,
                          csrfmiddlewaretoken: csrftoken};

          $.post('/get-alert-data', jsonData, function(data){

              alertLoader.hide();
              alertDataContainer.show();

              var alertData = JSON.parse(data);
              alertValue = alertData.alert_value; // Getting the property that is triggering the alert

                  for (var value in alertData) {

                      if(value == 'alert_id'){ // Checking for alert_id so that it is not displayed
                          element = '
' + alertData[value] + '
';
                          alertDataPointInfo.append(element)
                          continue;
                      }
                      else if(value == 'alert_value') {
                          continue;
                      }
                      else if(value == alertValue) {
                          element = '
 ' + value + '	  ' + alertData[value] + '
';
                          alertDataPointInfo.append(element);
                          continue;
                      }
                element = '
' + value + '	  ' + alertData[value] + '
';
                      alertDataPointInfo.append(element);
                  }
          });
          modal.modal('show');
      });

      modal.on('hidden.bs.modal',function(){
          alertDataPointInfo.html('');
      });

      silenceAlert.click(function(){
          alertId = parseInt($('.alert-id').text());
          jsonData = {
                      alert_id : alertId,
                      csrfmiddlewaretoken: csrftoken
                     };

          $.post('/silence-alert', jsonData, function(data) {
               modal.modal('hide');
          });
      });

      // Draggable panelsa
      var panelsContainer = $('.panels-container');

      panelsContainer.sortable();
      panelsContainer.disableSelection();

}
<|endoftext|>


<commit_before>Ficha = require('../models/').Ficha;
Users = require('../models/').User;
// CRUD Operations for Ficha Model
module.exports= {
  index(req, res) {
    Ficha.findAll()
      .then(function (Fichas) {
        res.status(200).json(Fichas);
      })
      .catch(function (error) {
        console.log(error);
        res.status(500).json(error);
      });
  },

  show(req, res) {
    Ficha.findAll({
      where: {
        id: req.params.id
      },
      include: [ {model: Users} ]
    })
    .then(function (Ficha) {
      res.status(200).json(Ficha);
    })
    .catch(function (error){
      console.log(error);
      res.status(500).json(error);
    });
  },

  create(req, res) {
    // res.status(200).json(req.body);
    Ficha.create(req.body)
      .then(function (newFicha) {
        res.status(200).json(newFicha);
      })
      .catch(function (error){
        res.status(500).json(error);
      });
  },

  update(req, res) {
    Ficha.update(req.body, {
      where: {
        id: req.body.id
      }
    })
    .then(function (updatedRecords) {
      res.status(200).json(updatedRecords);
    })
    .catch(function (error){
      console.log(error);
      res.status(500).json(error);
    });
  },

  delete(req, res) {
    console.log(req.params)
    Ficha.destroy({
      where: {
        id: req.params.id
      }
    })
    .then(function (deletedRecords) {
      res.status(200).json(deletedRecords);
    })
    .catch(function (error){
      console.log(error);
      res.status(500).json(error);
    });
  },

  search(req, res){
    Ficha.findAll({
        where: {
            nombreactividad: {
                $like:req.params.query
            }
        }
    })
    .then(function (Fichas) {
        res.status(200).json(Fichas);
    })
    .catch(function (error) {
        console.log(error);
        res.status(500).json(error);
    });
  }
};
<commit_msg>Update fichas.js<commit_after>Ficha = require('../models/').Ficha;
Users = require('../models/').User;
// CRUD Operations for Ficha Model
module.exports= {
  index(req, res) {
    Ficha.findAll()
      .then(function (Fichas) {
        res.status(200).json(Fichas);
      })
      .catch(function (error) {
        console.log(error);
        res.status(500).json(error);
      });
  },

  show(req, res) {
    Ficha.findAll({
      where: {
        id: req.params.id
      },
      include: [ {model: Users} ]
    })
    .then(function (Ficha) {
      res.status(200).json(Ficha);
    })
    .catch(function (error){
      console.log(error);
      res.status(500).json(error);
    });
  },

  create(req, res) {
    // res.status(200).json(req.body);
    Ficha.create(req.body)
      .then(function (newFicha) {
        res.status(200).json(newFicha);
      })
      .catch(function (error){
        res.status(500).json(error);
      });
  },

  update(req, res) {
    Ficha.update(req.body, {
      where: {
        id: req.body.id
      }
    })
    .then(function (updatedRecords) {
      res.status(200).json(updatedRecords);
    })
    .catch(function (error){
      console.log(error);
      res.status(500).json(error);
    });
  },

  delete(req, res) {
    console.log(req.params)
    Ficha.destroy({
      where: {
        id: req.params.id
      }
    })
    .then(function (deletedRecords) {
      res.status(200).json(deletedRecords);
    })
    .catch(function (error){
      console.log(error);
      res.status(500).json(error);
    });
  }
};
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */
module.exports = function(ukiyoe, app) {

var Image = ukiyoe.db.model("Image"),
    utils = require("../../lib/utils"),
    _ = require("lodash"),
    exports = {};

Image.prototype.getURL = function(locale) {
    return app.genURL(locale, "/images/" + this._id);
};

exports.load = function(req, res, next, imageName) {
    Image.findById(req.params.sourceId + "/" + imageName)
        .populate("similar.image")
        .populate("artists.artist")
        .populate("source") // TODO: Don't do this.
        .exec(function(err, image) {
            if (err) {
                return next(err);
            }
            if (!image) {
                console.log("not found")
                return next(new Error("not found"));
            }
            req.image = image;
            next();
        });
};

exports.search = function(req, res) {
    var page = (req.param("page") > 0 ? req.param("page") : 1) - 1;
    var perPage = 100;
    var q = req.param("q") || "";

    var query = {
        query_string: {
            query: q
        },
        filtered: {
            filter: {},
            size: perPage,
            from: page * perPage,
            "sort": [
                {
                    "dateCreated.start": {
                        "order": "asc"
                    }
                },
                {
                    "dateCreated.end": {
                        "order": "asc"
                    }
                }
            ]
        }
    };

    if (req.param("startDate") && req.param("endDate")) {
        query.filtered.filter.and = [
            {
                range: {
                    "dateCreated.start": {
                        gte: parseFloat(req.param("startDate")),
                        lte: parseFloat(req.param("endDate"))
                    }
                }
            },
            {
                range: {
                    "dateCreated.end": {
                        gte: parseFloat(req.param("startDate")),
                        lte: parseFloat(req.param("endDate"))
                    }
                }
            }
        ];
    }

    Image.search({query: query}, {hydrate: true, hydrateOptions: {populate: "artists.artist"}}, function(err, results){
        if (err) {
            console.error(err);
            return res.render("500");
        }

        res.render("images/index", {
            title: "Images",
            q: req.param("q"),
            startDate: req.param("startDate") || "1765",
            endDate: req.param("endDate") || "1868",
            images: results.hits,
            page: page + 1,
            pages: Math.ceil(results.total / perPage)
        });
    });
};

var handleUpload = function(req, baseDir, callback) {
    var url = req.body.url || req.query.url;

    // Handle the user accidentally hitting enter
    if (url && url === "http://") {
        return callback();
    }

    var stream;

    if (url) {
        stream = request({
            url: url,
            timeout: 30000
        });
    } else {
        stream = fs.createReadStream(req.files.file.path)
    }

    ukiyoe.images.downloadStream(stream, baseDir, true, callback);
};

exports.searchUpload = function(req, res) {
    // TODO: Get baseDir for the image
    handleUpload(req, "...", function() {

    });
};

/**
 * List
 */

exports.index = function(req, res) {
    var page = (req.param("page") > 0 ? req.param("page") : 1) - 1;
    var perPage = 100;
    var options = {
        query: "fish",
        size: perPage,
        from: page * perPage
    };

    // , hydrateOptions: {populate: "bios"}
    Image.search(options, {hydrate: true}, function(err, results){
        if (err) {
            return res.render("500");
        }

        res.render("images/index", {
            title: "Images",
            images: results.hits,
            page: page + 1,
            pages: Math.ceil(results.total / perPage)
        });
    });
};

/**
 * New image
 */

exports.new = function(req, res) {
    res.render("images/new", {
        title: "New Image",
        image: new Image({})
    });
};

/**
 * Create an image
 */

exports.create = function(req, res) {
    var image = new Image(req.body);
    image.user = req.user;

    image.save(function(err) {
        if (!err) {
            req.flash("success", "Successfully created image!");
            return res.redirect("/images/" + image._id);
        }

        res.render("images/new", {
            title: "New Image",
            image: image,
            errors: utils.errors(err.errors || err)
        });
    });
};

/**
 * Edit an image
 */

exports.edit = function(req, res) {
    res.render("images/edit", {
        title: "Edit " + req.image.title,
        image: req.image
    });
};

/**
 * Update image
 */

exports.update = function(req, res) {
    var image = req.image;
    image = _.extend(image, req.body);

    image.save(function(err) {
        if (!err) {
            return res.redirect("/images/" + image._id);
        }

        res.render("images/edit", {
            title: "Edit Image",
            image: image,
            errors: err.errors
        });
    });
};

/**
 * Show
 */

exports.show = function(req, res) {
    res.render("images/show", {
        //title: req.image.title,
        image: req.image,
        results: req.image.similar
    });
};

/**
 * Delete an image
 */

exports.destroy = function(req, res) {
    var image = req.image;
    image.remove(function(err) {
        req.flash("info", "Deleted successfully")
        res.redirect("/images")
    });
};

return exports;
};<commit_msg>Create a new upload entry on image upload.<commit_after>
/**
 * Module dependencies.
 */
module.exports = function(ukiyoe, app) {

var Image = ukiyoe.db.model("Image"),
    Upload = ukiyoe.db.model("Upload"),
    utils = require("../../lib/utils"),
    _ = require("lodash"),
    exports = {};

Image.prototype.getURL = function(locale) {
    return app.genURL(locale, "/images/" + this._id);
};

Upload.prototype.getURL = function(locale) {
    return app.genURL(locale, "/uploads/" + this._id);
};

exports.load = function(req, res, next, imageName) {
    Image.findById(req.params.sourceId + "/" + imageName)
        .populate("similar.image")
        .populate("artists.artist")
        .populate("source") // TODO: Don't do this.
        .exec(function(err, image) {
            if (err) {
                return next(err);
            }
            if (!image) {
                console.log("not found")
                return next(new Error("not found"));
            }
            req.image = image;
            next();
        });
};

exports.search = function(req, res) {
    var page = (req.param("page") > 0 ? req.param("page") : 1) - 1;
    var perPage = 100;
    var q = req.param("q") || "";

    var query = {
        query_string: {
            query: q
        },
        filtered: {
            filter: {},
            size: perPage,
            from: page * perPage,
            "sort": [
                {
                    "dateCreated.start": {
                        "order": "asc"
                    }
                },
                {
                    "dateCreated.end": {
                        "order": "asc"
                    }
                }
            ]
        }
    };

    if (req.param("startDate") && req.param("endDate")) {
        query.filtered.filter.and = [
            {
                range: {
                    "dateCreated.start": {
                        gte: parseFloat(req.param("startDate")),
                        lte: parseFloat(req.param("endDate"))
                    }
                }
            },
            {
                range: {
                    "dateCreated.end": {
                        gte: parseFloat(req.param("startDate")),
                        lte: parseFloat(req.param("endDate"))
                    }
                }
            }
        ];
    }

    Image.search({query: query}, {hydrate: true, hydrateOptions: {populate: "artists.artist"}}, function(err, results){
        if (err) {
            console.error(err);
            return res.render("500");
        }

        res.render("images/index", {
            title: "Images",
            q: req.param("q"),
            startDate: req.param("startDate") || "1765",
            endDate: req.param("endDate") || "1868",
            images: results.hits,
            page: page + 1,
            pages: Math.ceil(results.total / perPage)
        });
    });
};

var handleUpload = function(req, baseDir, callback) {
    var url = req.body.url || req.query.url;

    // Handle the user accidentally hitting enter
    if (url && url === "http://") {
        return callback({err: "No file specified."});
    }

    var stream;

    if (url) {
        stream = request({
            url: url,
            timeout: 5000
        });
    } else {
        stream = fs.createReadStream(req.files.file.path)
    }

    ukiyoe.images.downloadStream(stream, baseDir, true, callback);
};

exports.searchUpload = function(req, res) {
    // TODO: Get baseDir for the image
    handleUpload(req, "...", function(err, id) {
        if (err) {
            // TODO: Show some sort of error message
            return res.redirect(app.genURL(req.i18n.getLocale(), "/"));
        }

        var upload = new Upload({
            _id: "uploads/" + id,
            imageName: id,
            source: "uploads"
        });

        upload.save(function() {
            res.redirect(upload.getURL());
        });
    });
};

/**
 * List
 */

exports.index = function(req, res) {
    var page = (req.param("page") > 0 ? req.param("page") : 1) - 1;
    var perPage = 100;
    var options = {
        query: "fish",
        size: perPage,
        from: page * perPage
    };

    // , hydrateOptions: {populate: "bios"}
    Image.search(options, {hydrate: true}, function(err, results){
        if (err) {
            return res.render("500");
        }

        res.render("images/index", {
            title: "Images",
            images: results.hits,
            page: page + 1,
            pages: Math.ceil(results.total / perPage)
        });
    });
};

/**
 * New image
 */

exports.new = function(req, res) {
    res.render("images/new", {
        title: "New Image",
        image: new Image({})
    });
};

/**
 * Create an image
 */

exports.create = function(req, res) {
    var image = new Image(req.body);
    image.user = req.user;

    image.save(function(err) {
        if (!err) {
            req.flash("success", "Successfully created image!");
            return res.redirect("/images/" + image._id);
        }

        res.render("images/new", {
            title: "New Image",
            image: image,
            errors: utils.errors(err.errors || err)
        });
    });
};

/**
 * Edit an image
 */

exports.edit = function(req, res) {
    res.render("images/edit", {
        title: "Edit " + req.image.title,
        image: req.image
    });
};

/**
 * Update image
 */

exports.update = function(req, res) {
    var image = req.image;
    image = _.extend(image, req.body);

    image.save(function(err) {
        if (!err) {
            return res.redirect("/images/" + image._id);
        }

        res.render("images/edit", {
            title: "Edit Image",
            image: image,
            errors: err.errors
        });
    });
};

/**
 * Show
 */

exports.show = function(req, res) {
    res.render("images/show", {
        //title: req.image.title,
        image: req.image,
        results: req.image.similar
    });
};

/**
 * Delete an image
 */

exports.destroy = function(req, res) {
    var image = req.image;
    image.remove(function(err) {
        req.flash("info", "Deleted successfully")
        res.redirect("/images")
    });
};

return exports;
};<|endoftext|>


<commit_before>/* eslint eqeqeq: "off", guard-for-in: "off" */

import config from 'config';
import Records from '../models/records';
import getCacheKey from './helper/cacheKey';
import Downloads from '../services/downloads';
import dateHelper from '../utils/date';
import logger from '../utils/logger';
import notify from '../services/notify';
import {
  formatObject
} from '../utils/helper';
import UserAPI from '../services/user';

/* ===================== private ===================== */

const URL = config.get('url');

const getResumeShareStatus = (resumeInfo, locale) => {
  const {
    login,
    github,
    template,
    useGithub,
    resumeHash,
    openShare,
    simplifyUrl,
  } = resumeInfo;

  return {
    github,
    locale,
    template,
    openShare,
    useGithub,
    resumeHash,
    simplifyUrl,
    githubUrl: null,
    url: simplifyUrl && login
      ? `${login}/resume?locale=${locale}`
      : `resume/${resumeHash}?locale=${locale}`
  };
};

/* ===================== router handler ===================== */

const getResume = async (ctx) => {
  const { userId } = ctx.session;
  const data = await UserAPI.getResume({ userId });

  ctx.body = {
    success: true,
    result: data ? data.resume : null,
  };
};

const setResume = async (ctx, next) => {
  const { resume } = ctx.request.body;
  const { userId, githubLogin } = ctx.session;

  const targetResume = formatObject(resume);
  const result = await UserAPI.updateResume({
    userId,
    login: githubLogin,
    resume: targetResume
  });

  const cacheKey = getCacheKey(ctx);
  ctx.query.deleteKeys = [
    cacheKey(`resume.${result.hash}`)
  ];
  logger.info(`[RESUME:UPDATE][${githubLogin}]`);

  notify('slack').send({
    mq: ctx.mq,
    data: {
      type: 'resume',
      data: `Resume create or update by <https://github.com/${githubLogin}|${githubLogin}>`
    }
  });

  ctx.body = {
    result,
    success: true,
    message: ctx.__('messages.success.save'),
  };

  await next();
};

const patchResume = async (ctx, next) => {
  const { userId, githubLogin } = ctx.session;
  const getResult = await UserAPI.getResume({ userId });
  const resume = Object.assign({}, getResult ? getResult.resume : {});
  const { data } = ctx.request.body;

  for (const key in data) {
    const d = data[key];
    for (const k in d) {
      if (!resume[key]) resume[key] = {};
      resume[key][k] = d[k];
    }
  }

  const result = await UserAPI.updateResume({
    userId,
    resume,
    login: githubLogin,
  });

  const cacheKey = getCacheKey(ctx);
  ctx.query.deleteKeys = [
    cacheKey(`resume.${result.hash}`)
  ];

  ctx.body = {
    result,
    success: true,
  };

  await next();
};

const downloadResume = async (ctx) => {
  const { userId, githubLogin, locale } = ctx.session;

  const result = await UserAPI.getResumeInfo({ userId });
  const { template, resumeHash } = result;

  const findResult = await UserAPI.getResume({ userId });

  if (!findResult) {
    return ctx.body = {
      result: '',
      success: true,
      message: ctx.__('messages.error.emptyResume'),
    };
  }

  const updateTime = findResult.update_at;
  const seconds = dateHelper.getSeconds(updateTime);

  const resumeUrl =
    `${URL}/resume/${resumeHash}?locale=${locale}&userId=${userId}&notrace=true`;

  notify('slack').send({
    mq: ctx.mq,
    data: {
      type: 'download',
      data: `【${githubLogin}:${resumeHash}】`
    }
  });

  logger.info(`[RESUME:DOWNLOAD][${resumeUrl}]`);
  ctx.cache.hincrby('resume', 'download', 1);

  let resultUrl = '';
  try {
    resultUrl = await Downloads.resume(resumeUrl, {
      folder: githubLogin,
      title: `${template}-${locale}-${seconds}-resume.pdf`
    });
    logger.info(`[RESUME:RENDERED][${resultUrl}]`);
  } catch (e) {
    logger.error(`[RESUME:DOWNLOAD:ERROR]${e}`);
  }

  ctx.body = {
    result: resultUrl,
    success: true
  };
};

const resumePage = async (ctx) => {
  const { resumeInfo } = ctx;
  const { login } = resumeInfo;
  const user = await UserAPI.getUser({ login });

  const { isMobile } = ctx.state;
  const { fromDownload, githubLogin } = ctx.session;
  const isAdmin = login === githubLogin;
  const { userName, userId } = user;

  if (isMobile) {
    await ctx.render('user/mobile/resume', {
      title: ctx.__('resumePage.title', userName),
      login,
      userId,
      fromDownload,
      user: {
        login,
        isAdmin,
      },
      hideFooter: true,
    });
  } else {
    await ctx.render('resume/share', {
      login,
      userId,
      fromDownload,
      hideFooter: true,
      title: ctx.__('resumePage.title', userName),
    });
  }
};

const getResumeByHash = async (ctx, next) => {
  const { hash } = ctx.query;
  const findResult = await UserAPI.getResume({ hash });

  let result = null;
  if (findResult) {
    result = findResult.resume;
    result.updateAt = findResult.update_at;
  }

  ctx.body = {
    result,
    success: true,
  };

  await next();
};

const getResumeInfo = async (ctx) => {
  const { hash, userId } = ctx.query;
  const { locale } = ctx.session;
  const qs = {};
  if (hash) {
    qs.hash = hash;
  } else if (userId) {
    qs.userId = userId;
  } else {
    qs.userId = ctx.session.userId;
  }
  const resumeInfo = await UserAPI.getResumeInfo(qs);

  let result = null;
  if (resumeInfo) {
    result = getResumeShareStatus(resumeInfo, locale);
  }
  ctx.body = {
    result,
    success: true,
  };
};

const getShareRecords = async (ctx) => {
  const { userId, githubLogin } = ctx.session;

  const resumeInfo = await UserAPI.getResumeInfo({ userId });
  if (!resumeInfo) {
    return ctx.body = {
      success: true,
      result: {
        url: '',
        viewDevices: [],
        viewSources: [],
        pageViews: [],
        openShare: false
      }
    };
  }

  const records = await Records.getRecords(ctx.db, {
    login: githubLogin,
    type: 'resume'
  });
  const viewDevices = [];
  const viewSources = [];
  const pageViews = [];

  for (const record of records) {
    viewDevices.push(...record.viewDevices);
    viewSources.push(...record.viewSources);
    pageViews.push(...record.pageViews);
  }
  ctx.body = {
    success: true,
    result: {
      pageViews,
      viewDevices,
      viewSources,
      openShare: resumeInfo.openShare,
      url: `${githubLogin}/resume?locale=${ctx.session.locale}`,
    }
  };
};

const setResumeInfo = async (ctx) => {
  const { info } = ctx.request.body;
  const { userId, githubLogin } = ctx.session;

  const result = await UserAPI.setResumeInfo({
    info,
    userId,
    login: githubLogin
  });

  ctx.body = {
    result,
    success: true,
  };
};

export default {
  // ============
  getResume,
  setResume,
  patchResume,
  // ============
  resumePage,
  getResumeByHash,
  // ============
  downloadResume,
  getShareRecords,
  // ============
  getResumeInfo,
  setResumeInfo,
};
<commit_msg>WHAT: typo: update_at -> updated_at<commit_after>/* eslint eqeqeq: "off", guard-for-in: "off" */

import config from 'config';
import Records from '../models/records';
import getCacheKey from './helper/cacheKey';
import Downloads from '../services/downloads';
import dateHelper from '../utils/date';
import logger from '../utils/logger';
import notify from '../services/notify';
import {
  formatObject
} from '../utils/helper';
import UserAPI from '../services/user';

/* ===================== private ===================== */

const URL = config.get('url');

const getResumeShareStatus = (resumeInfo, locale) => {
  const {
    login,
    github,
    template,
    useGithub,
    resumeHash,
    openShare,
    simplifyUrl,
  } = resumeInfo;

  return {
    github,
    locale,
    template,
    openShare,
    useGithub,
    resumeHash,
    simplifyUrl,
    githubUrl: null,
    url: simplifyUrl && login
      ? `${login}/resume?locale=${locale}`
      : `resume/${resumeHash}?locale=${locale}`
  };
};

/* ===================== router handler ===================== */

const getResume = async (ctx) => {
  const { userId } = ctx.session;
  const data = await UserAPI.getResume({ userId });

  ctx.body = {
    success: true,
    result: data ? data.resume : null,
  };
};

const setResume = async (ctx, next) => {
  const { resume } = ctx.request.body;
  const { userId, githubLogin } = ctx.session;

  const targetResume = formatObject(resume);
  const result = await UserAPI.updateResume({
    userId,
    login: githubLogin,
    resume: targetResume
  });

  const cacheKey = getCacheKey(ctx);
  ctx.query.deleteKeys = [
    cacheKey(`resume.${result.hash}`)
  ];
  logger.info(`[RESUME:UPDATE][${githubLogin}]`);

  notify('slack').send({
    mq: ctx.mq,
    data: {
      type: 'resume',
      data: `Resume create or update by <https://github.com/${githubLogin}|${githubLogin}>`
    }
  });

  ctx.body = {
    result,
    success: true,
    message: ctx.__('messages.success.save'),
  };

  await next();
};

const patchResume = async (ctx, next) => {
  const { userId, githubLogin } = ctx.session;
  const getResult = await UserAPI.getResume({ userId });
  const resume = Object.assign({}, getResult ? getResult.resume : {});
  const { data } = ctx.request.body;

  for (const key in data) {
    const d = data[key];
    for (const k in d) {
      if (!resume[key]) resume[key] = {};
      resume[key][k] = d[k];
    }
  }

  const result = await UserAPI.updateResume({
    userId,
    resume,
    login: githubLogin,
  });

  const cacheKey = getCacheKey(ctx);
  ctx.query.deleteKeys = [
    cacheKey(`resume.${result.hash}`)
  ];

  ctx.body = {
    result,
    success: true,
  };

  await next();
};

const downloadResume = async (ctx) => {
  const { userId, githubLogin, locale } = ctx.session;

  const result = await UserAPI.getResumeInfo({ userId });
  const { template, resumeHash } = result;

  const findResult = await UserAPI.getResume({ userId });

  if (!findResult) {
    return ctx.body = {
      result: '',
      success: true,
      message: ctx.__('messages.error.emptyResume'),
    };
  }

  const updateTime = findResult.update_at || findResult.updated_at;
  const seconds = dateHelper.getSeconds(updateTime);

  const resumeUrl =
    `${URL}/resume/${resumeHash}?locale=${locale}&userId=${userId}&notrace=true`;

  notify('slack').send({
    mq: ctx.mq,
    data: {
      type: 'download',
      data: `【${githubLogin}:${resumeHash}】`
    }
  });

  logger.info(`[RESUME:DOWNLOAD][${resumeUrl}]`);
  ctx.cache.hincrby('resume', 'download', 1);

  let resultUrl = '';
  try {
    resultUrl = await Downloads.resume(resumeUrl, {
      folder: githubLogin,
      title: `${template}-${locale}-${seconds}-resume.pdf`
    });
    logger.info(`[RESUME:RENDERED][${resultUrl}]`);
  } catch (e) {
    logger.error(`[RESUME:DOWNLOAD:ERROR]${e}`);
  }

  ctx.body = {
    result: resultUrl,
    success: true
  };
};

const resumePage = async (ctx) => {
  const { resumeInfo } = ctx;
  const { login } = resumeInfo;
  const user = await UserAPI.getUser({ login });

  const { isMobile } = ctx.state;
  const { fromDownload, githubLogin } = ctx.session;
  const isAdmin = login === githubLogin;
  const { userName, userId } = user;

  if (isMobile) {
    await ctx.render('user/mobile/resume', {
      title: ctx.__('resumePage.title', userName),
      login,
      userId,
      fromDownload,
      user: {
        login,
        isAdmin,
      },
      hideFooter: true,
    });
  } else {
    await ctx.render('resume/share', {
      login,
      userId,
      fromDownload,
      hideFooter: true,
      title: ctx.__('resumePage.title', userName),
    });
  }
};

const getResumeByHash = async (ctx, next) => {
  const { hash } = ctx.query;
  const findResult = await UserAPI.getResume({ hash });

  let result = null;
  if (findResult) {
    result = findResult.resume;
    result.updateAt = findResult.updated_at;
  }

  ctx.body = {
    result,
    success: true,
  };

  await next();
};

const getResumeInfo = async (ctx) => {
  const { hash, userId } = ctx.query;
  const { locale } = ctx.session;
  const qs = {};
  if (hash) {
    qs.hash = hash;
  } else if (userId) {
    qs.userId = userId;
  } else {
    qs.userId = ctx.session.userId;
  }
  const resumeInfo = await UserAPI.getResumeInfo(qs);

  let result = null;
  if (resumeInfo) {
    result = getResumeShareStatus(resumeInfo, locale);
  }
  ctx.body = {
    result,
    success: true,
  };
};

const getShareRecords = async (ctx) => {
  const { userId, githubLogin } = ctx.session;

  const resumeInfo = await UserAPI.getResumeInfo({ userId });
  if (!resumeInfo) {
    return ctx.body = {
      success: true,
      result: {
        url: '',
        viewDevices: [],
        viewSources: [],
        pageViews: [],
        openShare: false
      }
    };
  }

  const records = await Records.getRecords(ctx.db, {
    login: githubLogin,
    type: 'resume'
  });
  const viewDevices = [];
  const viewSources = [];
  const pageViews = [];

  for (const record of records) {
    viewDevices.push(...record.viewDevices);
    viewSources.push(...record.viewSources);
    pageViews.push(...record.pageViews);
  }
  ctx.body = {
    success: true,
    result: {
      pageViews,
      viewDevices,
      viewSources,
      openShare: resumeInfo.openShare,
      url: `${githubLogin}/resume?locale=${ctx.session.locale}`,
    }
  };
};

const setResumeInfo = async (ctx) => {
  const { info } = ctx.request.body;
  const { userId, githubLogin } = ctx.session;

  const result = await UserAPI.setResumeInfo({
    info,
    userId,
    login: githubLogin
  });

  ctx.body = {
    result,
    success: true,
  };
};

export default {
  // ============
  getResume,
  setResume,
  patchResume,
  // ============
  resumePage,
  getResumeByHash,
  // ============
  downloadResume,
  getShareRecords,
  // ============
  getResumeInfo,
  setResumeInfo,
};
<|endoftext|>


<commit_before>define([
  'models/app',
  'data/search',
  'components/results',
  'components/searchForm',
  'components/recentSearches'
], function(app, SearchData, ResultsComponent, SearchFormComponent, RecentSearchesComponent) {
  return function(term) {
    var mainbar =   $('#mainbar').empty(),
        sidebar =   $('#sidebar').empty(),

        sf =        new SearchFormComponent().render().placeAt(mainbar),

        results =   new ResultsComponent({
                      searchData : SearchData
                    }).render().placeAt(mainbar),

        recent =    new RecentSearchesComponent({
                      searches : app.searches,
                      currentSearch : app.currentSearch
                    }).render().placeAt(sidebar);

    if (term) { update(term); }

    sf.on('search', function(term) {
      window.Router.navigate('/search/' + term, true);
    });

    app.currentSearch.on('change', function(s) {
      SearchData.term = s.get('term');
      SearchData.fetch();
    });

    function update(t) {
      if (t) {
        app.currentSearch.set('term', t);
      }
    }

    return {
      controller : 'search',
      update : function(params) {
        update(params.term);
      }
    };
  };
});
<commit_msg>make search results display on visit to #/search/term<commit_after>define([
  'models/app',
  'data/search',
  'components/results',
  'components/searchForm',
  'components/recentSearches'
], function(app, SearchData, ResultsComponent, SearchFormComponent, RecentSearchesComponent) {
  return function(term) {
    var mainbar =   $('#mainbar').empty(),
        sidebar =   $('#sidebar').empty(),

        sf =        new SearchFormComponent().render().placeAt(mainbar),

        results =   new ResultsComponent({
                      searchData : SearchData
                    }).render().placeAt(mainbar),

        recent =    new RecentSearchesComponent({
                      searches : app.searches,
                      currentSearch : app.currentSearch
                    }).render().placeAt(sidebar);

    if (term) { update(term); }

    sf.on('search', function(term) {
      window.Router.navigate('/search/' + term, true);
    });

    function update(t) {
      if (t) {
        app.currentSearch.set('term', t);
        app.currentSearch.trigger('change');
        SearchData.term = t;
        SearchData.fetch();
      }
    }

    return {
      controller : 'search',
      update : function(params) {
        update(params.term);
      }
    };
  };
});
<|endoftext|>


<commit_before>function initialize(io, ioClient, globals){
	var kerberos = null;

	if(globals.Kerberos != undefined && globals.Kerberos.length > 0)
		kerberos = ioClient.connect(globals.Kerberos, {reconnect: true});

	kerberos.on('connect', function(){
		console.log('Connected to Kerberos');
	});

	io.sockets.on('connection', function(socket){

		console.log('-' + socket.id);

		/// Welcome to the new client
		socket.emit('Welcome', {SocketId : socket.id});

		/*
		================
		Local functions
		*/

		/// Emit all cranes
		function sendHydraMessage(){
			socket.emit('Clapp.Hydra.Message', {Command : 'HydraCommand', Values : 1});
		}

		/*
		================
		Socket Intervals
		*/
		/// Emit every 5 seconds cranes
		setInterval(sendHydraMessage, 5000);

		/*
		================
		Templates for Socket.io
		*/
		/// Template for socket event
		//socket.on('', function(data){
		//  io.sockets.emit('Name', data);
		// socket.emit('ID', {Command: 'CommandID', Values:[{ID: socket.id}]});
		//});

	});

	console.log('Socket.io initialized');
}

exports.initialize = initialize;<commit_msg>commented validation<commit_after>function initialize(io, ioClient, globals){
	var kerberos = null;

	//if(globals.Kerberos != undefined && globals.Kerberos.length > 0)
		kerberos = ioClient.connect(globals.Kerberos, {reconnect: true});

	kerberos.on('connect', function(){
		console.log('Connected to Kerberos');
	});

	io.sockets.on('connection', function(socket){

		console.log('-' + socket.id);

		/// Welcome to the new client
		socket.emit('Welcome', {SocketId : socket.id});

		/*
		================
		Local functions
		*/

		/// Emit all cranes
		function sendHydraMessage(){
			socket.emit('Clapp.Hydra.Message', {Command : 'HydraCommand', Values : 1});
		}

		/*
		================
		Socket Intervals
		*/
		/// Emit every 5 seconds cranes
		setInterval(sendHydraMessage, 5000);

		/*
		================
		Templates for Socket.io
		*/
		/// Template for socket event
		//socket.on('', function(data){
		//  io.sockets.emit('Name', data);
		// socket.emit('ID', {Command: 'CommandID', Values:[{ID: socket.id}]});
		//});

	});

	console.log('Socket.io initialized');
}

exports.initialize = initialize;<|endoftext|>


<commit_before>( function($) {
	$.fn.activesearch = function(options) {
		var options = $.extend({
			'type' : 'GET',
			'dataType' : 'json',
			'contentType':'application/x-www-form-urlencoded;charset=UTF-8',
			'beforeSearch': function(){},
			'afterSearch': function(){},
			'error' : function(xhr, status, error) {
				console.log("Status: " + status);
				console.log("Error: " + error);
				console.log("XHR: " + xhr);
			}
		}, options);

		return this.each(function() {
			var $this = $(this);

			$this.bind("keyup.activesearch", function(event) {
				var value = $this.val();
				if(value && value.length > 0) { // TODO: cater for additional filters eg if val > 3 chars
					options.beforeSearch();
					$.ajax({ // TODO: cater for progress status
						url : options.url, // TODO: cater for pretty urls
						data : options.params(value),
						contentType: options.contentType,
						type : options.type,
						dataType : options.dataType,
						success : function(data, status, xhr) {
							options.success(data, status, xhr);
						},
						error : function(xhr, status, error) {
							options.error(xhr, status, error);
						},
						complete: options.afterSearch,
					});
				}
			});
		});
	}
}(jQuery));
<commit_msg>removed before and after todo<commit_after>( function($) {
	$.fn.activesearch = function(options) {
		var options = $.extend({
			'type' : 'GET',
			'dataType' : 'json',
			'contentType':'application/x-www-form-urlencoded;charset=UTF-8',
			'beforeSearch': function(){},
			'afterSearch': function(){},
			'error' : function(xhr, status, error) {
				console.log("Status: " + status);
				console.log("Error: " + error);
				console.log("XHR: " + xhr);
			}
		}, options);

		return this.each(function() {
			var $this = $(this);

			$this.bind("keyup.activesearch", function(event) {
				var value = $this.val();
				if(value && value.length > 0) { // TODO: cater for additional filters eg if val > 3 chars
					options.beforeSearch();
					$.ajax({
						url : options.url, // TODO: cater for pretty urls
						data : options.params(value),
						contentType: options.contentType,
						type : options.type,
						dataType : options.dataType,
						success : function(data, status, xhr) {
							options.success(data, status, xhr);
						},
						error : function(xhr, status, error) {
							options.error(xhr, status, error);
						},
						complete: options.afterSearch,
					});
				}
			});
		});
	}
}(jQuery));
<|endoftext|>