<commit_before>/**
* EmbedPlayer loader
*/
/**
* Default player module configuration
*/

mw.IA =
{
  VIDEO_WIDTH:640,
  VIDEO_HEIGHT:480,
  VIDEO_PLAYLIST_HEIGHT:80,

  video:true, //false means we are audio

  css:function(str)
  {
    var obj = document.createElement('style');
    obj.setAttribute('type', 'text/css');
    if (obj.styleSheet)
      obj.styleSheet.cssText = str; //MSIE
    else
      obj.appendChild(document.createTextNode(str)); // other browsers

    var headobj = document.getElementsByTagName("head")[0];
    headobj.appendChild(obj);
  },

  argin:function(theArgName, ary)
  {
    r = '';
    for (var i=0; i < ary.length; i++)
    {
      if (ary[i].slice(0,ary[i].indexOf('=')) == theArgName)
      {
        r = ary[i].slice(ary[i].indexOf('=')+1);
        break;
      }
    }
    return (r.length > 0 ? unescape(r).split(',') : '');
  },

  // parse a CGI arg
  arg:function(theArgName)
  {
    var ary = location.search.slice(1).split('&');
    mw.IA.log(ary);
    return this.argin(theArgName, ary);
  },

  // try to parse the identifier from the video and make the lower right icon
  // then go to the item's /details/ page
  detailsLink:function()
  {
    if (typeof(location.pathname)!='undefined'  &&
        location.pathname.length>0  &&
        location.pathname.match(/^\/details\//))
    {
      return '/details/'+location.pathname.replace(/^\/details\/([^\/]+).*$/,
                                                   '$1');
    }
    if (typeof(location.pathname)!='undefined'  &&
        location.pathname.length>0  &&
        location.pathname.match(/^\/embed\//))
    {
      return '/details/'+location.pathname.replace(/^\/embed\/([^\/]+).*$/,
                                                   '$1');
    }

    if (typeof(document.getElementsByTagName)!='undefined')
    {
      var els = document.getElementsByTagName('object');
      if (els  &&  els.length)
      {
        var i=0;
        for (i=0; i < els.length; i++)
        {
          var el = els[i];
          if (typeof(el.data)!='undefined')
          {
            var mat = el.data.match(/\.archive.org\/download\/([^\/]+)/);
            if (typeof(mat)!='undefined'  &&  mat  &&  mat.length>1)
            {
              return '/details/' + mat[1];
            }
          }
        }
      }
    }

    return '';
  },

  embedUrl:function()
  {
    return ('http://www.archive.org/embed/' +
            mw.IA.detailsLink().replace(/\/details\//,''));
  },

  embedCode:function()
  {
    return ('<iframe src="' +
            mw.escapeQuotesHTML( mw.IA.embedUrl() ) + '" ' +
            'width="' + mw.IA.VIDEO_WIDTH +'" ' +
            'height="' + mw.IA.VIDEO_HEIGHT + '" ' +
            'frameborder="0" ' +
            '>&lt/iframe>');
  },

  // Set up so that:
  //   - when "click to play" clicked, resize video window and playlist
  //   - we advance to the next clip (when 2+ present)
  newEmbedPlayerEvent:function(arg)
  {
    mw.IA.log('newEmbedPlayerEvent');

    if (typeof($('#iframeVidso').get(0)) != 'undefined')
    {
      mw.setConfig( {
        'EmbedPlayer.EnabledOptionsMenuItems':
        ['playerSelect','share','aboutPlayerLibrary']
      });
    }

    // Now put a nice looking "track number" in front of each playlist entry title
    $('div.playlistItem span.clipTitle').html(function(i,html) {
      return html.replace(/^(\d+)(.*)/, '$1$2');
    });

    var player = $('#mwplayer');
    if (!player)
      return;

    if (typeof(mw.IA.mrss)!='undefined')
    {
      if (mw.IA.video)
      {
        mw.IA.log('this is video!');
        mw.IA.video = true;

        player.unbind('play').bind('play', mw.IA.resize);

        // player.bind('pause', mw.IA.pause); //xxx hash not quite ready yet
        if (!mw.isMobileDevice())
        {
          player.bind('onCloseFullScreen', function(){ setTimeout(function() {
            mw.IA.resize(); }, 500); });
        }
      }
      else
      {
        mw.IA.log('this is audio!');
      }
    }
  },

  pause:function()
  {
    mw.IA.log('paused');

    // for hitting play:
    // location.hash = '#' + group['ORIG']; //xxxx hash not quite ready yet

    location.hash = '#' + // [get ORIG video file from playlist item and then matched back thru mrss variable etc.?]  +
      '/start=' + Math.round($('#mwplayer').get(0).currentTime * 10) / 10;
  },

  resize:function()
  {
    if (mw.isMobileDevice())
      return;

    if (!mw.IA.video)
      return;

    mw.IA.log('resize');

    var av=$('div.mv-player video, div.mv-player object, div.mv-player embed').parent().get(0);

    if (typeof(av)=='undefined'  &&  $('img.playerPoster').length > 0)
    {
      var wd = mw.IA.VIDEO_WIDTH / 2;
      var ht = mw.IA.VIDEO_HEIGHT / 2;
    }
    else
    {
      var wd = mw.IA.VIDEO_WIDTH;
      var ht = mw.IA.VIDEO_HEIGHT;

      if (typeof(av)!='undefined')
        av.resizePlayer({'width': wd, 'height':ht}, true);
    }

    $('#mwplayer_videolist').css('top', ht);

    $('#avplaydiv').css('width', wd);

    $('#mwplayer').css('width',  wd);
    $('#mwplayer').css('height', ht + mw.IA.VIDEO_PLAYLIST_HEIGHT);
  },

  log:function(str)
  {
    if ( typeof(console) !='undefined' )
      mw.log('      ---IA------------------------------>   '+str);
  },

  setup: function() {

    mw.IA.css("\n\
audio { z-index:666 !important; position:absolute !important; bottom:0px !important; } \n\
\n\
\n\
\n\
div#mwplayer_videolist { bottom:0px !important; right:0px !important; }\n\
div.playlistItem {\n\
  font-family:Lucida Grande;\n\
  margin:0px 5px 0px 5px !important;\n\
}\n\
div.playlist-title { display:none; }\n\
div.playlistItem img { display:none; }\n\
div.playlistItem span.clipTitle     { padding-left:15px; }\n\
div.playlistItem span.tn            { display:inline-block; width:25px; text-align:right; padding-right:5px; border-right:1px solid gray; }\n\
div.playlistItem div.clipDuration  { padding-right:20px; padding-top:1px; }\n\
div.movies div.playlistItem div.clipDuration  { display:none; }\n\
div.ui-state-active {\n\
  background-image:url(/images/orange_arrow.gif) !important;\n\
  background-position:10px 2px !important;\n\
  background-repeat:no-repeat !important;\n\
}\n\
\n\
.archive-icon {\n\
background-image:url('http://www.archive.org/images/logo-mw.png') !important;\n\
background-repeat:no-repeat;\n\
display: block;\n\
height: 12px;\n\
width: 12px;\n\
margin-left: 3px !important;\n\
}\n\
\n\
div.control-bar { -moz-border-radius:6px; -webkit-border-radius:6px; -khtml-border-radius:6px; border-radius:6px; }\n\
\n\
\n\
\n\
div.movies div.media-rss-video-list { background-image:url(/logos/hires/ia-tight-60x60-one-third-opacity.png); background-position:bottom; background-repeat:no-repeat; }\n\
div.maudio div.media-rss-video-list { background-image:url(/logos/hires/ia-tight-240x240-one-third-opacity.png); background-position:bottom; background-repeat:no-repeat; }\n\
div.maudio div.fullscreen-btn { display:none !important; }\n\
div.maudio img.playerPoster   { display:none; } \n\
div.maudio div.play-btn-large { display:none; } \n\
div.maudio div.media-rss-video-player { height:26px !important; } \n\
div.maudio div.mrss_mwplayer_0 { height:26px !important; } \n\
div.maudio div.mv-player  { height:26px !important; } \n\
div.maudio div.control-bar { display:block !important; } \n\
\n\
\n\
\n\
\n\
div.overlay-content { background-color:#666 !important; } \n\
div.overlay-content div h2 { background-color:transparent; }\n\
div.overlay-content        {\n\
  padding-top:0px !important; \n\
  border: 1px solid #666; \n\
  -moz-border-radius: 10px;\n\
  -webkit-border-radius:10px;\n\
  -khtml-border-radius:10px;\n\
  border-radius: 10px;\n\
}\n\
.mv-player .overlay-win textarea { height:60px !important; }\n\
");

    mw.setConfig( {
        // We want our video player to attribute something...
        "EmbedPlayer.AttributionButton" : true,

        'Mw.UserPreferenceExpireDays' : 90,

        // Our attribution button
        'EmbedPlayer.AttributionButton' : {
          'title' : 'Internet Archive',
          'href' : 'http://www.archive.org' + mw.IA.detailsLink(),
          'class' : 'archive-icon'
        },

        'imagesPath' : 'http://www/archive.org/images/', //xxxxxxx not working yet

        'Playlist.TitleLength': 38
      });

    if (!mw.isMobileDevice())
      mw.setConfig({'Playlist.ShowScrollButtons':false});

    // NOTE: keep this outside "mw.ready()" so that "click-to-play" does indeed
    // cause the newEmbedPlayerEvent() call
    $( mw ).bind('newEmbedPlayerEvent', mw.IA.newEmbedPlayerEvent);

    mw.ready(function(){
        var hash = unescape(location.hash);
        mw.IA.log("IA Player says mw.ready()" + hash);

        var star = (mw.IA.arg('start') ? parseFloat(mw.IA.arg('start')) : 0);
        if (!star)
        {
          // look for: /details/drake_saga1_shots/MVI_3986.AVI/start=13
          var a = location.pathname.split('/');
          star=(mw.IA.argin('start',a) ? parseFloat(mw.IA.argin('start',a)) : 0);
        }
        if (!star)
        {
          // look for: /details/drake_saga1_shots/MVI_3986.AVI#start=13
          var a = location.hash.slice(1).split('/');
          star=(mw.IA.argin('start',a) ? parseFloat(mw.IA.argin('start',a)) : 0);
        }
        if (star)
        {
          mw.IA.resize();
          var jplay = $('#mwplayer').get(0);
          var dura = jplay.duration;
          mw.IA.log(star+'s of '+dura+'s');

          jplay.currentTime = star;
          jplay.play();
        }
      });
  }
};

mw.IA.setup();
<commit_msg>comments, re-indents, etc (nothing substantitive)<commit_after>/**
* EmbedPlayer loader
*/
/**
* Default player module configuration
*/

mw.IA =
{
  VIDEO_WIDTH:640,
  VIDEO_HEIGHT:480,
  VIDEO_PLAYLIST_HEIGHT:80,

  video:true, //false means we are audio

  css:function(str)
  {
    var obj = document.createElement('style');
    obj.setAttribute('type', 'text/css');
    if (obj.styleSheet)
      obj.styleSheet.cssText = str; //MSIE
    else
      obj.appendChild(document.createTextNode(str)); // other browsers

    var headobj = document.getElementsByTagName("head")[0];
    headobj.appendChild(obj);
  },

  argin:function(theArgName, ary)
  {
    r = '';
    for (var i=0; i < ary.length; i++)
    {
      if (ary[i].slice(0,ary[i].indexOf('=')) == theArgName)
      {
        r = ary[i].slice(ary[i].indexOf('=')+1);
        break;
      }
    }
    return (r.length > 0 ? unescape(r).split(',') : '');
  },

  // parse a CGI arg
  arg:function(theArgName)
  {
    var ary = location.search.slice(1).split('&');
    mw.IA.log(ary);
    return this.argin(theArgName, ary);
  },

  // try to parse the identifier from the video and make the lower right icon
  // then go to the item's /details/ page
  detailsLink:function()
  {
    if (typeof(location.pathname)!='undefined'  &&
        location.pathname.length>0  &&
        location.pathname.match(/^\/details\//))
    {
      return '/details/'+location.pathname.replace(/^\/details\/([^\/]+).*$/,
                                                   '$1');
    }
    if (typeof(location.pathname)!='undefined'  &&
        location.pathname.length>0  &&
        location.pathname.match(/^\/embed\//))
    {
      return '/details/'+location.pathname.replace(/^\/embed\/([^\/]+).*$/,
                                                   '$1');
    }

    if (typeof(document.getElementsByTagName)!='undefined')
    {
      var els = document.getElementsByTagName('object');
      if (els  &&  els.length)
      {
        var i=0;
        for (i=0; i < els.length; i++)
        {
          var el = els[i];
          if (typeof(el.data)!='undefined')
          {
            var mat = el.data.match(/\.archive.org\/download\/([^\/]+)/);
            if (typeof(mat)!='undefined'  &&  mat  &&  mat.length>1)
            {
              return '/details/' + mat[1];
            }
          }
        }
      }
    }

    return '';
  },

  embedUrl:function()
  {
    return ('http://www.archive.org/embed/' +
            mw.IA.detailsLink().replace(/\/details\//,''));
  },

  embedCode:function()
  {
    return ('<iframe src="' +
            mw.escapeQuotesHTML( mw.IA.embedUrl() ) + '" ' +
            'width="' + mw.IA.VIDEO_WIDTH +'" ' +
            'height="' + mw.IA.VIDEO_HEIGHT + '" ' +
            'frameborder="0" ' +
            '>&lt/iframe>');
  },

  // Set up so that:
  //   - when "click to play" clicked, resize video window and playlist
  //   - we advance to the next clip (when 2+ present)
  newEmbedPlayerEvent:function(arg)
  {
    mw.IA.log('newEmbedPlayerEvent');

    if (typeof($('#iframeVidso').get(0)) != 'undefined')
    {
      mw.setConfig( {
        'EmbedPlayer.EnabledOptionsMenuItems':
        ['playerSelect','share','aboutPlayerLibrary']
      });
    }

    // Now put a nice looking "track number" in front of each playlist entry title
    $('div.playlistItem span.clipTitle').html(function(i,html) {
      return html.replace(/^(\d+)(.*)/, '$1$2');
    });

    var player = $('#mwplayer');
    if (!player)
      return;

    if (typeof(mw.IA.mrss)!='undefined')
    {
      if (mw.IA.video)
      {
        mw.IA.log('this is /details/ video!');
        mw.IA.video = true;

        player.unbind('play').bind('play', mw.IA.resize);

        // player.bind('pause', mw.IA.pause); //xxx hash not quite ready yet
        if (!mw.isMobileDevice())
        {
          player.bind('onCloseFullScreen', function(){ setTimeout(function() {
            mw.IA.resize(); }, 500); });
        }
      }
      else
      {
        mw.IA.log('this is /details/ audio!');
      }
    }
  },

  pause:function()
  {
    mw.IA.log('paused');

    // for hitting play:
    // location.hash = '#' + group['ORIG']; //xxxx hash not quite ready yet

    location.hash = '#' + // [get ORIG video file from playlist item and then matched back thru mrss variable etc.?]  +
      '/start=' + Math.round($('#mwplayer').get(0).currentTime * 10) / 10;
  },

  resize:function()
  {
    if (mw.isMobileDevice())
      return;

    if (!mw.IA.video)
      return;

    mw.IA.log('resize');

    var av=$('div.mv-player video, div.mv-player object, div.mv-player embed').parent().get(0);

    if (typeof(av)=='undefined'  &&  $('img.playerPoster').length > 0)
    {
      var wd = mw.IA.VIDEO_WIDTH / 2;
      var ht = mw.IA.VIDEO_HEIGHT / 2;
    }
    else
    {
      var wd = mw.IA.VIDEO_WIDTH;
      var ht = mw.IA.VIDEO_HEIGHT;

      if (typeof(av)!='undefined')
        av.resizePlayer({'width': wd, 'height':ht}, true);
    }

    $('#mwplayer_videolist').css('top', ht);

    $('#avplaydiv').css('width', wd);

    $('#mwplayer').css('width',  wd);
    $('#mwplayer').css('height', ht + mw.IA.VIDEO_PLAYLIST_HEIGHT);
  },

  log:function(str)
  {
    if ( typeof(console) !='undefined' )
      mw.log('      ---IA------------------------------>   '+str);
  },

  setup: function() {

    mw.IA.css("\n\
audio { z-index:666 !important; position:absolute !important; bottom:0px !important; } \n\
\n\
\n\
\n\
div#mwplayer_videolist { bottom:0px !important; right:0px !important; }\n\
div.playlistItem {\n\
  font-family:Lucida Grande;\n\
  margin:0px 5px 0px 5px !important;\n\
}\n\
div.playlist-title { display:none; }\n\
div.playlistItem img { display:none; }\n\
div.playlistItem span.clipTitle     { padding-left:15px; }\n\
div.playlistItem span.tn            { display:inline-block; width:25px; text-align:right; padding-right:5px; border-right:1px solid gray; }\n\
div.playlistItem div.clipDuration  { padding-right:20px; padding-top:1px; }\n\
div.movies div.playlistItem div.clipDuration  { display:none; }\n\
div.ui-state-active {\n\
  background-image:url(/images/orange_arrow.gif) !important;\n\
  background-position:10px 2px !important;\n\
  background-repeat:no-repeat !important;\n\
}\n\
\n\
.archive-icon {\n\
background-image:url('http://www.archive.org/images/logo-mw.png') !important;\n\
background-repeat:no-repeat;\n\
display: block;\n\
height: 12px;\n\
width: 12px;\n\
margin-left: 3px !important;\n\
}\n\
\n\
div.control-bar { -moz-border-radius:6px; -webkit-border-radius:6px; -khtml-border-radius:6px; border-radius:6px; }\n\
\n\
\n\
\n\
div.movies div.media-rss-video-list { background-image:url(/logos/hires/ia-tight-60x60-one-third-opacity.png); background-position:bottom; background-repeat:no-repeat; }\n\
div.maudio div.media-rss-video-list { background-image:url(/logos/hires/ia-tight-240x240-one-third-opacity.png); background-position:bottom; background-repeat:no-repeat; }\n\
div.maudio div.fullscreen-btn { display:none !important; }\n\
div.maudio img.playerPoster   { display:none; } \n\
div.maudio div.play-btn-large { display:none; } \n\
div.maudio div.media-rss-video-player { height:26px !important; } \n\
div.maudio div.mrss_mwplayer_0 { height:26px !important; } \n\
div.maudio div.mv-player  { height:26px !important; } \n\
div.maudio div.control-bar { display:block !important; } \n\
\n\
\n\
\n\
\n\
div.overlay-content { background-color:#666 !important; } \n\
div.overlay-content div h2 { background-color:transparent; }\n\
div.overlay-content        {\n\
  padding-top:0px !important; \n\
  border: 1px solid #666; \n\
  -moz-border-radius: 10px;\n\
  -webkit-border-radius:10px;\n\
  -khtml-border-radius:10px;\n\
  border-radius: 10px;\n\
}\n\
.mv-player .overlay-win textarea { height:60px !important; }\n\
");

    mw.setConfig( {
        // We want our video player to attribute something...
        "EmbedPlayer.AttributionButton" : true,

        'Mw.UserPreferenceExpireDays' : 90,

        // Our attribution button
        'EmbedPlayer.AttributionButton' : {
          'title' : 'Internet Archive',
          'href' : 'http://www.archive.org' + mw.IA.detailsLink(),
          'class' : 'archive-icon'
        },

        'imagesPath' : 'http://www/archive.org/images/', //xxxxxxx not working yet

        'Playlist.TitleLength': 38
      });

    if (!mw.isMobileDevice())
      mw.setConfig({'Playlist.ShowScrollButtons':false});

    // NOTE: keep this outside "mw.ready()" so that "click-to-play" does indeed
    // cause the newEmbedPlayerEvent() call
    $( mw ).bind('newEmbedPlayerEvent', mw.IA.newEmbedPlayerEvent);

    mw.ready(function(){
        var hash = unescape(location.hash);
        mw.IA.log("IA Player says mw.ready()" + hash);

        var star = (mw.IA.arg('start') ? parseFloat(mw.IA.arg('start')) : 0);
        if (!star)
        {
          // look for: /details/drake_saga1_shots/MVI_3986.AVI/start=13
          var a = location.pathname.split('/');
          star=(mw.IA.argin('start',a) ? parseFloat(mw.IA.argin('start',a)) : 0);
        }
        if (!star)
        {
          // look for: /details/drake_saga1_shots/MVI_3986.AVI#start=13
          var a = location.hash.slice(1).split('/');
          star=(mw.IA.argin('start',a) ? parseFloat(mw.IA.argin('start',a)) : 0);
        }
        if (star)
        {
          mw.IA.resize();
          var jplay = $('#mwplayer').get(0);
          var dura = jplay.duration;
          mw.IA.log(star+'s of '+dura+'s');

          jplay.currentTime = star;
          jplay.play();
        }
      });
  }
};

mw.IA.setup();
<|endoftext|>


<commit_before>function toggleLabel() {
  this.parentElement.classList.toggle('checked', this.checked);
}

function filterShows() {
  var filter = this.name,
      value = this.value,
      checked = this.checked;
  var selector = '#radioShows li.show[data-{filter}="{value}"]',
      tag = 'data-{filter}-is-hidden';
  selector = selector.replace('{filter}', filter);
  selector = selector.replace('{value}', value);
  tag = tag.replace('{filter}', filter);
  var shows = document.querySelectorAll(selector);
  Array.forEach(shows, function(show) {
    show.setAttribute(tag, !checked);
    if (show.getAttribute('data-producer-is-hidden') === "true" &&
        show.getAttribute('data-category-is-hidden') === "true") {
      show.style.display = 'none';
    } else {
      show.style.display = 'block';
    }
  });
}

var checkboxes = document.querySelectorAll('form li input');
Array.forEach(checkboxes, function(checkbox) {
  toggleLabel.apply(checkbox);
  filterShows.apply(checkbox);
  checkbox.onclick = function(event) {
    toggleLabel.apply(this);
    filterShows.apply(this);
  };
});
<commit_msg>Fixed #75: hide letter groups if there's no displayed show in them<commit_after>function toggleLabel() {
  this.parentElement.classList.toggle('checked', this.checked);
}

function filterShows() {
  var filter = this.name,
      value = this.value,
      checked = this.checked;
  var selector = '#radioShows li.show[data-{filter}="{value}"]',
      tag = 'data-{filter}-is-hidden';
  selector = selector.replace('{filter}', filter);
  selector = selector.replace('{value}', value);
  tag = tag.replace('{filter}', filter);
  var shows = document.querySelectorAll(selector);
  Array.forEach(shows, function(show) {
    show.setAttribute(tag, !checked);
    if (show.getAttribute('data-producer-is-hidden') === "true" &&
        show.getAttribute('data-category-is-hidden') === "true") {
      show.style.display = 'none';
    } else {
      show.style.display = 'block';
    }
  });
}

function filterShowGroups() {
  var showGroups = document.querySelectorAll('#radioShows li.radio.list');
  Array.forEach(showGroups, function(showGroup) {
    var shows = showGroup.querySelectorAll('li.show');
    var isHidden = Array.map(shows, function(show) {
      return (show.getAttribute('data-producer-is-hidden') === "true" &&
              show.getAttribute('data-category-is-hidden') === "true");
    });
    if (Array.indexOf(isHidden, false) === -1) {
      console.log("Should hide ", showGroup);
      showGroup.style.display = 'none';
    } else {
      showGroup.style.display = 'block';
    }
  });
}

var checkboxes = document.querySelectorAll('form li input');
Array.forEach(checkboxes, function(checkbox) {
  toggleLabel.apply(checkbox);
  filterShows.apply(checkbox);
  checkbox.onclick = function(event) {
    toggleLabel.apply(this);
    filterShows.apply(this);
    filterShowGroups.apply(this);
  };
});
filterShowGroups.apply();
<|endoftext|>


<commit_before>define(function(require) {
  /*
    DEPENDENCIES
   */

  var Locale = require('utils/locale');
  var Config = require('sunstone-config');
  var Sunstone = require('sunstone');
  var Humanize = require('utils/humanize');
  var Notifier = require('utils/notifier');
  var Graphs = require('utils/graphs');
  var StateActions = require('../utils/state-actions');
  var OpenNebulaVM = require('opennebula/vm');
  var SecGroupsCommon = require('tabs/secgroups-tab/utils/common');

  /*
    CONSTANTS
   */

  var TAB_ID = require('../tabId');
  var PANEL_ID = require('./network/panelId');
  var ATTACH_NIC_DIALOG_ID = require('../dialogs/attach-nic/dialogId');
  var RESOURCE = "VM"
  var XML_ROOT = "VM"

  /*
    CONSTRUCTOR
   */

  function Panel(info) {
    this.panelId = PANEL_ID;
    this.title = Locale.tr("Network");
    this.icon = "fa-globe";

    this.element = info[XML_ROOT];

    return this;
  };

  Panel.PANEL_ID = PANEL_ID;
  Panel.prototype.html = _html;
  Panel.prototype.setup = _setup;
  Panel.prototype.onShow = _onShow;
  Panel.prototype.getState = _getState;
  Panel.prototype.setState = _setState;

  return Panel;

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    var that = this;
    var html = '<form id="tab_network_form" vmid="' + that.element.ID + '" >\

\

\

\

\

\
                  	\
                  ' + Locale.tr("ID") + '	\
                  ' + Locale.tr("Network") + '	\
                  ' + Locale.tr("IP") + '	\
                  ' + Locale.tr("MAC") + '	\
                  ' + Locale.tr("IPv6 ULA") + '	\
                  ' + Locale.tr("IPv6 Global") + '	\
                  ' + Locale.tr("Actions") + '	\
                  '                 ;

    if (Config.isTabActionEnabled("vms-tab", "VM.attachnic")) {
      if (StateActions.enabledStateAction("VM.attachnic",
            that.element.STATE,
            that.element.LCM_STATE) &&
          OpenNebulaVM.isNICAttachSupported(that.element)) {
        html += '\
             <button id="attach_nic" class="button tiny success right radius" >' + Locale.tr("Attach nic") + '</button>'
      } else {
        html += '\
             <button id="attach_nic" class="button tiny success right radius" disabled="disabled">' + Locale.tr("Attach nic") + '</button>'
      }
    }

    html += '	\

\

\

\

\

\

\

'      ;

    var externalNetworkAttrs = OpenNebulaVM.retrieveExternalNetworkAttrs(that.element);
    if (!$.isEmptyObject(externalNetworkAttrs)) {
      html += '
' +
        '
' +
         '
' +
            '
' +
              '
' +
                 '' + Locale.tr("Network Monitoring Attributes") + '	' +
              '
' +
            '
' +
            '
';

      $.each(externalNetworkAttrs, function(key, value) {
        html += '
' +
           '' + key + '	' +
           '' + value + '	' +
          '
';
      });

      html += '
' +
            '
' +
          '
' +
        '
';
    }

    // Do not show statistics for not hypervisors that do not gather net data
    if (OpenNebulaVM.isNICGraphsSupported(that.element)) {
      html += '\

\

\

\

' + Locale.tr("NET RX") + '
\

\

\

\
                    \
                      \
                    \

\

\

\

\

\

\

\

\

\

' + Locale.tr("NET TX") + '
\

\

\

\
                    \
                      \
                    \

\

\

\

\

\

\

\

\

\

' + Locale.tr("NET DOWNLOAD SPEED") + '
\

\

\

\
                    \
                      \
                    \

\

\

\

\

\

\

\

\

\

' + Locale.tr("NET UPLOAD SPEED") + '
\

\

\

\
                    \
                      \
                    \

\

\

\

\

\

\

\

\
        </form>';
    }

    return html;
  }

  function _setup(context) {
    var that = this;

    var nics = []

    if ($.isArray(that.element.TEMPLATE.NIC))
        nics = that.element.TEMPLATE.NIC
    else if (!$.isEmptyObject(that.element.TEMPLATE.NIC))
        nics = [that.element.TEMPLATE.NIC]

    var nic_dt_data = [];
    if (nics.length) {
      var nic_dt_data = [];

      for (var i = 0; i < nics.length; i++) {
        var nic = nics[i];

        var actions;
        // Attach / Detach
        if (
           (
            that.element.STATE == OpenNebulaVM.STATES.ACTIVE) &&
           (
            that.element.LCM_STATE == OpenNebulaVM.LCM_STATES.HOTPLUG_NIC) &&
           (
            nic.ATTACH == "YES")
           ) {
          actions = Locale.tr("attach/detach in progress")
        } else {
          actions = '';

          if (Config.isTabActionEnabled("vms-tab", "VM.detachnic")) {
            if (StateActions.enabledStateAction("VM.detachnic", that.element.STATE, that.element.LCM_STATE)) {
              actions += '' + Locale.tr("Detach") + ''
            }
          }
        }

        var secgroups = [];

        var nic_secgroups = {};
        if (nic.SECURITY_GROUPS != undefined) {
          $.each(nic.SECURITY_GROUPS.split(","), function() {
            nic_secgroups[this] = true;
          });
        }

        if (that.element.TEMPLATE.SECURITY_GROUP_RULE != undefined) {
          $.each(that.element.TEMPLATE.SECURITY_GROUP_RULE, function() {
            if (nic_secgroups[this.SECURITY_GROUP_ID]) {
              secgroups.push(this);
            }
          });
        }

        nic_dt_data.push({
          NIC_ID : nic.NIC_ID,
          NETWORK : nic.NETWORK,
          IP : (nic.IP ? nic.IP : "--"),
          MAC : nic.MAC,
          IP6_ULA : (nic.IP6_ULA ? nic.IP6_ULA : "--"),
          IP6_GLOBAL : (nic.IP6_GLOBAL ? nic.IP6_GLOBAL : "--"),
          ACTIONS : actions,
          SECURITY_GROUP_RULES : secgroups
        });
      }
    }

    var nics_table = $("#tab_network_form .nics_table", context).DataTable({
      "bDeferRender": true,
      "data": nic_dt_data,
      "columns": [
        {
          "class":          'open-control',
          "orderable":      false,
          "data":           null,
          "defaultContent": ''
        },
        {"data": "NIC_ID",     "defaultContent": ""},
        {"data": "NETWORK",    "defaultContent": ""},
        {"data": "IP",         "defaultContent": ""},
        {"data": "MAC",        "defaultContent": ""},
        {"data": "IP6_ULA",    "defaultContent": ""},
        {"data": "IP6_GLOBAL", "defaultContent": ""},
        {"data": "ACTIONS",    "defaultContent": "", "orderable": false},
        {"defaultContent": "", "orderable": false}
      ],

      "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {

        if (aData.SECURITY_GROUP_RULES == undefined ||
            aData.SECURITY_GROUP_RULES.length == 0) {

          $("td.open-control", nRow).html("").removeClass('open-control');
        }

        $(nRow).attr("nic_id", aData.NIC_ID);
      }
    });

    $("#tab_network_form .nics_table", context).dataTable().fnSort([[1, 'asc']]);

    // Add event listener for opening and closing each NIC row details
    context.off('click', '#tab_network_form .nics_table td.open-control')
    context.on('click', '#tab_network_form .nics_table td.open-control', function () {
      var row = $(this).closest('table').DataTable().row($(this).closest('tr'));

      if (row.child.isShown()) {
        row.child.hide();
        $(this).children("span").addClass('fa-chevron-down');
        $(this).children("span").removeClass('fa-chevron-up');
      } else {
        var html = '
\

\

\

\
                    ' + Locale.tr("Security Group") + '	\
                    ' + Locale.tr("Protocol") + '	\
                    ' + Locale.tr("Type") + '	\
                    ' + Locale.tr("Range") + '	\
                    ' + Locale.tr("Network") + '	\
                    ' + Locale.tr("ICMP Type") + '	\

\

\

'            ;

        $.each(row.data().SECURITY_GROUP_RULES, function(index, elem) {
          var rule_st = SecGroupsCommon.sgRuleToSt(this);

          var new_tr = '
\
                  ' + this.SECURITY_GROUP_ID + '	\
                  ' + this.SECURITY_GROUP_NAME + '	\
                  ' + rule_st.PROTOCOL + '	\
                  ' + rule_st.RULE_TYPE + '	\
                  ' + rule_st.RANGE + '	\
                  ' + rule_st.NETWORK + '	\
                  ' + rule_st.ICMP_TYPE + '	\

'

          html += new_tr;
        });

        row.child(html).show();
        $(this).children("span").removeClass('fa-chevron-down');
        $(this).children("span").addClass('fa-chevron-up');
      }
    });

    if (Config.isTabActionEnabled("vms-tab", "VM.attachnic")) {
      context.off('click', '#attach_nic');
      context.on('click', '#attach_nic', function() {
        var dialog = Sunstone.getDialog(ATTACH_NIC_DIALOG_ID);
        dialog.setElement(that.element);
        dialog.show();
        return false;
      });
    }

    if (Config.isTabActionEnabled("vms-tab", "VM.detachnic")) {
      context.off('click', '.detachnic');
      context.on('click', '.detachnic', function() {
        var nic_id = $(this).parents('tr').attr('nic_id');
        Sunstone.runAction('VM.detachnic', that.element.ID, nic_id);
        return false;
      });
    }
  }

  function _onShow(context) {
    var that = this;
    if (OpenNebulaVM.isNICGraphsSupported(that.element)) {
      OpenNebulaVM.monitor({
        data: {
          id: that.element.ID,
          monitor: {
            monitor_resources : "MONITORING/NETTX,MONITORING/NETRX"
          }
        },
        success: function(req, response) {
          var vmGraphs = [
            {
              labels : Locale.tr("Network reception"),
              monitor_resources : "MONITORING/NETRX",
              humanize_figures : true,
              convert_from_bytes : true,
              div_graph : $("#vm_net_rx_graph")
            },
            {
              labels : Locale.tr("Network transmission"),
              monitor_resources : "MONITORING/NETTX",
              humanize_figures : true,
              convert_from_bytes : true,
              div_graph : $("#vm_net_tx_graph")
            },
            {
              labels : Locale.tr("Network reception speed"),
              monitor_resources : "MONITORING/NETRX",
              humanize_figures : true,
              convert_from_bytes : true,
              y_sufix : "B/s",
              derivative : true,
              div_graph : $("#vm_net_rx_speed_graph")
            },
            {
              labels : Locale.tr("Network transmission speed"),
              monitor_resources : "MONITORING/NETTX",
              humanize_figures : true,
              convert_from_bytes : true,
              y_sufix : "B/s",
              derivative : true,
              div_graph : $("#vm_net_tx_speed_graph")
            }
          ];

          for (var i = 0; i < vmGraphs.length; i++) {
            Graphs.plot(response, vmGraphs[i]);
          }
        },
        error: Notifier.onError
      });
    }
  }

  function _getState(context) {
    var state = {
      openNicsDetails : []
    };

    $.each($("#tab_network_form .nics_table .fa-chevron-up", context), function(){
      state.openNicsDetails.push($(this).closest("tr").attr("nic_id"));
    });

    return state;
  }

  function _setState(state, context) {
    var that = this;

    $.each(state["openNicsDetails"], function(){
      $('#tab_network_form .nics_table tr[nic_id="'+this+'"] td.open-control', context).click();
    });
  }
});
<commit_msg>bug #3787: Check if secgroups is defined for a nic<commit_after>define(function(require) {
  /*
    DEPENDENCIES
   */

  var Locale = require('utils/locale');
  var Config = require('sunstone-config');
  var Sunstone = require('sunstone');
  var Humanize = require('utils/humanize');
  var Notifier = require('utils/notifier');
  var Graphs = require('utils/graphs');
  var StateActions = require('../utils/state-actions');
  var OpenNebulaVM = require('opennebula/vm');
  var SecGroupsCommon = require('tabs/secgroups-tab/utils/common');

  /*
    CONSTANTS
   */

  var TAB_ID = require('../tabId');
  var PANEL_ID = require('./network/panelId');
  var ATTACH_NIC_DIALOG_ID = require('../dialogs/attach-nic/dialogId');
  var RESOURCE = "VM"
  var XML_ROOT = "VM"

  /*
    CONSTRUCTOR
   */

  function Panel(info) {
    this.panelId = PANEL_ID;
    this.title = Locale.tr("Network");
    this.icon = "fa-globe";

    this.element = info[XML_ROOT];

    return this;
  };

  Panel.PANEL_ID = PANEL_ID;
  Panel.prototype.html = _html;
  Panel.prototype.setup = _setup;
  Panel.prototype.onShow = _onShow;
  Panel.prototype.getState = _getState;
  Panel.prototype.setState = _setState;

  return Panel;

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    var that = this;
    var html = '<form id="tab_network_form" vmid="' + that.element.ID + '" >\

\

\

\

\

\
                  	\
                  ' + Locale.tr("ID") + '	\
                  ' + Locale.tr("Network") + '	\
                  ' + Locale.tr("IP") + '	\
                  ' + Locale.tr("MAC") + '	\
                  ' + Locale.tr("IPv6 ULA") + '	\
                  ' + Locale.tr("IPv6 Global") + '	\
                  ' + Locale.tr("Actions") + '	\
                  '                 ;

    if (Config.isTabActionEnabled("vms-tab", "VM.attachnic")) {
      if (StateActions.enabledStateAction("VM.attachnic",
            that.element.STATE,
            that.element.LCM_STATE) &&
          OpenNebulaVM.isNICAttachSupported(that.element)) {
        html += '\
             <button id="attach_nic" class="button tiny success right radius" >' + Locale.tr("Attach nic") + '</button>'
      } else {
        html += '\
             <button id="attach_nic" class="button tiny success right radius" disabled="disabled">' + Locale.tr("Attach nic") + '</button>'
      }
    }

    html += '	\

\

\

\

\

\

\

'      ;

    var externalNetworkAttrs = OpenNebulaVM.retrieveExternalNetworkAttrs(that.element);
    if (!$.isEmptyObject(externalNetworkAttrs)) {
      html += '
' +
        '
' +
         '
' +
            '
' +
              '
' +
                 '' + Locale.tr("Network Monitoring Attributes") + '	' +
              '
' +
            '
' +
            '
';

      $.each(externalNetworkAttrs, function(key, value) {
        html += '
' +
           '' + key + '	' +
           '' + value + '	' +
          '
';
      });

      html += '
' +
            '
' +
          '
' +
        '
';
    }

    // Do not show statistics for not hypervisors that do not gather net data
    if (OpenNebulaVM.isNICGraphsSupported(that.element)) {
      html += '\

\

\

\

' + Locale.tr("NET RX") + '
\

\

\

\
                    \
                      \
                    \

\

\

\

\

\

\

\

\

\

' + Locale.tr("NET TX") + '
\

\

\

\
                    \
                      \
                    \

\

\

\

\

\

\

\

\

\

' + Locale.tr("NET DOWNLOAD SPEED") + '
\

\

\

\
                    \
                      \
                    \

\

\

\

\

\

\

\

\

\

' + Locale.tr("NET UPLOAD SPEED") + '
\

\

\

\
                    \
                      \
                    \

\

\

\

\

\

\

\

\
        </form>';
    }

    return html;
  }

  function _setup(context) {
    var that = this;

    var nics = []

    if ($.isArray(that.element.TEMPLATE.NIC))
        nics = that.element.TEMPLATE.NIC
    else if (!$.isEmptyObject(that.element.TEMPLATE.NIC))
        nics = [that.element.TEMPLATE.NIC]

    var nic_dt_data = [];
    if (nics.length) {
      var nic_dt_data = [];

      for (var i = 0; i < nics.length; i++) {
        var nic = nics[i];

        var actions;
        // Attach / Detach
        if (
           (
            that.element.STATE == OpenNebulaVM.STATES.ACTIVE) &&
           (
            that.element.LCM_STATE == OpenNebulaVM.LCM_STATES.HOTPLUG_NIC) &&
           (
            nic.ATTACH == "YES")
           ) {
          actions = Locale.tr("attach/detach in progress")
        } else {
          actions = '';

          if (Config.isTabActionEnabled("vms-tab", "VM.detachnic")) {
            if (StateActions.enabledStateAction("VM.detachnic", that.element.STATE, that.element.LCM_STATE)) {
              actions += '' + Locale.tr("Detach") + ''
            }
          }
        }

        var secgroups = [];

        var nic_secgroups = {};
        if (!$.isEmptyObject(nic.SECURITY_GROUPS)) {
          $.each(nic.SECURITY_GROUPS.split(","), function() {
            nic_secgroups[this] = true;
          });
        }

        if (that.element.TEMPLATE.SECURITY_GROUP_RULE != undefined) {
          $.each(that.element.TEMPLATE.SECURITY_GROUP_RULE, function() {
            if (nic_secgroups[this.SECURITY_GROUP_ID]) {
              secgroups.push(this);
            }
          });
        }

        nic_dt_data.push({
          NIC_ID : nic.NIC_ID,
          NETWORK : nic.NETWORK,
          IP : (nic.IP ? nic.IP : "--"),
          MAC : nic.MAC,
          IP6_ULA : (nic.IP6_ULA ? nic.IP6_ULA : "--"),
          IP6_GLOBAL : (nic.IP6_GLOBAL ? nic.IP6_GLOBAL : "--"),
          ACTIONS : actions,
          SECURITY_GROUP_RULES : secgroups
        });
      }
    }

    var nics_table = $("#tab_network_form .nics_table", context).DataTable({
      "bDeferRender": true,
      "data": nic_dt_data,
      "columns": [
        {
          "class":          'open-control',
          "orderable":      false,
          "data":           null,
          "defaultContent": ''
        },
        {"data": "NIC_ID",     "defaultContent": ""},
        {"data": "NETWORK",    "defaultContent": ""},
        {"data": "IP",         "defaultContent": ""},
        {"data": "MAC",        "defaultContent": ""},
        {"data": "IP6_ULA",    "defaultContent": ""},
        {"data": "IP6_GLOBAL", "defaultContent": ""},
        {"data": "ACTIONS",    "defaultContent": "", "orderable": false},
        {"defaultContent": "", "orderable": false}
      ],

      "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {

        if (aData.SECURITY_GROUP_RULES == undefined ||
            aData.SECURITY_GROUP_RULES.length == 0) {

          $("td.open-control", nRow).html("").removeClass('open-control');
        }

        $(nRow).attr("nic_id", aData.NIC_ID);
      }
    });

    $("#tab_network_form .nics_table", context).dataTable().fnSort([[1, 'asc']]);

    // Add event listener for opening and closing each NIC row details
    context.off('click', '#tab_network_form .nics_table td.open-control')
    context.on('click', '#tab_network_form .nics_table td.open-control', function () {
      var row = $(this).closest('table').DataTable().row($(this).closest('tr'));

      if (row.child.isShown()) {
        row.child.hide();
        $(this).children("span").addClass('fa-chevron-down');
        $(this).children("span").removeClass('fa-chevron-up');
      } else {
        var html = '
\

\

\

\
                    ' + Locale.tr("Security Group") + '	\
                    ' + Locale.tr("Protocol") + '	\
                    ' + Locale.tr("Type") + '	\
                    ' + Locale.tr("Range") + '	\
                    ' + Locale.tr("Network") + '	\
                    ' + Locale.tr("ICMP Type") + '	\

\

\

'            ;

        $.each(row.data().SECURITY_GROUP_RULES, function(index, elem) {
          var rule_st = SecGroupsCommon.sgRuleToSt(this);

          var new_tr = '
\
                  ' + this.SECURITY_GROUP_ID + '	\
                  ' + this.SECURITY_GROUP_NAME + '	\
                  ' + rule_st.PROTOCOL + '	\
                  ' + rule_st.RULE_TYPE + '	\
                  ' + rule_st.RANGE + '	\
                  ' + rule_st.NETWORK + '	\
                  ' + rule_st.ICMP_TYPE + '	\

'

          html += new_tr;
        });

        row.child(html).show();
        $(this).children("span").removeClass('fa-chevron-down');
        $(this).children("span").addClass('fa-chevron-up');
      }
    });

    if (Config.isTabActionEnabled("vms-tab", "VM.attachnic")) {
      context.off('click', '#attach_nic');
      context.on('click', '#attach_nic', function() {
        var dialog = Sunstone.getDialog(ATTACH_NIC_DIALOG_ID);
        dialog.setElement(that.element);
        dialog.show();
        return false;
      });
    }

    if (Config.isTabActionEnabled("vms-tab", "VM.detachnic")) {
      context.off('click', '.detachnic');
      context.on('click', '.detachnic', function() {
        var nic_id = $(this).parents('tr').attr('nic_id');
        Sunstone.runAction('VM.detachnic', that.element.ID, nic_id);
        return false;
      });
    }
  }

  function _onShow(context) {
    var that = this;
    if (OpenNebulaVM.isNICGraphsSupported(that.element)) {
      OpenNebulaVM.monitor({
        data: {
          id: that.element.ID,
          monitor: {
            monitor_resources : "MONITORING/NETTX,MONITORING/NETRX"
          }
        },
        success: function(req, response) {
          var vmGraphs = [
            {
              labels : Locale.tr("Network reception"),
              monitor_resources : "MONITORING/NETRX",
              humanize_figures : true,
              convert_from_bytes : true,
              div_graph : $("#vm_net_rx_graph")
            },
            {
              labels : Locale.tr("Network transmission"),
              monitor_resources : "MONITORING/NETTX",
              humanize_figures : true,
              convert_from_bytes : true,
              div_graph : $("#vm_net_tx_graph")
            },
            {
              labels : Locale.tr("Network reception speed"),
              monitor_resources : "MONITORING/NETRX",
              humanize_figures : true,
              convert_from_bytes : true,
              y_sufix : "B/s",
              derivative : true,
              div_graph : $("#vm_net_rx_speed_graph")
            },
            {
              labels : Locale.tr("Network transmission speed"),
              monitor_resources : "MONITORING/NETTX",
              humanize_figures : true,
              convert_from_bytes : true,
              y_sufix : "B/s",
              derivative : true,
              div_graph : $("#vm_net_tx_speed_graph")
            }
          ];

          for (var i = 0; i < vmGraphs.length; i++) {
            Graphs.plot(response, vmGraphs[i]);
          }
        },
        error: Notifier.onError
      });
    }
  }

  function _getState(context) {
    var state = {
      openNicsDetails : []
    };

    $.each($("#tab_network_form .nics_table .fa-chevron-up", context), function(){
      state.openNicsDetails.push($(this).closest("tr").attr("nic_id"));
    });

    return state;
  }

  function _setState(state, context) {
    var that = this;

    $.each(state["openNicsDetails"], function(){
      $('#tab_network_form .nics_table tr[nic_id="'+this+'"] td.open-control', context).click();
    });
  }
});
<|endoftext|>


<commit_before>define(function (require) {
    'use strict';

    if (location.pathname.split('/').indexOf('search') !== -1) {
        var commonSearchBooleans = require('./../commonSearchBooleans');
        return function (options, onLoad) {
            $.extend(options, {
                header: MetkaJS.L10N.get('type.PUBLICATION.search'),
                fieldTitles: {
                    "publicationid": {
                        "title" : "Numero"
                    },
                    "publicationtitle": {
                        "title" : "Otsikko"
                    },
                    "state": {
                        "title" : "Tila"
                    }
                },
                content: [
                    commonSearchBooleans.column,
                    {
                        "type": "COLUMN",
                        "columns": 2,
                        "rows": [
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Julkaisu id-nro",
                                        "horizontal": true,
                                        "field": {
                                            "key": "publicationid"
                                        }
                                    },
                                    {
                                        "type": "CELL",
                                        "title": "/ Aineiston numerot",
                                        "horizontal": true,
                                        "field": {
                                            "key": "studies"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Julkaisun lisäyspvm",
                                        "horizontal": true,
                                        "field": {
                                            "key": "publicationfirstsaved"
                                        }
                                    },
                                    {
                                        "type": "CELL",
                                        "title": "Viimeisin muutospvm",
                                        "horizontal": true,
                                        "field": {
                                            "key": "savedAt"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Julkaisuvuosi",
                                        "horizontal": true,
                                        "field": {
                                            "key": "publicationyear"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Aineiston nimi",
                                        "horizontal": true,
                                        "colspan": 2,
                                        "field": {
                                            "key": "studyname"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Sarjan nimi",
                                        "horizontal": true,
                                        "colspan": 2,
                                        "field": {
                                            "key": "seriesname"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Tekijän sukunimi",
                                        "horizontal": true,
                                        "field": {
                                            "key": "lastname"
                                        }
                                    },
                                    {
                                        "type": "CELL",
                                        "title": "Etunimi",
                                        "horizontal": true,
                                        "field": {
                                            "key": "firstname"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Julkaisun otsikko",
                                        "horizontal": true,
                                        "colspan": 2,
                                        "field": {
                                            "key": "publicationtitle"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "relPubl",
                                        "horizontal": true,
                                        "colspan": 2,
                                        "field": {
                                            "key": "publicationrelpubl"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Julkaisun kieli",
                                        "horizontal": true,
                                        "colspan": 2,
                                        "field": {
                                            "key": "publicationlanguage"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Voiko julkaista",
                                        "horizontal": true,
                                        "colspan": 2,
                                        "field": {
                                            "key": "publicationpublic"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Käsitteljä",
                                        "horizontal": true,
                                        "colspan": 2,
                                        "field": {
                                            "key": "savedBy"
                                        }
                                    }
                                ]
                            }
                        ]
                    }
                ],
                buttons: [
                    require('./../searchButton')('/revision/ajax/search', function () {
                        var requestData = commonSearchBooleans.requestData(options, {
                            type: require('./../../metka').PAGE,
                            values: {}
                        });
                        [
                            'publicationfirstsaved',
                            'savedAt',
                            'publicationyear',
                            'studyname',
                            'seriesname',
                            'lastname',
                            'firstname',
                            'publicationtitle',
                            'publicationrelpubl',
                            'publicationlanguage',
                            'publicationpublic',
                            'savedBy'
                        ].forEach(function (field) {
                            requestData.values[field] = data(field).getByLang(options.defaultLang);
                        });
                        return requestData;
                    }, function (data) {
                        return data.rows;
                    }, function (result) {
                        return {
                            id: result.id,
                            no: result.no,
                            publicationid: result.values.publicationid,
                            publicationtitle: result.values.publicationtitle,
                            state: MetkaJS.L10N.get('search.result.state.{state}'.supplant(result))
                        };
                    }, {
                        publicationid: {
                            type: 'STRING'
                        },
                        publicationtitle: {
                            type: 'STRING'
                        },
                        state: {
                            type: 'STRING'
                        }
                    }, [
                        "publicationid",
                        "publicationtitle",
                        "state"
                    ],
                    null,
                    options),
                    /*{
                        "&title": {
                            "default": "Tyhjennä"
                        },
                        create: function () {
                            this.click(function () {
                                log('TODO: tyhjennä lomake')
                            });
                        }
                    },*/
                    {
                        "&title": {
                            "default": "Lisää uusi"
                        },
                        permissions: [
                            "canCreateRevision"
                        ],
                        create: function () {
                            this
                                .click(function () {
                                    require('./../server')('create', {
                                        data: JSON.stringify({
                                            type: 'PUBLICATION'
                                        }),
                                        success: function (response) {
                                            if (response.result === 'REVISION_CREATED') {
                                                require('./../assignUrl')('view', {
                                                    id: response.data.key.id,
                                                    no: response.data.key.no
                                                });
                                            }
                                        }
                                    });
                                });
                        }
                    }
                ],
                data: commonSearchBooleans.initialData({}),
                dataConf: {
                    "selectionLists": {
                        "yes_no": {
                            "key": "yes_no",
                            "type": "VALUE",
                            "options": [
                                {
                                    "&title": {
                                        "default": ""
                                    },
                                    "value": ''
                                },
                                {
                                    "&title": {
                                        "default": "Kyllä"
                                    },
                                    "value": 1
                                },
                                {
                                    "&title": {
                                        "default": "Ei"
                                    },
                                    "value": 0
                                }
                            ]
                        },
                        "langs": {
                            "key": "langs",
                            "type": "VALUE",
                            "options": [
                                {
                                    "&title": {
                                        "default": ""
                                    },
                                    "value": ''
                                },
                                {
                                    "&title": {
                                        "default": "Suomi"
                                    },
                                    "value": 'fi'
                                },
                                {
                                    "&title": {
                                        "default": "Englanti"
                                    },
                                    "value": 'en'
                                },
                                {
                                    "&title": {
                                        "default": "Ruotsi"
                                    },
                                    "value": 'sv'
                                },
                                {
                                    "&title": {
                                        "default": "Muu"
                                    },
                                    "value": 'other'
                                }
                            ]
                        },
                        "publicationannouncement_list": {
                            "key": "publicationannouncement_list",
                            "type": "VALUE",
                            "options": [
                                {
                                    "&title": {
                                        "default": "Ei tietoa"
                                    },
                                    "value": 0
                                },
                                {
                                    "&title": {
                                        "default": "Alkup. tutkija ilmoit."
                                    },
                                    "value": 1
                                },
                                {
                                    "&title": {
                                        "default": "Oma paikannus"
                                    },
                                    "value": 2
                                },
                                {
                                    "&title": {
                                        "default": "käyttäjä ilmoit."
                                    },
                                    "value": 3
                                }
                            ]
                        }
                    },
                    fields: {
                        publicationid: {
                            type: 'STRING'
                        },
                        studies: {
                            type: 'STRING'
                        },
                        publicationfirstsaved: {
                            type: 'DATE'
                        },
                        savedAt: {
                            type: 'DATE'
                        },
                        publicationyear: {
                            type: 'INTEGER'
                        },
                        studyname: {
                            type: 'STRING'
                        },
                        seriesname: {
                            type: 'SELECTION'
                        },
                        lastname: {
                            type: 'STRING'
                        },
                        firstname: {
                            type: 'STRING'
                        },
                        publicationtitle: {
                            type: 'STRING'
                        },
                        publicationrelpubl: {
                            type: 'STRING'
                        },
                        "publicationlanguage": {
                            "type": "SELECTION",
                            "selectionList": "langs"
                        },
                        "publicationpublic": {
                            "type": "SELECTION",
                            "selectionList": "yes_no"
                        },
                        savedBy: {
                            type: 'STRING'
                        }
                    }
                }
            });
            var data = require('./../data')(options);
            onLoad();
        };
    } else {
        return require('./defaults');
    }
});<commit_msg>Add missing publicationid & studies fields to search request<commit_after>define(function (require) {
    'use strict';

    if (location.pathname.split('/').indexOf('search') !== -1) {
        var commonSearchBooleans = require('./../commonSearchBooleans');
        return function (options, onLoad) {
            $.extend(options, {
                header: MetkaJS.L10N.get('type.PUBLICATION.search'),
                fieldTitles: {
                    "publicationid": {
                        "title" : "Numero"
                    },
                    "publicationtitle": {
                        "title" : "Otsikko"
                    },
                    "state": {
                        "title" : "Tila"
                    }
                },
                content: [
                    commonSearchBooleans.column,
                    {
                        "type": "COLUMN",
                        "columns": 2,
                        "rows": [
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Julkaisu id-nro",
                                        "horizontal": true,
                                        "field": {
                                            "key": "publicationid"
                                        }
                                    },
                                    {
                                        "type": "CELL",
                                        "title": "/ Aineiston numerot",
                                        "horizontal": true,
                                        "field": {
                                            "key": "studies"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Julkaisun lisäyspvm",
                                        "horizontal": true,
                                        "field": {
                                            "key": "publicationfirstsaved"
                                        }
                                    },
                                    {
                                        "type": "CELL",
                                        "title": "Viimeisin muutospvm",
                                        "horizontal": true,
                                        "field": {
                                            "key": "savedAt"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Julkaisuvuosi",
                                        "horizontal": true,
                                        "field": {
                                            "key": "publicationyear"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Aineiston nimi",
                                        "horizontal": true,
                                        "colspan": 2,
                                        "field": {
                                            "key": "studyname"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Sarjan nimi",
                                        "horizontal": true,
                                        "colspan": 2,
                                        "field": {
                                            "key": "seriesname"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Tekijän sukunimi",
                                        "horizontal": true,
                                        "field": {
                                            "key": "lastname"
                                        }
                                    },
                                    {
                                        "type": "CELL",
                                        "title": "Etunimi",
                                        "horizontal": true,
                                        "field": {
                                            "key": "firstname"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Julkaisun otsikko",
                                        "horizontal": true,
                                        "colspan": 2,
                                        "field": {
                                            "key": "publicationtitle"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "relPubl",
                                        "horizontal": true,
                                        "colspan": 2,
                                        "field": {
                                            "key": "publicationrelpubl"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Julkaisun kieli",
                                        "horizontal": true,
                                        "colspan": 2,
                                        "field": {
                                            "key": "publicationlanguage"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Voiko julkaista",
                                        "horizontal": true,
                                        "colspan": 2,
                                        "field": {
                                            "key": "publicationpublic"
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "ROW",
                                "cells": [
                                    {
                                        "type": "CELL",
                                        "title": "Käsitteljä",
                                        "horizontal": true,
                                        "colspan": 2,
                                        "field": {
                                            "key": "savedBy"
                                        }
                                    }
                                ]
                            }
                        ]
                    }
                ],
                buttons: [
                    require('./../searchButton')('/revision/ajax/search', function () {
                        var requestData = commonSearchBooleans.requestData(options, {
                            type: require('./../../metka').PAGE,
                            values: {}
                        });
                        [
                            'publicationid',
                            'studies',
                            'publicationfirstsaved',
                            'savedAt',
                            'publicationyear',
                            'studyname',
                            'seriesname',
                            'lastname',
                            'firstname',
                            'publicationtitle',
                            'publicationrelpubl',
                            'publicationlanguage',
                            'publicationpublic',
                            'savedBy'
                        ].forEach(function (field) {
                            requestData.values[field] = data(field).getByLang(options.defaultLang);
                        });
                        return requestData;
                    }, function (data) {
                        return data.rows;
                    }, function (result) {
                        return {
                            id: result.id,
                            no: result.no,
                            publicationid: result.values.publicationid,
                            publicationtitle: result.values.publicationtitle,
                            state: MetkaJS.L10N.get('search.result.state.{state}'.supplant(result))
                        };
                    }, {
                        publicationid: {
                            type: 'STRING'
                        },
                        publicationtitle: {
                            type: 'STRING'
                        },
                        state: {
                            type: 'STRING'
                        }
                    }, [
                        "publicationid",
                        "publicationtitle",
                        "state"
                    ],
                    null,
                    options),
                    /*{
                        "&title": {
                            "default": "Tyhjennä"
                        },
                        create: function () {
                            this.click(function () {
                                log('TODO: tyhjennä lomake')
                            });
                        }
                    },*/
                    {
                        "&title": {
                            "default": "Lisää uusi"
                        },
                        permissions: [
                            "canCreateRevision"
                        ],
                        create: function () {
                            this
                                .click(function () {
                                    require('./../server')('create', {
                                        data: JSON.stringify({
                                            type: 'PUBLICATION'
                                        }),
                                        success: function (response) {
                                            if (response.result === 'REVISION_CREATED') {
                                                require('./../assignUrl')('view', {
                                                    id: response.data.key.id,
                                                    no: response.data.key.no
                                                });
                                            }
                                        }
                                    });
                                });
                        }
                    }
                ],
                data: commonSearchBooleans.initialData({}),
                dataConf: {
                    "selectionLists": {
                        "yes_no": {
                            "key": "yes_no",
                            "type": "VALUE",
                            "options": [
                                {
                                    "&title": {
                                        "default": ""
                                    },
                                    "value": ''
                                },
                                {
                                    "&title": {
                                        "default": "Kyllä"
                                    },
                                    "value": 1
                                },
                                {
                                    "&title": {
                                        "default": "Ei"
                                    },
                                    "value": 0
                                }
                            ]
                        },
                        "langs": {
                            "key": "langs",
                            "type": "VALUE",
                            "options": [
                                {
                                    "&title": {
                                        "default": ""
                                    },
                                    "value": ''
                                },
                                {
                                    "&title": {
                                        "default": "Suomi"
                                    },
                                    "value": 'fi'
                                },
                                {
                                    "&title": {
                                        "default": "Englanti"
                                    },
                                    "value": 'en'
                                },
                                {
                                    "&title": {
                                        "default": "Ruotsi"
                                    },
                                    "value": 'sv'
                                },
                                {
                                    "&title": {
                                        "default": "Muu"
                                    },
                                    "value": 'other'
                                }
                            ]
                        },
                        "publicationannouncement_list": {
                            "key": "publicationannouncement_list",
                            "type": "VALUE",
                            "options": [
                                {
                                    "&title": {
                                        "default": "Ei tietoa"
                                    },
                                    "value": 0
                                },
                                {
                                    "&title": {
                                        "default": "Alkup. tutkija ilmoit."
                                    },
                                    "value": 1
                                },
                                {
                                    "&title": {
                                        "default": "Oma paikannus"
                                    },
                                    "value": 2
                                },
                                {
                                    "&title": {
                                        "default": "käyttäjä ilmoit."
                                    },
                                    "value": 3
                                }
                            ]
                        }
                    },
                    fields: {
                        publicationid: {
                            type: 'STRING'
                        },
                        studies: {
                            type: 'STRING'
                        },
                        publicationfirstsaved: {
                            type: 'DATE'
                        },
                        savedAt: {
                            type: 'DATE'
                        },
                        publicationyear: {
                            type: 'INTEGER'
                        },
                        studyname: {
                            type: 'STRING'
                        },
                        seriesname: {
                            type: 'SELECTION'
                        },
                        lastname: {
                            type: 'STRING'
                        },
                        firstname: {
                            type: 'STRING'
                        },
                        publicationtitle: {
                            type: 'STRING'
                        },
                        publicationrelpubl: {
                            type: 'STRING'
                        },
                        "publicationlanguage": {
                            "type": "SELECTION",
                            "selectionList": "langs"
                        },
                        "publicationpublic": {
                            "type": "SELECTION",
                            "selectionList": "yes_no"
                        },
                        savedBy: {
                            type: 'STRING'
                        }
                    }
                }
            });
            var data = require('./../data')(options);
            onLoad();
        };
    } else {
        return require('./defaults');
    }
});<|endoftext|>


<commit_before>'use strict';

const models = require("models"),
    HTTPStatus = require('http-status'),
    queryHelpers = require('utils/query-helpers'),
    objectValidator = require('utils/object-validator'),
    errors = require('errors'),
    <%_ if (locals.useMongo){_%>
    mongooseTypes = require('mongoose').Types,
    <%_}_%>
    <%_ if (locals.useSequelize) {_%>
    sequelize = require('utils/sequelize'),
    <%_}_%>
    _ = require('utils/lodash-ext');

/**
 * GET /api/v1/cats
 * @param req req
 * @param res res
 */

async function list(req, res) {
    //@f:off
    objectValidator.createValidator(req.query)
        .field('name')
            .optional()
            .isLength('Name search must be from 1 to 255 symbols.', {min: 1, max: 255})
        .field('bossName')
            .optional()
            .isLength('Boss name search must be from 1 to 255 symbols.', {min: 1, max: 255})
        .validate();
    //@f:on

    let pagingFilter = queryHelpers.createPaging(req.query),
        entitiesFilter = queryHelpers.createFilters(req.query, {
            name: 'startsWith',
            bossName: 'startsWith'
        }),
        <%_ if (locals.useMongo) {_%>
        sortCondition = {
            [req.query.sort || 'name']: req.query.direction || 'asc'
        };
        <%_}_%>
        <%_ if (locals.useSequelize) {_%>
        sortCondition = [[req.query.sort || 'name', req.query.direction ? req.query.direction.toUpperCase() : 'ASC']];
        <%_}_%>

    <%_ if (locals.useMongo) {_%>
    let [cats, totalCount] = [
        await models.Cat
            .find(entitiesFilter)
            .sort(sortCondition)
            .skip(pagingFilter.skip)
            .limit(pagingFilter.limit),
        await models.Cat
            .find(entitiesFilter).count()
    ];

    res.json({
        offset: pagingFilter.skip,
        limit: pagingFilter.limit,
        count: cats.length,
        totalCount: totalCount,
        cats: _.pickArrayExt(cats, ['id:_id', 'name', 'bossName', 'birthDate'])
    });
    <%_}_%>
    <%_ if (locals.useSequelize) {_%>
    let cats = await sequelize.transaction(async t => {
                // chain all your queries here. make sure you return them.
                return await models.Cat.findAll({
                    where: entitiesFilter,
                    order: sortCondition,
                    offset: pagingFilter.skip,
                    limit: pagingFilter.limit,
                    transaction: t
                });
            }
        );

    res.json({
        cats: _.pickArrayExt(cats, ['name', 'bossName', 'birthDate', 'id'])
    });
    <%_}_%>
}

/**
 * GET /api/v1/cats/:id
 * @param req req
 * @param res res
 */

async function get(req, res) {
    <%_ if (locals.useMongo) {_%>
    if (!mongooseTypes.ObjectId.isValid(req.params.id)) {
        throw new errors.NotFoundError('Cat is not found.', req.params.id);
    }

    let cat = await models.Cat.findById(req.params.id);

    if (!cat) {
        throw new errors.NotFoundError('Cat is not found.', req.params.id);
    }

    res.json({
        cat: _.pickExt(cat, ['id:_id', 'name', 'bossName', 'birthDate'])
    });
    <%_}_%>
    <%_ if (locals.useSequelize) {_%>
    let cat = await sequelize.transaction(async t => {
                // chain all your queries here. make sure you return them.
                return await models.Cat.find({
                    where: {
                        id : req.params.id
                    },
                    transaction: t
                });
            }
        );

    if (!cat) {
        throw new errors.NotFoundError('Cat is not found.', req.params.id);
    }

    res.json({
        cat: _.pickExt(cat, ['name', 'bossName', 'birthDate', 'id'])
    });
    <%_}_%>
}

/**
 * POST /api/v1/cats
 * @param req req
 * @param res res
 */

async function create(req, res) {
    //@f:off
    objectValidator.createValidator(req.body)
        .field('name')
            .isLength('Name must be from 1 to 255 symbols.', {min: 1, max: 255})
        .field('bossName')
            .optional()
            .isLength('Boss Name must be from 1 to 255 symbols.', {min: 1, max: 255})
        .field('birthDate')
            .optional()
            .isDate('Invalid date.')
        .validate();
    //@f:on

    //It was made in order to not create empty fields in database
    _.removeEmptyFieldsExt(req.body, 'bossName birthDate', undefined);

    <%_ if (locals.useMongo) {_%>
    let newCat = await models.Cat.create(req.body);
    <%_}_%>
    <%_ if (locals.useSequelize) {_%>
    let newCat = await sequelize.transaction(async t => {
            // chain all your queries here. make sure you return them.
            return await models.Cat.create(req.body, {transaction: t});
        }
    );
    <%_}_%>

    res.json({
        id: newCat.id
    });
}

/**
 * PUT /api/v1/cats/:id
 * @param req req
 * @param res res
 */

async function update(req, res) {
    //@f:off
    objectValidator.createValidator(req.body, {allowUndefined: true})
        .field('name')
            .isLength('Name must be from 1 to 255 symbols.', {min: 1, max: 255})
        .field('bossName')
            .optional()
            .isLength('Boss Name must be from 1 to 255 symbols.', {min: 1, max: 255})
        .field('birthDate')
            .optional()
            .isDate('Invalid date.')
        .validate();
    //@f:on

    <%_ if (locals.useMongo) {_%>
    if (!mongooseTypes.ObjectId.isValid(req.params.id)) {
        throw new errors.NotFoundError('Cat is not found.', req.params.id);
    }

    let cat = await models.Cat.findById(req.params.id);

    if (!cat) {
        throw new errors.NotFoundError('Cat is not found.', req.params.id);
    }

    //it was made in order to delete empty fields from database
    _.removeEmptyFieldsExt(req.body, 'bossName birthDate', undefined);

    _.assign(cat, req.body);

    await cat.save();
    <%_}_%>
    <%_ if (locals.useSequelize) {_%>
    await sequelize.transaction(async t => {
            // chain all your queries here. make sure you return them.
            let cat = await models.Cat.find({
                where: {
                    id : req.params.id
                },
                transaction: t
            });

            if (!cat) {
                throw new errors.NotFoundError('Cat is not found.', req.params.id);
            }

            //it was made in order to delete empty fields from database
            _.removeEmptyFieldsExt(req.body, 'bossName birthDate', null);

            _.assign(cat, req.body);

            await cat.save({transaction: t});
        }
    );
    <%_}_%>

    res.status(HTTPStatus.NO_CONTENT).send();
}

/**
 * DELETE /api/v1/cats/:id
 * @param req req
 * @param res res
 */

async function remove(req, res) {
    <%_ if (locals.useMongo) {_%>
    if (!mongooseTypes.ObjectId.isValid(req.params.id)) {
        throw new errors.NotFoundError('Cat is not found.', req.params.id);
    }

    let cat = await models.Cat.findById(req.params.id);

    if (!cat) {
        throw new errors.NotFoundError('Cat is not found.', req.params.id);
    }

    await cat.remove();
    <%_}_%>
    <%_ if (locals.useSequelize) {_%>
    await sequelize.transaction(async t => {
            // chain all your queries here. make sure you return them.
            let cat = await models.Cat.find({
                where: {
                    id: req.params.id
                },
                transaction: t
            });

            if (!cat) {
                throw new errors.NotFoundError('Cat is not found.', req.params.id);
            }

            await cat.destroy({transaction: t});
        }
    );
    <%_}_%>

    res.status(HTTPStatus.NO_CONTENT).send();
}

module.exports = {
    list: list,
    get: get,
    create: create,
    update: update,
    remove: remove
};<commit_msg>added additional information to response<commit_after>'use strict';

const models = require("models"),
    HTTPStatus = require('http-status'),
    queryHelpers = require('utils/query-helpers'),
    objectValidator = require('utils/object-validator'),
    errors = require('errors'),
    <%_ if (locals.useMongo){_%>
    mongooseTypes = require('mongoose').Types,
    <%_}_%>
    <%_ if (locals.useSequelize) {_%>
    sequelize = require('utils/sequelize'),
    <%_}_%>
    _ = require('utils/lodash-ext');

/**
 * GET /api/v1/cats
 * @param req req
 * @param res res
 */

async function list(req, res) {
    //@f:off
    objectValidator.createValidator(req.query)
        .field('name')
            .optional()
            .isLength('Name search must be from 1 to 255 symbols.', {min: 1, max: 255})
        .field('bossName')
            .optional()
            .isLength('Boss name search must be from 1 to 255 symbols.', {min: 1, max: 255})
        .validate();
    //@f:on

    let pagingFilter = queryHelpers.createPaging(req.query),
        entitiesFilter = queryHelpers.createFilters(req.query, {
            name: 'startsWith',
            bossName: 'startsWith'
        }),
        <%_ if (locals.useMongo) {_%>
        sortCondition = {
            [req.query.sort || 'name']: req.query.direction || 'asc'
        };
        <%_}_%>
        <%_ if (locals.useSequelize) {_%>
        sortCondition = [[req.query.sort || 'name', req.query.direction ? req.query.direction.toUpperCase() : 'ASC']];
        <%_}_%>

    <%_ if (locals.useMongo) {_%>
    let [cats, totalCount] = [
        await models.Cat
            .find(entitiesFilter)
            .sort(sortCondition)
            .skip(pagingFilter.skip)
            .limit(pagingFilter.limit),
        await models.Cat
            .find(entitiesFilter).count()
    ];

    res.json({
        offset: pagingFilter.skip,
        limit: pagingFilter.limit,
        count: cats.length,
        totalCount: totalCount,
        cats: _.pickArrayExt(cats, ['id:_id', 'name', 'bossName', 'birthDate'])
    });
    <%_}_%>
    <%_ if (locals.useSequelize) {_%>
    let cats = await sequelize.transaction(async t => {
                // chain all your queries here. make sure you return them.
                return await models.Cat.findAndCountAll({
                    where: entitiesFilter,
                    order: sortCondition,
                    offset: pagingFilter.skip,
                    limit: pagingFilter.limit,
                    transaction: t
                });
            }
        );

    res.json({
        offset: pagingFilter.skip,
        limit: pagingFilter.limit,
        count: cats.rows.length,
        totalCount: cats.count,
        cats: _.pickArrayExt(cats.rows, ['name', 'bossName', 'birthDate', 'id'])
    });
    <%_}_%>
}

/**
 * GET /api/v1/cats/:id
 * @param req req
 * @param res res
 */

async function get(req, res) {
    <%_ if (locals.useMongo) {_%>
    if (!mongooseTypes.ObjectId.isValid(req.params.id)) {
        throw new errors.NotFoundError('Cat is not found.', req.params.id);
    }

    let cat = await models.Cat.findById(req.params.id);

    if (!cat) {
        throw new errors.NotFoundError('Cat is not found.', req.params.id);
    }

    res.json({
        cat: _.pickExt(cat, ['id:_id', 'name', 'bossName', 'birthDate'])
    });
    <%_}_%>
    <%_ if (locals.useSequelize) {_%>
    let cat = await sequelize.transaction(async t => {
                // chain all your queries here. make sure you return them.
                return await models.Cat.find({
                    where: {
                        id : req.params.id
                    },
                    transaction: t
                });
            }
        );

    if (!cat) {
        throw new errors.NotFoundError('Cat is not found.', req.params.id);
    }

    res.json({
        cat: _.pickExt(cat, ['name', 'bossName', 'birthDate', 'id'])
    });
    <%_}_%>
}

/**
 * POST /api/v1/cats
 * @param req req
 * @param res res
 */

async function create(req, res) {
    //@f:off
    objectValidator.createValidator(req.body)
        .field('name')
            .isLength('Name must be from 1 to 255 symbols.', {min: 1, max: 255})
        .field('bossName')
            .optional()
            .isLength('Boss Name must be from 1 to 255 symbols.', {min: 1, max: 255})
        .field('birthDate')
            .optional()
            .isDate('Invalid date.')
        .validate();
    //@f:on

    //It was made in order to not create empty fields in database
    _.removeEmptyFieldsExt(req.body, 'bossName birthDate', undefined);

    <%_ if (locals.useMongo) {_%>
    let newCat = await models.Cat.create(req.body);
    <%_}_%>
    <%_ if (locals.useSequelize) {_%>
    let newCat = await sequelize.transaction(async t => {
            // chain all your queries here. make sure you return them.
            return await models.Cat.create(req.body, {transaction: t});
        }
    );
    <%_}_%>

    res.json({
        id: newCat.id
    });
}

/**
 * PUT /api/v1/cats/:id
 * @param req req
 * @param res res
 */

async function update(req, res) {
    //@f:off
    objectValidator.createValidator(req.body, {allowUndefined: true})
        .field('name')
            .isLength('Name must be from 1 to 255 symbols.', {min: 1, max: 255})
        .field('bossName')
            .optional()
            .isLength('Boss Name must be from 1 to 255 symbols.', {min: 1, max: 255})
        .field('birthDate')
            .optional()
            .isDate('Invalid date.')
        .validate();
    //@f:on

    <%_ if (locals.useMongo) {_%>
    if (!mongooseTypes.ObjectId.isValid(req.params.id)) {
        throw new errors.NotFoundError('Cat is not found.', req.params.id);
    }

    let cat = await models.Cat.findById(req.params.id);

    if (!cat) {
        throw new errors.NotFoundError('Cat is not found.', req.params.id);
    }

    //it was made in order to delete empty fields from database
    _.removeEmptyFieldsExt(req.body, 'bossName birthDate', undefined);

    _.assign(cat, req.body);

    await cat.save();
    <%_}_%>
    <%_ if (locals.useSequelize) {_%>
    await sequelize.transaction(async t => {
            // chain all your queries here. make sure you return them.
            let cat = await models.Cat.find({
                where: {
                    id : req.params.id
                },
                transaction: t
            });

            if (!cat) {
                throw new errors.NotFoundError('Cat is not found.', req.params.id);
            }

            //it was made in order to delete empty fields from database
            _.removeEmptyFieldsExt(req.body, 'bossName birthDate', null);

            _.assign(cat, req.body);

            await cat.save({transaction: t});
        }
    );
    <%_}_%>

    res.status(HTTPStatus.NO_CONTENT).send();
}

/**
 * DELETE /api/v1/cats/:id
 * @param req req
 * @param res res
 */

async function remove(req, res) {
    <%_ if (locals.useMongo) {_%>
    if (!mongooseTypes.ObjectId.isValid(req.params.id)) {
        throw new errors.NotFoundError('Cat is not found.', req.params.id);
    }

    let cat = await models.Cat.findById(req.params.id);

    if (!cat) {
        throw new errors.NotFoundError('Cat is not found.', req.params.id);
    }

    await cat.remove();
    <%_}_%>
    <%_ if (locals.useSequelize) {_%>
    await sequelize.transaction(async t => {
            // chain all your queries here. make sure you return them.
            let cat = await models.Cat.find({
                where: {
                    id: req.params.id
                },
                transaction: t
            });

            if (!cat) {
                throw new errors.NotFoundError('Cat is not found.', req.params.id);
            }

            await cat.destroy({transaction: t});
        }
    );
    <%_}_%>

    res.status(HTTPStatus.NO_CONTENT).send();
}

module.exports = {
    list: list,
    get: get,
    create: create,
    update: update,
    remove: remove
};<|endoftext|>