<commit_before>if (typeof(jQuery)=='undefined'){
  var script = document.createElement("script");
  script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
  script.onload = script.onreadystatechange = function(){
    // I18nT.init(jQuery);
  };
  document.body.appendChild( script );

}
jQuery(document).ready(function(jQuery) {
  I18nT.init(jQuery);
})

I18nT =
  {
  active:false,
  init:function(jQuery) {
    this.addGUI();
    this.parseAllAttributes();
    this.parseAllTextElements();
    this.bindClick();
    I18nT.jQuery = this.$ = jQuery;
    this.$('body').css('visibility','visible')
  },
  addGUI:function() {
    document.documentElement.innerHTML += '
<button id="i18nToggle">Toggle edit inline</button>'; //<button id="i18nToggleForm">Toggle edit form</button>

  },
  parseAllAttributes:function() {
    var matches = document.documentElement.innerHTML.match(/<[^<]*[",'](\{\%[^\}]*\%\})[",'].*>/gi);
    if (!matches) return;
    for (var i = 0; i < matches.length; i++) {
      var match = matches[i];
      var html = match.replace(/(\{\%[^\}]*\%\})/gi,'')
      document.documentElement.innerHTML = document.documentElement.innerHTML.replace(match, html)
}
    },
    parseAllTextElements:function() {
      var matches = document.documentElement.innerHTML.match(/(\{\%.*\%\})/gi)
      if (!matches) return;
      for (var i = 0; i < matches.length; i++) {
        var match = matches[i];
        var obj = this.parse(match);
        var html = this.decorateTextElement(obj);
        document.documentElement.innerHTML = document.documentElement.innerHTML.replace(match, html)
      }
    },
    parse:function(match) {
      console.log(match)
      var obj = match.replace(/{%/g,'{').replace(/%}/g,'}');
      if (obj.indexOf('class="translation_missing"') >= 0) {
        obj = obj.replace(/'value':'.*'/i, "'value':''")
      }

      obj = obj.replace(/'/g, '"');
      if (obj.indexOf('"value":"{')>-1){
        obj = obj.replace(/"value".*/i,'"value":""}');
      }

      obj = JSON.parse(obj);
      if (obj['KEY']){ obj.key = obj.KEY.toLowerCase() }
      if (obj['VALUE']){ obj.value = obj.VALUE }
      if (obj.value==''){ obj.value = obj.key}
      return obj;
    },

    decorateTextElement:function(obj) {
      var html = '' + obj.value + '';
      return html;
    },

    bindClick:function() {

      jQuery("#i18nToggle").click(function() {
        if (I18nT.active) {
          jQuery(".i18nized").removeClass("i18nized-active");
        }else{
          jQuery(".i18nized").addClass("i18nized-active");
        }
        I18nT.active = !I18nT.active;
      })
      jQuery(".i18nInput").live("blur",function(){
        endEditField(this)
      });
      jQuery(".i18nInput").live("keydown",function(e){
        if (e.keyCode==13){
          this.blur()
        }
      }) ;
      function endEditField(field){
        var val = jQuery(field).val();
        var key = jQuery(field).data('key')
        jQuery(field).parent().data("active",'false')
        jQuery(field).parent().html(jQuery(field).val())
        jQuery.get('/krembo_i18nizer/translator/update?key='+escape(key)+'&value='+escape(val));
      }
      jQuery(".i18nized").click(function(e) {
        if (!I18nT.active) {return;}
        e.preventDefault();
        if (jQuery(this).data("active")=="true") {return;}
        jQuery(this).data("active","true")
        var key = jQuery(this).data("i18n");
        var value = jQuery(this).text();
        jQuery(this).html('<input type="text" class="i18nInput" data-key="'+key+'" value="'+value+'" style="width:'+jQuery(this).width()+'px"/>');

      })
    }

}

<commit_msg>[FIX] support unicode values<commit_after>if (typeof(jQuery)=='undefined'){
  var script = document.createElement("script");
  script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
  script.onload = script.onreadystatechange = function(){
    // I18nT.init(jQuery);
  };
  document.body.appendChild( script );

}
jQuery(document).ready(function(jQuery) {
  I18nT.init(jQuery);
})

I18nT =
  {
  active:false,
  init:function(jQuery) {
    this.addGUI();
    this.parseAllAttributes();
    this.parseAllTextElements();
    this.bindClick();
    I18nT.jQuery = this.$ = jQuery;
    this.$('body').css('visibility','visible')
  },
  addGUI:function() {
    document.documentElement.innerHTML += '
<button id="i18nToggle">Toggle edit inline</button>'; //<button id="i18nToggleForm">Toggle edit form</button>

  },
  parseAllAttributes:function() {
    var matches = document.documentElement.innerHTML.match(/<[^<]*[",'](\{\%[^\}]*\%\})[",'].*>/gi);
    if (!matches) return;
    for (var i = 0; i < matches.length; i++) {
      var match = matches[i];
      var html = match.replace(/(\{\%[^\}]*\%\})/gi,'')
      document.documentElement.innerHTML = document.documentElement.innerHTML.replace(match, html)
}
    },
    parseAllTextElements:function() {
      var matches = document.documentElement.innerHTML.match(/(\{\%.*\%\})/gi)
      if (!matches) return;
      for (var i = 0; i < matches.length; i++) {
        var match = matches[i];
        var obj = this.parse(match);
        var html = this.decorateTextElement(obj);
        document.documentElement.innerHTML = document.documentElement.innerHTML.replace(match, html)
      }
    },
    parse:function(match) {
      console.log(match)
      var obj = match.replace(/{%/g,'{').replace(/%}/g,'}');
      if (obj.indexOf('class="translation_missing"') >= 0) {
        obj = obj.replace(/'value':'.*'/i, "'value':''")
      }

      obj = obj.replace(/'/g, '"');
      if (obj.indexOf('"value":"{')>-1){
        obj = obj.replace(/"value".*/i,'"value":""}');
      }

      obj = JSON.parse(obj);
      if (obj['KEY']){ obj.key = obj.KEY.toLowerCase() }
      if (obj['VALUE']){ obj.value = obj.VALUE }
      if (obj.value==''){ obj.value = obj.key}
      return obj;
    },

    decorateTextElement:function(obj) {
      var html = '' + obj.value + '';
      return html;
    },

    bindClick:function() {

      jQuery("#i18nToggle").click(function() {
        if (I18nT.active) {
          jQuery(".i18nized").removeClass("i18nized-active");
        }else{
          jQuery(".i18nized").addClass("i18nized-active");
        }
        I18nT.active = !I18nT.active;
      })
      jQuery(".i18nInput").live("blur",function(){
        endEditField(this)
      });
      jQuery(".i18nInput").live("keydown",function(e){
        if (e.keyCode==13){
          this.blur()
        }
      }) ;
      function endEditField(field){
        var val = jQuery(field).val();
        var key = jQuery(field).data('key')
        jQuery(field).parent().data("active",'false')
        jQuery(field).parent().html(jQuery(field).val())
        jQuery.get('/krembo_i18nizer/translator/update?key='+encodeURI(key)+'&value='+encodeURI(val));
      }
      jQuery(".i18nized").click(function(e) {
        if (!I18nT.active) {return;}
        e.preventDefault();
        if (jQuery(this).data("active")=="true") {return;}
        jQuery(this).data("active","true")
        var key = jQuery(this).data("i18n");
        var value = jQuery(this).text();
        jQuery(this).html('<input type="text" class="i18nInput" data-key="'+key+'" value="'+value+'" style="width:'+jQuery(this).width()+'px"/>');

      })
    }

}

<|endoftext|>


<commit_before>'use strict';

angular.module('gpConnect')
  .value("content", {
    "gpconnect_title": "GP Connect 1.2.0 - Demonstrator",
    "gpconnect_privacy": "Warning! This is a test server. Do not store any information here that contains personal health information or any other confidential information. This server will be regularly purged and reloaded with fixed test data."
  });
<commit_msg>Update content.js<commit_after>'use strict';

angular.module('gpConnect')
  .value("content", {
    "gpconnect_title": "GP Connect 1.2.1 - Demonstrator",
    "gpconnect_privacy": "Warning! This is a test server. Do not store any information here that contains personal health information or any other confidential information. This server will be regularly purged and reloaded with fixed test data."
  });
<|endoftext|>


<commit_before>'use strict';
let fs = require('fs');
let async = require('async');

const fullURL   = /http[s]?:\/\/codepen\.io\/(.*)\/(.*)\/(.*)/;
const domainURL = /codepen\.io\/(.*)\/(.*)\/(.*)/;
const penURL    = /\/(.*)\/(.*)\/(.*)/;

const normalURL = /htt[s]?:\/\/(.*)/;

module.exports = {

  parseUrl(url) {
    if (fullURL.exec(url) !== null) {
      return url;
    } else if (domainURL.exec(url) !== null){
      return `http://${url}`;
    } else if (penURL.exec(url) !== null) {
      return `http://codepen.io${url}`;
    } else {
      throw new Error('Invalid URL');
    }
  },

  createDirectoryIfMissing(destination, callback) {
    fs.readdir(destination, (err) => {
      if (!err) return callback();
      fs.mkdir(destination, (err) => {
        callback(err);
      });
    });
  },

  parseScriptUrl(url) {
    if (normalURL.exec(url) === null)
      return `http:${url}`;
    else
      return url;
  },

  createScriptTag(result) {
    let scripts = "";
    result.deps.resources.forEach((d) => {
      d.url = this.parseScriptUrl(d.url);
      if (d.resource_type === 'js')
        scripts = `${scripts}\n \
                    <script src=${d.url}></script>`;
    });
    return scripts;
  },

  createIndexHtmlFile(file, result, fn) {
    async.parallel([
      (callback) => fs.readFile(__dirname + '/template/head01.html', callback),
      (callback) => fs.readFile(__dirname + '/template/head02.html', callback),
      (callback) => fs.readFile(__dirname + '/template/foot.html', callback)
    ], (err, data) => {
      if(err) return fn(err);
      this.removeFileIfExists(file, (err) => {
        if (err) return fn(err);
        fs.appendFileSync(file, data[0]);
        fs.appendFileSync(file, this.createScriptTag(result));
        fs.appendFileSync(file, data[1]);
        fs.appendFileSync(file, result.html);
        fs.appendFileSync(file, data[2]);
        fn(null, file);
      });
    });
  },

  createFile(file, data, fn) {
    this.removeFileIfExists(file, (err) => {
      if (err) return fn(err);
      fs.appendFile(file, data, fn);
    });
  },

  removeFileIfExists(file, fn) {
    fs.stat(file, (err) => {
      if(!err) {
        fs.unlink(file, fn);
      } else if (err.code !== "ENOENT") {
        fn(err);
      } else {
        fn(null);
      }
    });
  },

  defaultOptions : {
    targetFiles : ['html', 'css', 'js'],
    includeDependencies : true
  }

};
<commit_msg>fix tests<commit_after>'use strict';
let fs = require('fs');
let async = require('async');

const fullURL   = /http[s]?:\/\/codepen\.io\/(.*)\/(.*)\/(.*)/;
const domainURL = /codepen\.io\/(.*)\/(.*)\/(.*)/;
const penURL    = /\/(.*)\/(.*)\/(.*)/;

const normalURL = /htt[s]?:\/\/(.*)/;

module.exports = {

  parseUrl(url) {
    if (fullURL.exec(url) !== null) {
      return url;
    } else if (domainURL.exec(url) !== null){
      return `http://${url}`;
    } else if (penURL.exec(url) !== null) {
      return `http://codepen.io${url}`;
    } else {
      throw new Error('Invalid URL');
    }
  },

  createDirectoryIfMissing(destination, callback) {
    fs.readdir(destination, (err) => {
      if (!err) return callback();
      fs.mkdir(destination, (err) => {
        callback(err);
      });
    });
  },

  parseScriptUrl(url) {
    if (normalURL.exec(url) === null)
      return `http:${url}`;
    else
      return url;
  },

  createScriptTag(result) {
    let scripts = "";
    if (result.deps) {
      result.deps.resources.forEach((d) => {
        d.url = this.parseScriptUrl(d.url);
        if (d.resource_type === 'js')
        scripts = `${scripts}\n \
        <script src=${d.url}></script>`;
      });
    }
    return scripts;
  },

  createIndexHtmlFile(file, result, fn) {
    async.parallel([
      (callback) => fs.readFile(__dirname + '/template/head01.html', callback),
      (callback) => fs.readFile(__dirname + '/template/head02.html', callback),
      (callback) => fs.readFile(__dirname + '/template/foot.html', callback)
    ], (err, data) => {
      if(err) return fn(err);
      this.removeFileIfExists(file, (err) => {
        if (err) return fn(err);
        fs.appendFileSync(file, data[0]);
        fs.appendFileSync(file, this.createScriptTag(result));
        fs.appendFileSync(file, data[1]);
        fs.appendFileSync(file, result.html);
        fs.appendFileSync(file, data[2]);
        fn(null, file);
      });
    });
  },

  createFile(file, data, fn) {
    this.removeFileIfExists(file, (err) => {
      if (err) return fn(err);
      fs.appendFile(file, data, fn);
    });
  },

  removeFileIfExists(file, fn) {
    fs.stat(file, (err) => {
      if(!err) {
        fs.unlink(file, fn);
      } else if (err.code !== "ENOENT") {
        fn(err);
      } else {
        fn(null);
      }
    });
  },

  defaultOptions : {
    targetFiles : ['html', 'css', 'js'],
    includeDependencies : true
  }

};
<|endoftext|>


<commit_before>/*
* Copyright 2017 the Isard-vdi project authors:
*      Josep Maria Viñolas Auquer
*      Alberto Larraz Dalmases
* License: AGPLv3
*/

$(document).ready(function() {
    $('.btn-scheduler').on( 'click', function () {
        $('#modalScheduler').modal({
				backdrop: 'static',
				keyboard: false
        }).modal('show');
    });

    $("#modalScheduler #send").on('click', function(e){
            var form = $('#modalAddScheduler');
            data=$('#modalAddScheduler').serializeObject();
            api.ajax('/scheduler/system/'+data["kind"]+"/"+data["action"]+"/"+data["hour"]+"/"+data["minute"],'POST',{}).done(function(data) {
            });
            $("#modalAddScheduler")[0].reset();
            $("#modalScheduler").modal('hide');
        });

    $('.btn-backup').on( 'click', function () {
				new PNotify({
						title: 'Create backup',
							text: "Do you really want to create a new backup?",
							hide: false,
							opacity: 0.9,
							confirm: {confirm: true},
							buttons: {closer: false,sticker: false},
							history: {history: false},
							addclass: 'pnotify-center'
						}).get().on('pnotify.confirm', function() {
                            api.ajax('/api/v3/backup','POST',{}).done(function(data) {
                            });
						}).on('pnotify.cancel', function() {
				});
    });

    $('.btn-backups-upload').on( 'click', function () {
			$('#modalUpload').modal({
				backdrop: 'static',
				keyboard: false
			}).modal('show');
        });

    backups_table=$('#table-backups').DataTable({
			"ajax": {
				"url": "/api/v3/admin/table/backups",
                "contentType": "application/json",
                "type": 'POST',
                "data": function(d){return JSON.stringify({'order':'filename'})}
			},
            "sAjaxDataProp": "",
			"language": {
				"loadingRecords": 'Loading...'
			},
            "bLengthChange": false,
            "bFilter": false,
			"rowId": "id",
			"deferRender": true,
			"columns": [
				{ "data": "when"},
				{ "data": "status"},
                { "data": "version", "defaultContent": "Unknown"},
				{
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "width": "88px",
                "defaultContent": '<button id="btn-backups-delete" class="btn btn-xs" type="button"  data-placement="top"></button> \
                                   <button id="btn-backups-restore" class="btn btn-xs" type="button"  data-placement="top"></button> \
                                   <button id="btn-backups-info" class="btn btn-xs" type="button"  data-placement="top"></button> \
                                   <button id="btn-backups-download" class="btn btn-xs" type="button"  data-placement="top"></button>'
				},
                ],
			 "order": [[0, 'desc']],
			 "columnDefs": [ {
							"targets": 0,
							"render": function ( data, type, full, meta ) {
                              if ( type === 'display' || type === 'filter' ) {
                                    return moment.unix(full.when).fromNow();
                              }
                              return data;
							}}]
    } );

     $('#table-backups').find(' tbody').on( 'click', 'button', function () {
        var data = backups_table.row( $(this).parents('tr') ).data();
        if($(this).attr('id')=='btn-backups-delete'){
				new PNotify({
						title: 'Delete backup',
							text: "Do you really want to delete backup on date "+moment.unix(data.when).fromNow()+"?",
							hide: false,
							opacity: 0.9,
							confirm: {confirm: true},
							buttons: {closer: false,sticker: false},
							history: {history: false},
							addclass: 'pnotify-center'
						}).get().on('pnotify.confirm', function() {
                            api.ajax('/api/v3/backup/'+data["id"],'DELETE',{}).done(function(data) {
                            });
						}).on('pnotify.cancel', function() {
				});
        }
        if($(this).attr('id')=='btn-backups-restore'){
				new PNotify({
						title: 'Restore backup',
							text: "Do you really want to restore backup from file "+data.filename+"?",
							hide: false,
							opacity: 0.9,
							confirm: {confirm: true},
							buttons: {closer: false,sticker: false},
							history: {history: false},
							addclass: 'pnotify-center'
						}).get().on('pnotify.confirm', function() {
                            api.ajax('/api/v3/backup/restore/'+data["id"],'PUT',{}).done(function(data) {
                            });
						}).on('pnotify.cancel', function() {
				});
        }
        if($(this).attr('id')=='btn-backups-download'){
						var url = '/api/v3/backup/download/'+data['id']+'?jwt='+localStorage.getItem("token");
						var anchor = document.createElement('a');
							anchor.setAttribute('href', url);
							anchor.setAttribute('download', data['filename']);
						var ev = document.createEvent("MouseEvents");
							ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
						anchor.dispatchEvent(ev);
        }
        if($(this).attr('id')=='btn-backups-info'){
						api.ajax('/api/v3/backup/'+data["id"],'GET',{}).done(function(data) {
                            $("#backup-tables").find('option').remove();
                            $("#backup-tables").append('<option value="">Choose..</option>');
                            $.each(data.data,function(key, value)
                            {
                                if(value>0){
                                    $("#backup-tables").append('<option value=' + key + '>' + key+' ('+value+' items)' + '</option>');
                                }
                            });
                            $('#backup-id').val(data['id'])
                            $('#modalBackupInfo').modal({
                                backdrop: 'static',
                                keyboard: false
                            }).modal('show');
                        });
        }
    });

    $('#backup-tables').on('change', function (e) {
			var valueSelected = this.value;
            // var backup_id = +'/'+$('#backup-id').val()
			api.ajax('/api/v3/backup/table/'+valueSelected,'GET',{}).done(function(data) {
				if ( $.fn.dataTable.isDataTable( '#backup-table-detail' ) ) {
					backup_table_detail.clear().rows.add(data).draw()
				}else{

					backup_table_detail=$('#backup-table-detail').DataTable( {
						data: data,
						rowId: 'id',
						//~ language: {
							//~ "loadingRecords": 'Loading...'
						//~ },
						columns: [
							{ "data": "id", "width": "88px"},
							{ "data": "description", "width": "88px", "defaultContent": ""},
							{
							"className":      'actions-control',
							"orderable":      false,
							"data":           null,
							"width": "88px",
							"defaultContent": '<button class="btn btn-xs btn-individual-restore" type="button"  data-placement="top"></button>'
							},
							],
						 "order": [[0, 'asc']],
						 "columnDefs": [ {
										"targets": 2,
										"render": function ( data, type, full, meta ) {
										  if(full.new_backup_data){
											  return '<button class="btn btn-xs btn-individual-restore" type="button"  data-placement="top">New</button>';
										  }else{
											  return '<button class="btn btn-xs btn-individual-restore" type="button"  data-placement="top">Exists</button>'
										  }
										}}]
					} );
				}
								$('.btn-individual-restore').on('click', function (e){
									data=backup_table_detail.row( $(this).parents('tr') ).data();
									table=$('#backup-tables').val()
									new PNotify({
											title: 'Restore data',
												text: "Do you really want to restore row "+data.id+" to table "+table+"?",
												hide: false,
												opacity: 0.9,
												confirm: {confirm: true},
												buttons: {closer: false,sticker: false},
												history: {history: false},
												addclass: 'pnotify-center'
											}).get().on('pnotify.confirm', function() {
												api.ajax('/api/v3/backup/restore/table/'+table,'PUT',{'data':data,}).done(function(data1) {
													api.ajax('/api/v3/backup/table/'+table,'GET',{}).done(function(data) {
														dtUpdateInsert(backup_table_detail,data,false);
													});
												});
											}).on('pnotify.cancel', function() {
									});
								});
			});
		});

        scheduler_table=$('#table-scheduler').DataTable({
            "ajax": {
                "url": "/admin/table/scheduler_jobs",
                "data": function(d){return JSON.stringify({'order_by':'date','pluck':['id','name','kind','next_run_time'],'id':'system','index':'type'})},
                "contentType": "application/json",
                "type": 'POST',
            },
            "sAjaxDataProp": "",
			"language": {
				"loadingRecords": 'Loading...'
			},
            "bLengthChange": false,
            "bFilter": false,
			"rowId": "id",
			"deferRender": true,
			"columns": [
                { "data": "name"},
				{ "data": "kind"},
				{ "data": "next_run_time"},
				{
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "width": "58px",
                "defaultContent": '<button id="btn-scheduler-delete" class="btn btn-xs" type="button"  data-placement="top"></button>'
				},
                ],
			 "order": [[1, 'asc']],
			 "columnDefs": [ {
							"targets": 2,
							"render": function ( data, type, full, meta ) {
							  return moment.unix(full.next_run_time);
							}}]
    } );

     $('#table-scheduler').find(' tbody').on( 'click', 'button', function () {
        var data = scheduler_table.row( $(this).parents('tr') ).data();
        if($(this).attr('id')=='btn-scheduler-delete'){
				new PNotify({
						title: 'Delete scheduled task',
							text: "Do you really want to delete scheduled task "+moment.unix(data.next_run_time)+"?",
							hide: false,
							opacity: 0.9,
							confirm: {confirm: true},
							buttons: {closer: false,sticker: false},
							history: {history: false},
							addclass: 'pnotify-center'
						}).get().on('pnotify.confirm', function() {
                            api.ajax('/scheduler/'+data["id"],'DELETE',{}).done(function(data) {
                                // Websocket event will delete it
                                // scheduler_table.row('#'+data["id"]).remove().draw();
                            });
						}).on('pnotify.cancel', function() {
				});
        }
    });

    maintenance_update_checkbox = (enabled) => {
        let status
        if (enabled) {
            status = 'check'
        } else {
            status = 'uncheck'
        }
        $('#maintenance_checkbox').iCheck(status)
    }
    maintenance_bind_checkbox = () => {
        $('#maintenance_checkbox').on('ifChecked', () => {
            maintenance_update_status(true)
        })
        $('#maintenance_checkbox').on('ifUnchecked', () => {
            maintenance_update_status(false)
        })
    }
    maintenance_update_status = (enabled) => {
        $('#maintenance_wrapper').hide()
        $('#maintenance_spinner').show()
        $('#maintenance_checkbox').unbind('ifChecked')
        $('#maintenance_checkbox').unbind('ifUnchecked')
        api.ajax(
            '/api/v3/maintenance',
            'PUT',
            enabled
        ).done((data) => {
            maintenance_update_checkbox(data)
            maintenance_bind_checkbox()
            $('#maintenance_spinner').hide()
            $('#maintenance_wrapper').show()
        })
    }
    api.ajax('/api/v3/maintenance', 'GET').done((data) => {
        maintenance_update_checkbox(data)
        maintenance_bind_checkbox()
        $('#maintenance_spinner').hide()
        $('#maintenance_wrapper').show()
    })

    // SocketIO
    socket = io.connect(location.protocol+'//' + document.domain + ':' + location.port+'/administrators', {
        'query': {'jwt': localStorage.getItem("token")},
        'path': '/api/v3/socket.io/',
        'transports': ['websocket']
    });

    socket.on('connect', function() {
        connection_done();
        console.log('Listening admins namespace');
        console.log('Listening config updates');
    });

    socket.on('connect_error', function(data) {
      connection_lost();
    });

    socket.on('user_quota', function(data) {
        var data = JSON.parse(data);
        drawUserQuota(data);
    });

    socket.on('backups_data', function(data){
        var data = JSON.parse(data);
        dtUpdateInsert(backups_table,data,false);
    });

    socket.on('backups_deleted', function(data){
        var data = JSON.parse(data);
        backups_table.row('#'+data.id).remove().draw();
        new PNotify({
                title: "Backup deleted",
                text: "Backup "+data.name+" has been deleted",
                hide: true,
                delay: 4000,
                icon: 'fa fa-success',
                opacity: 1,
                type: 'success'
        });
    });

    socket.on('scheduler_jobs_data', function(data){
        var data = JSON.parse(data);
        dtUpdateInsert(scheduler_table,data,false);
    });

    socket.on('scheduler_jobs_deleted', function(data){
        var data = JSON.parse(data);
        scheduler_table.row('#'+data.id).remove().draw();
        new PNotify({
                title: "Scheduler deleted",
                text: "Scheduler "+data.name+" has been deleted",
                hide: true,
                delay: 4000,
                icon: 'fa fa-success',
                opacity: 1,
                type: 'success'
        });
    });

    socket.on ('result', function (data) {
        var data = JSON.parse(data);
        new PNotify({
                title: data.title,
                text: data.text,
                hide: true,
                delay: 4000,
                icon: 'fa fa-'+data.icon,
                opacity: 1,
                type: data.type
        });
    });

    socket.on('add_form_result', function (data) {
        var data = JSON.parse(data);
        if(data.result){
            $("#modalAddScheduler")[0].reset();
            $("#modalScheduler").modal('hide');
            //~ $('body').removeClass('modal-open');
            //~ $('.modal-backdrop').remove();
        }
        new PNotify({
                title: data.title,
                text: data.text,
                hide: true,
                delay: 4000,
                icon: 'fa fa-'+data.icon,
                opacity: 1,
                type: data.type
        });
    });

});
<commit_msg>fix(webapp): inform user to restart isard-engine after restoring db<commit_after>/*
* Copyright 2017 the Isard-vdi project authors:
*      Josep Maria Viñolas Auquer
*      Alberto Larraz Dalmases
* License: AGPLv3
*/

$(document).ready(function() {
    $('.btn-scheduler').on( 'click', function () {
        $('#modalScheduler').modal({
				backdrop: 'static',
				keyboard: false
        }).modal('show');
    });

    $("#modalScheduler #send").on('click', function(e){
            var form = $('#modalAddScheduler');
            data=$('#modalAddScheduler').serializeObject();
            api.ajax('/scheduler/system/'+data["kind"]+"/"+data["action"]+"/"+data["hour"]+"/"+data["minute"],'POST',{}).done(function(data) {
            });
            $("#modalAddScheduler")[0].reset();
            $("#modalScheduler").modal('hide');
        });

    $('.btn-backup').on( 'click', function () {
				new PNotify({
						title: 'Create backup',
							text: "Do you really want to create a new backup?",
							hide: false,
							opacity: 0.9,
							confirm: {confirm: true},
							buttons: {closer: false,sticker: false},
							history: {history: false},
							addclass: 'pnotify-center'
						}).get().on('pnotify.confirm', function() {
                            api.ajax('/api/v3/backup','POST',{}).done(function(data) {
                            });
						}).on('pnotify.cancel', function() {
				});
    });

    $('.btn-backups-upload').on( 'click', function () {
			$('#modalUpload').modal({
				backdrop: 'static',
				keyboard: false
			}).modal('show');
        });

    backups_table=$('#table-backups').DataTable({
			"ajax": {
				"url": "/api/v3/admin/table/backups",
                "contentType": "application/json",
                "type": 'POST',
                "data": function(d){return JSON.stringify({'order':'filename'})}
			},
            "sAjaxDataProp": "",
			"language": {
				"loadingRecords": 'Loading...'
			},
            "bLengthChange": false,
            "bFilter": false,
			"rowId": "id",
			"deferRender": true,
			"columns": [
				{ "data": "when"},
				{ "data": "status"},
                { "data": "version", "defaultContent": "Unknown"},
				{
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "width": "88px",
                "defaultContent": '<button id="btn-backups-delete" class="btn btn-xs" type="button"  data-placement="top"></button> \
                                   <button id="btn-backups-restore" class="btn btn-xs" type="button"  data-placement="top"></button> \
                                   <button id="btn-backups-info" class="btn btn-xs" type="button"  data-placement="top"></button> \
                                   <button id="btn-backups-download" class="btn btn-xs" type="button"  data-placement="top"></button>'
				},
                ],
			 "order": [[0, 'desc']],
			 "columnDefs": [ {
							"targets": 0,
							"render": function ( data, type, full, meta ) {
                              if ( type === 'display' || type === 'filter' ) {
                                    return moment.unix(full.when).fromNow();
                              }
                              return data;
							}}]
    } );

     $('#table-backups').find(' tbody').on( 'click', 'button', function () {
        var data = backups_table.row( $(this).parents('tr') ).data();
        if($(this).attr('id')=='btn-backups-delete'){
				new PNotify({
						title: 'Delete backup',
							text: "Do you really want to delete backup on date "+moment.unix(data.when).fromNow()+"?",
							hide: false,
							opacity: 0.9,
							confirm: {confirm: true},
							buttons: {closer: false,sticker: false},
							history: {history: false},
							addclass: 'pnotify-center'
						}).get().on('pnotify.confirm', function() {
                            api.ajax('/api/v3/backup/'+data["id"],'DELETE',{}).done(function(data) {
                            });
						}).on('pnotify.cancel', function() {
				});
        }
        if($(this).attr('id')=='btn-backups-restore'){
				new PNotify({
						title: 'Restore backup',
							text: "Do you really want to restore backup from file "+data.filename+"? NOTE: After restoring isard-engine container MUST be restarted to apply db version upgrade!",
							hide: false,
							opacity: 0.9,
							confirm: {confirm: true},
							buttons: {closer: false,sticker: false},
							history: {history: false},
							addclass: 'pnotify-center'
						}).get().on('pnotify.confirm', function() {
                            api.ajax('/api/v3/backup/restore/'+data["id"],'PUT',{}).done(function(data) {
                            });
						}).on('pnotify.cancel', function() {
				});
        }
        if($(this).attr('id')=='btn-backups-download'){
						var url = '/api/v3/backup/download/'+data['id']+'?jwt='+localStorage.getItem("token");
						var anchor = document.createElement('a');
							anchor.setAttribute('href', url);
							anchor.setAttribute('download', data['filename']);
						var ev = document.createEvent("MouseEvents");
							ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
						anchor.dispatchEvent(ev);
        }
        if($(this).attr('id')=='btn-backups-info'){
						api.ajax('/api/v3/backup/'+data["id"],'GET',{}).done(function(data) {
                            $("#backup-tables").find('option').remove();
                            $("#backup-tables").append('<option value="">Choose..</option>');
                            $.each(data.data,function(key, value)
                            {
                                if(value>0){
                                    $("#backup-tables").append('<option value=' + key + '>' + key+' ('+value+' items)' + '</option>');
                                }
                            });
                            $('#backup-id').val(data['id'])
                            $('#modalBackupInfo').modal({
                                backdrop: 'static',
                                keyboard: false
                            }).modal('show');
                        });
        }
    });

    $('#backup-tables').on('change', function (e) {
			var valueSelected = this.value;
            // var backup_id = +'/'+$('#backup-id').val()
			api.ajax('/api/v3/backup/table/'+valueSelected,'GET',{}).done(function(data) {
				if ( $.fn.dataTable.isDataTable( '#backup-table-detail' ) ) {
					backup_table_detail.clear().rows.add(data).draw()
				}else{

					backup_table_detail=$('#backup-table-detail').DataTable( {
						data: data,
						rowId: 'id',
						//~ language: {
							//~ "loadingRecords": 'Loading...'
						//~ },
						columns: [
							{ "data": "id", "width": "88px"},
							{ "data": "description", "width": "88px", "defaultContent": ""},
							{
							"className":      'actions-control',
							"orderable":      false,
							"data":           null,
							"width": "88px",
							"defaultContent": '<button class="btn btn-xs btn-individual-restore" type="button"  data-placement="top"></button>'
							},
							],
						 "order": [[0, 'asc']],
						 "columnDefs": [ {
										"targets": 2,
										"render": function ( data, type, full, meta ) {
										  if(full.new_backup_data){
											  return '<button class="btn btn-xs btn-individual-restore" type="button"  data-placement="top">New</button>';
										  }else{
											  return '<button class="btn btn-xs btn-individual-restore" type="button"  data-placement="top">Exists</button>'
										  }
										}}]
					} );
				}
								$('.btn-individual-restore').on('click', function (e){
									data=backup_table_detail.row( $(this).parents('tr') ).data();
									table=$('#backup-tables').val()
									new PNotify({
											title: 'Restore data',
												text: "Do you really want to restore row "+data.id+" to table "+table+"?",
												hide: false,
												opacity: 0.9,
												confirm: {confirm: true},
												buttons: {closer: false,sticker: false},
												history: {history: false},
												addclass: 'pnotify-center'
											}).get().on('pnotify.confirm', function() {
												api.ajax('/api/v3/backup/restore/table/'+table,'PUT',{'data':data,}).done(function(data1) {
													api.ajax('/api/v3/backup/table/'+table,'GET',{}).done(function(data) {
														dtUpdateInsert(backup_table_detail,data,false);
													});
												});
											}).on('pnotify.cancel', function() {
									});
								});
			});
		});

        scheduler_table=$('#table-scheduler').DataTable({
            "ajax": {
                "url": "/admin/table/scheduler_jobs",
                "data": function(d){return JSON.stringify({'order_by':'date','pluck':['id','name','kind','next_run_time'],'id':'system','index':'type'})},
                "contentType": "application/json",
                "type": 'POST',
            },
            "sAjaxDataProp": "",
			"language": {
				"loadingRecords": 'Loading...'
			},
            "bLengthChange": false,
            "bFilter": false,
			"rowId": "id",
			"deferRender": true,
			"columns": [
                { "data": "name"},
				{ "data": "kind"},
				{ "data": "next_run_time"},
				{
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "width": "58px",
                "defaultContent": '<button id="btn-scheduler-delete" class="btn btn-xs" type="button"  data-placement="top"></button>'
				},
                ],
			 "order": [[1, 'asc']],
			 "columnDefs": [ {
							"targets": 2,
							"render": function ( data, type, full, meta ) {
							  return moment.unix(full.next_run_time);
							}}]
    } );

     $('#table-scheduler').find(' tbody').on( 'click', 'button', function () {
        var data = scheduler_table.row( $(this).parents('tr') ).data();
        if($(this).attr('id')=='btn-scheduler-delete'){
				new PNotify({
						title: 'Delete scheduled task',
							text: "Do you really want to delete scheduled task "+moment.unix(data.next_run_time)+"?",
							hide: false,
							opacity: 0.9,
							confirm: {confirm: true},
							buttons: {closer: false,sticker: false},
							history: {history: false},
							addclass: 'pnotify-center'
						}).get().on('pnotify.confirm', function() {
                            api.ajax('/scheduler/'+data["id"],'DELETE',{}).done(function(data) {
                                // Websocket event will delete it
                                // scheduler_table.row('#'+data["id"]).remove().draw();
                            });
						}).on('pnotify.cancel', function() {
				});
        }
    });

    maintenance_update_checkbox = (enabled) => {
        let status
        if (enabled) {
            status = 'check'
        } else {
            status = 'uncheck'
        }
        $('#maintenance_checkbox').iCheck(status)
    }
    maintenance_bind_checkbox = () => {
        $('#maintenance_checkbox').on('ifChecked', () => {
            maintenance_update_status(true)
        })
        $('#maintenance_checkbox').on('ifUnchecked', () => {
            maintenance_update_status(false)
        })
    }
    maintenance_update_status = (enabled) => {
        $('#maintenance_wrapper').hide()
        $('#maintenance_spinner').show()
        $('#maintenance_checkbox').unbind('ifChecked')
        $('#maintenance_checkbox').unbind('ifUnchecked')
        api.ajax(
            '/api/v3/maintenance',
            'PUT',
            enabled
        ).done((data) => {
            maintenance_update_checkbox(data)
            maintenance_bind_checkbox()
            $('#maintenance_spinner').hide()
            $('#maintenance_wrapper').show()
        })
    }
    api.ajax('/api/v3/maintenance', 'GET').done((data) => {
        maintenance_update_checkbox(data)
        maintenance_bind_checkbox()
        $('#maintenance_spinner').hide()
        $('#maintenance_wrapper').show()
    })

    // SocketIO
    socket = io.connect(location.protocol+'//' + document.domain + ':' + location.port+'/administrators', {
        'query': {'jwt': localStorage.getItem("token")},
        'path': '/api/v3/socket.io/',
        'transports': ['websocket']
    });

    socket.on('connect', function() {
        connection_done();
        console.log('Listening admins namespace');
        console.log('Listening config updates');
    });

    socket.on('connect_error', function(data) {
      connection_lost();
    });

    socket.on('user_quota', function(data) {
        var data = JSON.parse(data);
        drawUserQuota(data);
    });

    socket.on('backups_data', function(data){
        var data = JSON.parse(data);
        dtUpdateInsert(backups_table,data,false);
    });

    socket.on('backups_deleted', function(data){
        var data = JSON.parse(data);
        backups_table.row('#'+data.id).remove().draw();
        new PNotify({
                title: "Backup deleted",
                text: "Backup "+data.name+" has been deleted",
                hide: true,
                delay: 4000,
                icon: 'fa fa-success',
                opacity: 1,
                type: 'success'
        });
    });

    socket.on('scheduler_jobs_data', function(data){
        var data = JSON.parse(data);
        dtUpdateInsert(scheduler_table,data,false);
    });

    socket.on('scheduler_jobs_deleted', function(data){
        var data = JSON.parse(data);
        scheduler_table.row('#'+data.id).remove().draw();
        new PNotify({
                title: "Scheduler deleted",
                text: "Scheduler "+data.name+" has been deleted",
                hide: true,
                delay: 4000,
                icon: 'fa fa-success',
                opacity: 1,
                type: 'success'
        });
    });

    socket.on ('result', function (data) {
        var data = JSON.parse(data);
        new PNotify({
                title: data.title,
                text: data.text,
                hide: true,
                delay: 4000,
                icon: 'fa fa-'+data.icon,
                opacity: 1,
                type: data.type
        });
    });

    socket.on('add_form_result', function (data) {
        var data = JSON.parse(data);
        if(data.result){
            $("#modalAddScheduler")[0].reset();
            $("#modalScheduler").modal('hide');
            //~ $('body').removeClass('modal-open');
            //~ $('.modal-backdrop').remove();
        }
        new PNotify({
                title: data.title,
                text: data.text,
                hide: true,
                delay: 4000,
                icon: 'fa fa-'+data.icon,
                opacity: 1,
                type: data.type
        });
    });

});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require_tree .

var toggle = function(id) {
  var s = document.getElementById("toggle_" + id).style;
  var t = document.getElementById("toggle_" + id + "_toggle");
  if (s.display == 'none') {
    s.display = 'block';
    t.innerHTML = t.innerHTML.replace(/^Show/, 'Hide');
  } else {
    s.display = 'none';
    t.innerHTML = t.innerHTML.replace(/^Hide/, 'Show');
  }
  return false;
}

var toggleHeadersDump = function() {
  return toggle('headers_dump');
}
<commit_msg>No longer include jquery since we don't use it.<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require_tree .

var toggle = function(id) {
  var s = document.getElementById("toggle_" + id).style;
  var t = document.getElementById("toggle_" + id + "_toggle");
  if (s.display == 'none') {
    s.display = 'block';
    t.innerHTML = t.innerHTML.replace(/^Show/, 'Hide');
  } else {
    s.display = 'none';
    t.innerHTML = t.innerHTML.replace(/^Hide/, 'Show');
  }
  return false;
}

var toggleHeadersDump = function() {
  return toggle('headers_dump');
}
<|endoftext|>


<commit_before>
angular.module('os.administrative.user.roles', ['os.administrative.models', 'os.biospecimen.models'])
  .controller('UserRolesCtrl', function(
    $scope, $translate, $filter,
    user, userRoles,
    PvManager, CollectionProtocol, Site, Role) {

    function init() {
      $scope.currentRole = {};
      $scope.userRoles = {};
      createUserRolesJson(userRoles);

      $scope.addMode = false;
      $scope.all = $translate.instant('user.role.all');
      loadPvs();
      $scope.userRolesList = getUserRolesList($scope.userRoles);
    }

    function createUserRolesJson(userRoles) {
      angular.forEach(userRoles, function(userRole) {
        updateUserRoles(userRole);
      });
    }

    function loadPvs() {
      var query = undefined;
      if ($scope.currentUser.admin) {
        query = Site.listForInstitute($scope.user.instituteName)
      } else {
        query = Site.listForUsers('Update');
      }

      query.then(function(sites) {
        $scope.sites = sites;
      });
      $scope.sites.splice(0, 0, $scope.all);
      setSitePvs();

      $scope.roles = [];
      Role.query().then(
        function(result) {
          angular.forEach(result, function(role) {
            $scope.roles.push(role.name);
          });
        }
      );
    }

    $scope.showAddRole = function() {
      $scope.addMode = true;
      $scope.currentRole = user.newRole();
      $scope.cps = [];
      setSitePvs();
    }

    $scope.showEditRole = function(role) {
      $scope.loadCps(role.site);
      setSitePvs();

      $scope.currentRole = angular.copy(role);
      //If site or cp not exist means "All Sites" or "All CPs" is selected.
      if (!$scope.currentRole.site) {
        $scope.currentRole.site = $scope.all;
      }
      if (!$scope.currentRole.collectionProtocol) {
        $scope.currentRole.collectionProtocol = $scope.all;
      }

      $scope.addMode = false;
    }

    $scope.saveOrUpdateRole = function() {
      $scope.currentRole.$saveOrUpdate().then(
        function(role) {
          updateUserRoles(role);
          $scope.userRolesList = getUserRolesList($scope.userRoles);

          $scope.currentRole = {};
          $scope.addMode = false;
        }
      );
    }

    $scope.removeRole = function(role) {
      role.$remove().then(function(role) {
        deleteRole($scope.userRoles, role);
        $scope.userRolesList = getUserRolesList($scope.userRoles);
      })
    }

    $scope.revertEdit = function() {
      $scope.addMode = false;
      $scope.currentRole = {};
    }

    $scope.loadCps = function(site) {
      if (site == $scope.all) {
        $scope.cps = [$scope.all];
        return;
      }
      var cpsToRemove = [];
      angular.forEach($scope.userRoles.siteCpRoles, function(role) {
        cpsToRemove.push(role.collectionProtocol);
      });

      var cpListOpts = {detailedList: false};
      if (site != $scope.all) {
        cpListOpts["repositoryName"] = site;
      }

      CollectionProtocol.list(cpListOpts).then(
        function(result) {
          $scope.cps = [];
          angular.forEach(result, function(cp) {
            if (cpsToRemove.indexOf(cp.shortTitle) == -1 || $scope.currentRole.collectionProtocol == cp.shortTitle) {
              $scope.cps.push(cp.shortTitle);
            }
          });

          if (result.length == $scope.cps.length) {
            $scope.cps.splice(0, 0, $scope.all);
          }
      });
    }

    function updateUserRoles(userRole) {
      // In Case of Update, remove old role from json.
      if (userRole.id) {
        for (var key in $scope.userRoles) {
          var deleted = deleteRoleById($scope.userRoles[key], userRole);
          if (deleted) {
            break;
          }
        }
      }

      var roleType = getRoleType(userRole);
      var roles = $scope.userRoles[roleType] || [];
      roles.push(formatRoleToUiModel(userRole));
      $scope.userRoles[roleType] = roles;
    }

    function deleteRole(userRoles, role) {
      var roleType = getRoleType(role);
      var roles = userRoles[roleType];
      deleteRoleById(roles, role);
    }

    function deleteRoleById(roles, role) {
      for (var i = roles.length - 1; i >= 0; i--) {
        if (roles[i].id == role.id) {
          roles.splice(i, 1);
          return true;
        }
      }

      return false;
    }

    function formatRoleToUiModel(userRole) {
      userRole.role = userRole.role.name;
      userRole.site = userRole.site ? userRole.site.name : $scope.all;
      userRole.collectionProtocol = userRole.collectionProtocol ? userRole.collectionProtocol.shortTitle : $scope.all;
      return userRole;
    }

    function getRoleType(userRole) {
      var roleType = undefined;
      if (!userRole.site && !userRole.collectionProtocol) {
        roleType = 'all';
      } else if (!userRole.site) {
        roleType = 'allSites';
      } else if (!userRole.collectionProtocol) {
        roleType = 'allCps';
      } else {
        roleType = 'siteCpRoles';
      }

      return roleType;
    }

    function getUserRolesList(userRoles) {
      var userRolesList = [];
      angular.forEach(userRoles, function(value) {
        angular.forEach(value, function(role) {
          userRolesList.push(role);
        })
      });

      var sortedUserRoles = userRolesList.sort(function(role1, role2) {
        return role1.id - role2.id;
      });

      return sortedUserRoles;
    }

    function setSitePvs() {
      // If role exist on individual site then hide "All Sites" option.
      $scope.sitePvs = angular.copy($scope.sites);
      if (hasRoleOnIndividualSite()) {
        $scope.sitePvs.splice(0, 1);
      }

      // Hide sites for which role is selected for all cps.
      angular.forEach($scope.userRoles.allCps, function(role) {
        var idx = $scope.sitePvs.indexOf(role.site);
        if (idx != -1) {
          $scope.sitePvs.splice(idx, 1);
        }
      });
    }

    function hasRoleOnIndividualSite() {
      return ($scope.userRoles.allCps && $scope.userRoles.allCps.length > 0) ||
        ($scope.userRoles.siteCpRoles && $scope.userRoles.siteCpRoles.length > 0) ;
    }

    $scope.allowAddRoles = function() {
      return !$scope.userRoles.all || $scope.userRoles.all.length == 0;
    }

    init();
  });
<commit_msg>1.Change in UI for assign role to CP on all sites 2.Fix bug All Current and Future option not showing in site dropdown<commit_after>
angular.module('os.administrative.user.roles', ['os.administrative.models', 'os.biospecimen.models'])
  .controller('UserRolesCtrl', function(
    $scope, $translate, $filter,
    user, userRoles,
    PvManager, CollectionProtocol, Site, Role) {

    function init() {
      $scope.currentRole = {};
      $scope.userRoles = {};
      createUserRolesJson(userRoles);

      $scope.addMode = false;
      $scope.all = $translate.instant('user.role.all');
      loadPvs();
      $scope.userRolesList = getUserRolesList($scope.userRoles);
    }

    function createUserRolesJson(userRoles) {
      angular.forEach(userRoles, function(userRole) {
        updateUserRoles(userRole);
      });
    }

    function loadPvs() {
      var query = undefined;
      if ($scope.currentUser.admin) {
        query = Site.listForInstitute($scope.user.instituteName)
      } else {
        query = Site.listForUsers('Update');
      }

      $scope.sites = [];
      query.then(function(sites) {
        angular.forEach(sites, function(site) {
          $scope.sites.push(site);
        });
      });
      $scope.sites.splice(0, 0, $scope.all);
      setSitePvs();

      $scope.roles = [];
      Role.query().then(
        function(result) {
          angular.forEach(result, function(role) {
            $scope.roles.push(role.name);
          });
        }
      );
    }

    $scope.showAddRole = function() {
      $scope.addMode = true;
      $scope.currentRole = user.newRole();
      $scope.cps = [];
      setSitePvs();
    }

    $scope.showEditRole = function(role) {
      $scope.loadCps(role.site);
      setSitePvs();

      $scope.currentRole = angular.copy(role);
      //If site or cp not exist means "All Sites" or "All CPs" is selected.
      if (!$scope.currentRole.site) {
        $scope.currentRole.site = $scope.all;
      }
      if (!$scope.currentRole.collectionProtocol) {
        $scope.currentRole.collectionProtocol = $scope.all;
      }

      $scope.addMode = false;
    }

    $scope.saveOrUpdateRole = function() {
      $scope.currentRole.$saveOrUpdate().then(
        function(role) {
          updateUserRoles(role);
          $scope.userRolesList = getUserRolesList($scope.userRoles);

          $scope.currentRole = {};
          $scope.addMode = false;
        }
      );
    }

    $scope.removeRole = function(role) {
      role.$remove().then(function(role) {
        deleteRole($scope.userRoles, role);
        $scope.userRolesList = getUserRolesList($scope.userRoles);
      })
    }

    $scope.revertEdit = function() {
      $scope.addMode = false;
      $scope.currentRole = {};
    }

    $scope.loadCps = function(site) {
      var cpsToRemove = [];

      angular.forEach($scope.userRoles.allSites, function(role) {
        cpsToRemove.push(role.collectionProtocol);
      });

      angular.forEach($scope.userRoles.siteCpRoles, function(role) {
        cpsToRemove.push(role.collectionProtocol);
      });

      var cpListOpts = {detailedList: false};
      if (site != $scope.all) {
        cpListOpts["repositoryName"] = site;
      }

      CollectionProtocol.list(cpListOpts).then(
        function(result) {
          $scope.cps = [];
          angular.forEach(result, function(cp) {
            if (cpsToRemove.indexOf(cp.shortTitle) == -1 || $scope.currentRole.collectionProtocol == cp.shortTitle) {
              $scope.cps.push(cp.shortTitle);
            }
          });

          if (result.length == $scope.cps.length) {
            $scope.cps.splice(0, 0, $scope.all);
          }
      });
    }

    function updateUserRoles(userRole) {
      // In Case of Update, remove old role from json.
      if (userRole.id) {
        for (var key in $scope.userRoles) {
          var deleted = deleteRoleById($scope.userRoles[key], userRole);
          if (deleted) {
            break;
          }
        }
      }

      var roleType = getRoleType(userRole);
      var roles = $scope.userRoles[roleType] || [];
      roles.push(formatRoleToUiModel(userRole));
      $scope.userRoles[roleType] = roles;
    }

    function deleteRole(userRoles, role) {
      var roleType = getRoleType(role);
      var roles = userRoles[roleType];
      deleteRoleById(roles, role);
    }

    function deleteRoleById(roles, role) {
      for (var i = roles.length - 1; i >= 0; i--) {
        if (roles[i].id == role.id) {
          roles.splice(i, 1);
          return true;
        }
      }

      return false;
    }

    function formatRoleToUiModel(userRole) {
      userRole.role = userRole.role.name;
      userRole.site = userRole.site ? userRole.site.name : $scope.all;
      userRole.collectionProtocol = userRole.collectionProtocol ? userRole.collectionProtocol.shortTitle : $scope.all;
      return userRole;
    }

    function getRoleType(userRole) {
      var roleType = undefined;
      if (!userRole.site && !userRole.collectionProtocol) {
        roleType = 'all';
      } else if (!userRole.site) {
        roleType = 'allSites';
      } else if (!userRole.collectionProtocol) {
        roleType = 'allCps';
      } else {
        roleType = 'siteCpRoles';
      }

      return roleType;
    }

    function getUserRolesList(userRoles) {
      var userRolesList = [];
      angular.forEach(userRoles, function(value) {
        angular.forEach(value, function(role) {
          userRolesList.push(role);
        })
      });

      var sortedUserRoles = userRolesList.sort(function(role1, role2) {
        return role1.id - role2.id;
      });

      return sortedUserRoles;
    }

    function setSitePvs() {
      // If role exist on individual site then hide "All Sites" option.
      $scope.sitePvs = angular.copy($scope.sites);
      if (hasRoleOnIndividualSite()) {
        $scope.sitePvs.splice(0, 1);
      }

      // Hide sites for which role is selected for all cps.
      angular.forEach($scope.userRoles.allCps, function(role) {
        var idx = $scope.sitePvs.indexOf(role.site);
        if (idx != -1) {
          $scope.sitePvs.splice(idx, 1);
        }
      });
    }

    function hasRoleOnIndividualSite() {
      return ($scope.userRoles.allCps && $scope.userRoles.allCps.length > 0) ||
        ($scope.userRoles.siteCpRoles && $scope.userRoles.siteCpRoles.length > 0) ;
    }

    $scope.allowAddRoles = function() {
      return !$scope.userRoles.all || $scope.userRoles.all.length == 0;
    }

    init();
  });
<|endoftext|>


<commit_before>define(['cookie', '../../Router', 'validate', '../../service/DataService', '../../Notify'], function(cookie, router, validate, service, notify) {"use strict";

	var EntryView = ( function() {

			/**
			 * Constructor
			 */

			var ENTITY;
			var DOMAINSLIST;
			var ERROR = '';
			var OK = '';
			var INFO = '';

			function EntryView() {

				function activateSuggestionSearch() {
					if (ENTITY) {
						jQuery('#new-user-domain').val(ENTITY);
					}
					if (checkForActiveCookie() === false) {
						service.entityList({
							success : function(result) {
								DOMAINSLIST = result;
								if (result !== 'error') {
									$("#new-user-domain").autocomplete({
										source : function(request, response) {
											var results = $.ui.autocomplete.filter(result, request.term);
											response(results.slice(0, 5));
										},
										select : function(event, ui) {
											var origEvent = event;
											while (origEvent.originalEvent !== undefined)
											origEvent = origEvent.originalEvent;
											if (origEvent.type == 'keydown')
												$("#new-user-domain").keyup();
										},
									});
								}
							}
						});
					}
				}

				function RegisterUser(username, password, domain) {
					service.registerNewUser(username, password, domain, {
						success : function(RegisterData) {
							if (RegisterData.status === 'success') {
								notify.showNotification('OK', 'Congratulations!!!', null, '1000');
								Login(username, password);
							} else {
								notify.showNotification('ERROR', RegisterData.message);
							}
						}
					});
				}

				function checkForActiveCookie() {
					if (jQuery.cookie('user')) {
						router.go('/studentlist', '/register');
						return true;
					} else {
						return false;
					}
				}

				function Login(username, password) {
					service.Login(username, password, {
						success : function(LoginData) {
							if (LoginData !== 'error') {
								notify.showNotification('OK', 'Congratulations!!!', 'studentlist', '1000');
								if (username.length > 18) {
									username = username.split('@')[0];
								}
								jQuery.cookie('user', username, {
									expires : 100,
									path : '/'
								});
							} else {
								notify.showNotification('ERROR', 'Some thing didnt go right!');
							}
						}
					});
				}

				function parseQueryURL() {
					var requesturl = router.location().substring(1);
					if (requesturl.indexOf('email=') !== -1 && requesturl.indexOf('domain=') !== -1) {
						var query = requesturl.split('email=')[1];
						query = query.split("?");
						jQuery('#new-user-name').val(query[0]);
						jQuery('#new-user-domain').val(query[1].split("domain=")[1].toUpperCase());
						jQuery('#new-user-name').attr('readonly', true);
						jQuery('#new-user-doamin').attr('readonly', true);
						jQuery('#new-user-password').focus();
					} else {
						jQuery('#new-user-name').val('');
						jQuery('#new-user-domain').val('');
						jQuery('#new-user-name').attr('readonly', false);
						jQuery('#new-user-doamin').attr('readonly', false);
						jQuery('#new-user-name').focus();
					}
				}

				$.validator.addMethod("passwordvalid", function(value, element, param) {
					var ValidPwd = (/^[^<>;,"'&\\\/|+:= ]+$/.test(value));
					return (value.length == 0 || ValidPwd);
				}, 'Invalid Password Choice');

				this.entity = function(entity) {
					ENTITY = entity;
				}

				this.pause = function() {

				};

				this.resume = function() {
					checkForActiveCookie();
					jQuery('.info').hide();
					parseQueryURL();
				};

				this.init = function() {
					if (!jQuery.cookie('entity')) {
						jQuery('#user-domain').removeAttr('readonly');
						jQuery('#user-domain').removeClass('onlyone');
						activateSuggestionSearch();
					} else {
						jQuery('#user-domain').addClass('onlyone');
						jQuery('#user-domain').val('Active Domain: ' + jQuery.cookie('entity').toUpperCase());
					}

					parseQueryURL();

					jQuery('#register').on('click', function(e) {
						if ($("#register-form").valid()) {
							var inputuname = jQuery('#new-user-name').val();
							var inputpass = jQuery('#new-user-password').val();
							var inputdomain = jQuery('#new-user-domain').val().toUpperCase();
							RegisterUser(inputuname, inputpass, inputdomain);
							e.preventDefault();
						}
					});

					//Rarely die to network latency if not loaded, just reload
					if (!$.ui) {
						location.reload();
					}

					jQuery(function() {
						$("#user-dob").datepicker();
					});

					jQuery('#user-name').on('keyup', function() {
						jQuery('#login-notification').fadeOut(1000);
					});

					jQuery('#user-password').on('keyup', function() {
						jQuery('#login-notification').fadeOut(1000);
					});

					jQuery('#new-user-domain').keyup(function() {
						//Sanity
						jQuery('#new-user-domain').css("text-transform", "uppercase");
						var domainrequest = jQuery('#new-user-domain').val().toUpperCase();
						if (domainrequest === "") {
							jQuery('#new-user-domain').css("text-transform", "none");
							jQuery('#RInfo').fadeOut();
						} else {
							jQuery('#RInfo').fadeIn();
							if (DOMAINSLIST && DOMAINSLIST.indexOf(domainrequest) !== -1) {
								jQuery('.info').text('This is an existing Domain');
							} else {
								jQuery('.info').text('This is a New Domain');
							}
						}
					});

					jQuery('#login-close').on('click', function() {
						router.returnToPrevious();
					});

					jQuery("#register-form").validate({
						rules : {
							Rfirstname : {
								required : false,
							},
							Rusername : {
								required : true,
								email : true
							},
							Rpassword : {
								required : true,
								passwordvalid : '#new-user-password'
							},
							Rpasswordrepeat : {
								required : true,
								equalTo : "#new-user-password"
							},
							Rdomain : {
								required : true,
							},
							RDOB : {
								required : false,
								date : true
							},
						},
						messages : {
							Rusername : "Valid Email Needed",
						},
					});

				};

			}

			return EntryView;
		}());

	return new EntryView();
});
<commit_msg>Register direct hyperlink<commit_after>define(['cookie', '../../Router', 'validate', '../../service/DataService', '../../Notify'], function(cookie, router, validate, service, notify) {"use strict";

	var EntryView = ( function() {

			/**
			 * Constructor
			 */

			var ENTITY;
			var DOMAINSLIST;
			var ERROR = '';
			var OK = '';
			var INFO = '';

			function EntryView() {

				function activateSuggestionSearch() {
					if (ENTITY) {
						jQuery('#new-user-domain').val(ENTITY);
					}
					if (checkForActiveCookie() === false) {
						service.entityList({
							success : function(result) {
								DOMAINSLIST = result;
								if (result !== 'error') {
									$("#new-user-domain").autocomplete({
										source : function(request, response) {
											var results = $.ui.autocomplete.filter(result, request.term);
											response(results.slice(0, 5));
										},
										select : function(event, ui) {
											var origEvent = event;
											while (origEvent.originalEvent !== undefined)
											origEvent = origEvent.originalEvent;
											if (origEvent.type == 'keydown')
												$("#new-user-domain").keyup();
										},
									});
								}
							}
						});
					}
				}

				function RegisterUser(username, password, domain) {
					service.registerNewUser(username, password, domain, {
						success : function(RegisterData) {
							if (RegisterData.status === 'success') {
								notify.showNotification('OK', 'Congratulations!!!', null, '1000');
								Login(username, password);
							} else {
								notify.showNotification('ERROR', RegisterData.message);
							}
						}
					});
				}

				function checkForActiveCookie() {
					if (jQuery.cookie('user')) {
						router.go('/studentlist', '/register');
						return true;
					} else {
						return false;
					}
				}

				function Login(username, password) {
					service.Login(username, password, {
						success : function(LoginData) {
							if (LoginData !== 'error') {
								notify.showNotification('OK', 'Congratulations!!!', 'studentlist', '1000');
								if (username.length > 18) {
									username = username.split('@')[0];
								}
								jQuery.cookie('user', username, {
									expires : 100,
									path : '/'
								});
							} else {
								notify.showNotification('ERROR', 'Some thing didnt go right!');
							}
						}
					});
				}

				function parseQueryURL() {
					var requesturl = router.location().substring(1);
					if (requesturl.indexOf('email=') !== -1 && requesturl.indexOf('domain=') !== -1) {
						var query = requesturl.split('email=')[1];
						query = query.split("&domain=");
						jQuery('#new-user-name').val(query[0]);
						jQuery('#new-user-domain').val(query[1].toUpperCase());
						jQuery('#new-user-name').attr('readonly', 'readonly');
						jQuery('#new-user-domain').attr('readonly', 'readonly');
						jQuery('#new-user-password').focus();
					} else {
						jQuery('#new-user-name').val('');
						jQuery('#new-user-domain').val('');
						jQuery('#new-user-name').attr('readonly', false);
						jQuery('#new-user-domain').attr('readonly', false);
						jQuery('#new-user-name').focus();
					}
				}

				$.validator.addMethod("passwordvalid", function(value, element, param) {
					var ValidPwd = (/^[^<>;,"'&\\\/|+:= ]+$/.test(value));
					return (value.length == 0 || ValidPwd);
				}, 'Invalid Password Choice');

				this.entity = function(entity) {
					ENTITY = entity;
				}

				this.pause = function() {

				};

				this.resume = function() {
					checkForActiveCookie();
					jQuery('.info').hide();
					parseQueryURL();
				};

				this.init = function() {
					if (!jQuery.cookie('entity')) {
						jQuery('#user-domain').removeAttr('readonly');
						jQuery('#user-domain').removeClass('onlyone');
						activateSuggestionSearch();
					} else {
						jQuery('#user-domain').addClass('onlyone');
						jQuery('#user-domain').val('Active Domain: ' + jQuery.cookie('entity').toUpperCase());
					}

					parseQueryURL();

					jQuery('#register').on('click', function(e) {
						if ($("#register-form").valid()) {
							var inputuname = jQuery('#new-user-name').val();
							var inputpass = jQuery('#new-user-password').val();
							var inputdomain = jQuery('#new-user-domain').val().toUpperCase();
							RegisterUser(inputuname, inputpass, inputdomain);
							e.preventDefault();
						}
					});

					//Rarely die to network latency if not loaded, just reload
					if (!$.ui) {
						location.reload();
					}

					jQuery(function() {
						$("#user-dob").datepicker();
					});

					jQuery('#user-name').on('keyup', function() {
						jQuery('#login-notification').fadeOut(1000);
					});

					jQuery('#user-password').on('keyup', function() {
						jQuery('#login-notification').fadeOut(1000);
					});

					jQuery('#new-user-domain').keyup(function() {
						//Sanity
						jQuery('#new-user-domain').css("text-transform", "uppercase");
						var domainrequest = jQuery('#new-user-domain').val().toUpperCase();
						if (domainrequest === "") {
							jQuery('#new-user-domain').css("text-transform", "none");
							jQuery('#RInfo').fadeOut();
						} else {
							jQuery('#RInfo').fadeIn();
							if (DOMAINSLIST && DOMAINSLIST.indexOf(domainrequest) !== -1) {
								jQuery('.info').text('This is an existing Domain');
							} else {
								jQuery('.info').text('This is a New Domain');
							}
						}
					});

					jQuery('#login-close').on('click', function() {
						router.returnToPrevious();
					});

					jQuery("#register-form").validate({
						rules : {
							Rfirstname : {
								required : false,
							},
							Rusername : {
								required : true,
								email : true
							},
							Rpassword : {
								required : true,
								passwordvalid : '#new-user-password'
							},
							Rpasswordrepeat : {
								required : true,
								equalTo : "#new-user-password"
							},
							Rdomain : {
								required : true,
							},
							RDOB : {
								required : false,
								date : true
							},
						},
						messages : {
							Rusername : "Valid Email Needed",
						},
					});

				};

			}

			return EntryView;
		}());

	return new EntryView();
});
<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.views.get_listview = function(doctype, parent) {
	if(frappe.listviews[doctype]) {
		var listview = new frappe.listviews[doctype](parent);
	} else {
		var listview = new frappe.views.ListView(parent, doctype);
	}
	return listview;
}

// Renders customized list
// usually based on `in_list_view` property

frappe.views.ListView = Class.extend({
	init: function(doclistview, doctype) {
		this.doclistview = doclistview;
		this.doctype = doctype;
		this.meta = frappe.get_doc("DocType", this.doctype);
		this.image_field = this.meta.image_field || image;
		this.settings = frappe.listview_settings[this.doctype] || {};
		if(this.meta.__listview_template) {
			this.template_name = doctype + "_listview";
			frappe.templates[this.template_name] = this.meta.__listview_template;
		}
		this.set_fields();
		this.set_columns();
		this.id_list = [];
		if(this.settings.group_by)
			this.group_by = this.settings.group_by;

		var me = this;
		this.doclistview.onreset = function() {
			me.id_list = [];
		}
		this.order_by = this.settings.order_by;
		this.group_by = this.settings.group_by;
	},
	set_fields: function() {
		var me = this;
		var t = "`tab"+this.doctype+"`.";
		this.fields = [];
		this.stats = ['_user_tags'];

		var add_field = function(fieldname) {
			field = t + "`" + fieldname + "`"
			if(me.fields.indexOf(field)=== -1)
				me.fields.push(field);
		}

		$.each(['name', 'owner', 'docstatus', '_user_tags', '_comments', 'modified',
			'modified_by', '_assign', '_liked_by', '_seen'],
		function(i, fieldname) { add_field(fieldname); })

		// add title field
		if(this.meta.title_field) {
			this.title_field = this.meta.title_field;
			add_field(this.meta.title_field);
		}

		// endabled / disabled
		if(frappe.meta.has_field(this.doctype, 'enabled')) { add_field('enabled'); };
		if(frappe.meta.has_field(this.doctype, 'disabled')) { add_field('disabled'); };

		// add workflow field (as priority)
		this.workflow_state_fieldname = frappe.workflow.get_state_fieldname(this.doctype);
		if(this.workflow_state_fieldname) {
			if (!frappe.workflow.workflows[this.doctype]["override_status"]) {
				add_field(this.workflow_state_fieldname);
			}
			this.stats.push(this.workflow_state_fieldname);
		}

		$.each(this.meta.fields, function(i,d) {
			if(d.in_list_view && frappe.perm.has_perm(me.doctype, d.permlevel, "read")) {
				if(d.fieldtype=="Image" && d.options) {
					add_field(d.options);
				} else {
					add_field(d.fieldname);
				}
				// currency field for symbol (multi-currency)
				if(d.fieldtype=="Currency" && d.options) {
					if(d.options.indexOf(":")!=-1) {
						add_field(d.options.split(":")[1]);
					} else {
						add_field(d.options);
					};
				}
			}
		});

		// additional fields
		if(this.settings.add_fields) {
			$.each(this.settings.add_fields, function(i, d) {
				if(d.indexOf("`tab")===-1) {
					d = "`tab" + me.doctype + "`." + d;
				}
				if(me.fields.indexOf(d)==-1)
					me.fields.push(d);
			});
		}
	},
	set_columns: function() {
		var me = this;
		this.columns = [];
		var name_column = {
			colspan: this.settings.colwidths && this.settings.colwidths.subject || 6,
			type: "Subject",
			title: "Name"
		};
		if (this.meta.title_field) {
			name_column.title = frappe.meta.get_docfield(this.doctype, this.meta.title_field).label;
		}
		this.columns.push(name_column);
		this.total_colspans = this.columns[0].colspan;

		if(frappe.has_indicator(this.doctype)) {
			// indicator
			this.columns.push({
				colspan: this.settings.colwidths && this.settings.colwidths.indicator || 3,
				type: "Indicator",
				title: "Status"
			});
			this.total_colspans += this.columns[1].colspan;
		}

		// overridden
		var overridden = $.map(this.settings.add_columns || [], function(d) {
			return d.content;
		});
		var docfields_in_list_view = frappe.get_children("DocType", this.doctype, "fields",
			{"in_list_view":1}).sort(function(a, b) { return a.idx - b.idx })

		$.each(docfields_in_list_view, function(i,d) {
			if(in_list(overridden, d.fieldname) || d.fieldname === me.title_field) {
				return;
			}
			if(me.total_colspans < 12) {
				me.add_column(d);
			}
		});

		// additional columns
		if(this.settings.add_columns) {
			$.each(this.settings.add_columns, function(i, d) {
				if(me.total_colspans < 12) {
					if(typeof d==="string") {
						me.add_column(frappe.meta.get_docfield(me.doctype, d));
					} else {
						me.columns.push(d);
						me.total_colspans += parseInt(d.colspan);
					}
				}
			});
		}

		var empty_cols = flt(12 - this.total_colspans);
		while(empty_cols > 0) {
			for(var i=0, l=this.columns.length; i < l && empty_cols > 0; i++) {
				this.columns[i].colspan = cint(this.columns[i].colspan) + 1;
				empty_cols = empty_cols - 1;
			}
		}
	},
	add_column: function(df) {
		// field width
		var colspan = 3;
		if(in_list(["Int", "Percent"], df.fieldtype)) {
			colspan = 2;
		} else if(in_list(["Check", "Image"], df.fieldtype)) {
			colspan = 1;
		} else if(in_list(["name", "subject", "title"], df.fieldname)) { // subjects are longer
			colspan = 4;
		} else if(df.fieldtype=="Text Editor" || df.fieldtype=="Text") {
			colspan = 4;
		}
		if(df.columns && df.columns>0){
			colspan = df.columns;
		}
		else if(this.settings.column_colspan && this.settings.column_colspan[df.fieldname]) {
			colspan = this.settings.column_colspan[df.fieldname];
		}
		this.total_colspans += parseInt(colspan);
		var col = {
			colspan: colspan,
			content: df.fieldname,
			type: df.fieldtype,
			df:df,
			fieldtype: df.fieldtype,
			fieldname: df.fieldname,
			title:__(df.label)
		};
		if(this.settings.column_render && this.settings.column_render[df.fieldname]) {
			col.render = this.settings.column_render[df.fieldname];
		}
		this.columns.push(col);

	},
	render: function(row, data) {
		this.prepare_data(data);

		// maintain id_list to avoid duplication incase
		// of filtering by child table
		if(in_list(this.id_list, data.name)) {
			$(row).toggle(false);
			return;
		} else {
			this.id_list.push(data.name);
		}

		this['render_row_' + this.doclistview.current_view](row, data);

		if(this.settings.post_render_item) {
			this.settings.post_render_item(this, row, data);
		}

		this.render_tags(row, data);

	},
	render_row_List: function(row, data) {
		var main = frappe.render_template("list_item_main", {
			data: data,
			columns: this.columns,
			subject: this.get_avatar_and_id(data, true),
			list: this,
			right_column: this.settings.right_column
		});

		$(frappe.render_template("list_item_row", {
			data: data,
			main: main,
			list: this,
			right_column: this.settings.right_column
		})).appendTo(row);
	},
	render_row_Image: function(row, data) {
		this.allowed_type = [
			"Check", "Currency", "Data", "Date",
			"Datetime", "Float", "Int", "Link",
			"Percent", "Select", "Read Only", "Time"
		];
		var image_url = (data.image && window.cordova && data.image.indexOf('http')===-1) ?
			frappe.base_url + data[this.image_field] : data[this.image_field];

		img_col = $(frappe.render_template("image_view_item_row", {
			data: data,
			list: this,
			columns: this.columns,
			allowed_type: this.allowed_type,
			item_image: image_url ? "url('" + image_url + "')" : null,
			color: frappe.get_palette(data.item_name),
			subject: this.get_avatar_and_id(data, true),
			right_column: this.settings.right_column
		}))
		.data("data", data)
		.appendTo($(row).find(".image-view-marker"));
	},
	render_tags: function(row, data) {
		var me = this;
		var row2 = $('
\

\

\

').appendTo(row);

		if(!me.doclistview.tags_shown) {
			row2.addClass("hide");
		}

		// add tags
		var tag_editor = new frappe.ui.TagEditor({
			parent: row2.find(".list-tag"),
			frm: {
				doctype: this.doctype,
				docname: data.name
			},
			list_sidebar: me.doclistview.list_sidebar,
			user_tags: data._user_tags,
			on_change: function(user_tags) {
				data._user_tags = user_tags;
				//me.render_timestamp_and_comments(row, data);
			}
		});
		tag_editor.wrapper.on("click", ".tagit-label", function() {
			me.doclistview.set_filter("_user_tags",
				$(this).text());
		});
	},

	get_avatar_and_id: function(data, without_workflow) {
		data._without_workflow = without_workflow;
		data.css_seen = '';

		if(data._seen) {
			var seen = JSON.parse(data._seen);
			if(seen && seen.indexOf(frappe.session.user) !== -1) {
				data.css_seen = 'seen'
			}
		}

		return frappe.render_template("list_item_subject", data);
	},

	get_indicator: function(doc) {
        var indicator = frappe.get_indicator(doc, this.doctype);
		if(indicator) {
	        return ''+__(indicator[0])+'';
		} else {
			return "";
		}
	},

	get_indicator_dot: function(doc) {
		var indicator = frappe.get_indicator(doc, this.doctype);
		if (!indicator) {
			return "";
		}
		return '';
	},

	prepare_data: function(data) {
		if(data.modified)
			this.prepare_when(data, data.modified);

		data._liked_by = data._liked_by ?
			JSON.parse(data._liked_by) : [];

		data._checkbox = (frappe.model.can_delete(this.doctype) || this.settings.selectable) && !this.no_delete

		data._doctype_encoded = encodeURIComponent(data.doctype);
		data._name = data.name.replace(/"/g, '\"');
		data._name_encoded = encodeURIComponent(data.name);
		data._submittable = frappe.model.is_submittable(this.doctype);

		data._title = strip_html(data[this.title_field || "name"] || data["name"]);
		data._full_title = data._title;

		if(data._title.length > 40) {
			data._title = data._title.slice(0, 40) + "...";
		}

		data._workflow = null;
		if(this.workflow_state_fieldname) {
			data._workflow = {
				fieldname: this.workflow_state_fieldname,
				value: data[this.workflow_state_fieldname],
				style: frappe.utils.guess_style(data[this.workflow_state_fieldname])
			}
		}
		data._user = user;

		data._tags = $.map((data._user_tags || "").split(","),
			function(v) { return v ? v : null; });
		data._assign_list = data._assign ? JSON.parse(data._assign) : [];

		// nulls as strings
		for(key in data) {
			if(data[key]==null) {
				data[key]='';
			}
		}

		// prepare data in settings
		if(this.settings.prepare_data)
			this.settings.prepare_data(data);
	},

	prepare_when: function(data, date_str) {
		if (!date_str) date_str = data.modified;
		// when
		data.when = (dateutil.str_to_user(date_str)).split(' ')[0];
		var diff = dateutil.get_diff(dateutil.get_today(), date_str.split(' ')[0]);
		if(diff==0) {
			data.when = comment_when(date_str);
		}
		if(diff == 1) {
			data.when = __('Yesterday')
		}
		if(diff == 2) {
			data.when = __('2 days ago')
		}
	},

	render_bar_graph: function(parent, data, field, label) {
		var args = {
			percent: data[field],
			label: __(label)
		}
		$(parent).append(repl(' \
			\
		', args));
	},
	render_icon: function(parent, icon_class, label) {
		var icon_html = "";
		$(parent).append(repl(icon_html, {icon_class: icon_class, label: __(label) || ''}));
	}
});
<commit_msg>[minor] fix image view, frappe/erpnext#7062<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.views.get_listview = function(doctype, parent) {
	if(frappe.listviews[doctype]) {
		var listview = new frappe.listviews[doctype](parent);
	} else {
		var listview = new frappe.views.ListView(parent, doctype);
	}
	return listview;
}

// Renders customized list
// usually based on `in_list_view` property

frappe.views.ListView = Class.extend({
	init: function(doclistview, doctype) {
		this.doclistview = doclistview;
		this.doctype = doctype;
		this.meta = frappe.get_doc("DocType", this.doctype);
		this.image_field = this.meta.image_field || 'image';
		this.settings = frappe.listview_settings[this.doctype] || {};
		if(this.meta.__listview_template) {
			this.template_name = doctype + "_listview";
			frappe.templates[this.template_name] = this.meta.__listview_template;
		}
		this.set_fields();
		this.set_columns();
		this.id_list = [];
		if(this.settings.group_by)
			this.group_by = this.settings.group_by;

		var me = this;
		this.doclistview.onreset = function() {
			me.id_list = [];
		}
		this.order_by = this.settings.order_by;
		this.group_by = this.settings.group_by;
	},
	set_fields: function() {
		var me = this;
		var t = "`tab"+this.doctype+"`.";
		this.fields = [];
		this.stats = ['_user_tags'];

		var add_field = function(fieldname) {
			field = t + "`" + fieldname + "`"
			if(me.fields.indexOf(field)=== -1)
				me.fields.push(field);
		}

		$.each(['name', 'owner', 'docstatus', '_user_tags', '_comments', 'modified',
			'modified_by', '_assign', '_liked_by', '_seen'],
		function(i, fieldname) { add_field(fieldname); })

		// add title field
		if(this.meta.title_field) {
			this.title_field = this.meta.title_field;
			add_field(this.meta.title_field);
		}

		// endabled / disabled
		if(frappe.meta.has_field(this.doctype, 'enabled')) { add_field('enabled'); };
		if(frappe.meta.has_field(this.doctype, 'disabled')) { add_field('disabled'); };

		// add workflow field (as priority)
		this.workflow_state_fieldname = frappe.workflow.get_state_fieldname(this.doctype);
		if(this.workflow_state_fieldname) {
			if (!frappe.workflow.workflows[this.doctype]["override_status"]) {
				add_field(this.workflow_state_fieldname);
			}
			this.stats.push(this.workflow_state_fieldname);
		}

		$.each(this.meta.fields, function(i,d) {
			if(d.in_list_view && frappe.perm.has_perm(me.doctype, d.permlevel, "read")) {
				if(d.fieldtype=="Image" && d.options) {
					add_field(d.options);
				} else {
					add_field(d.fieldname);
				}
				// currency field for symbol (multi-currency)
				if(d.fieldtype=="Currency" && d.options) {
					if(d.options.indexOf(":")!=-1) {
						add_field(d.options.split(":")[1]);
					} else {
						add_field(d.options);
					};
				}
			}
		});

		// additional fields
		if(this.settings.add_fields) {
			$.each(this.settings.add_fields, function(i, d) {
				if(d.indexOf("`tab")===-1) {
					d = "`tab" + me.doctype + "`." + d;
				}
				if(me.fields.indexOf(d)==-1)
					me.fields.push(d);
			});
		}
	},
	set_columns: function() {
		var me = this;
		this.columns = [];
		var name_column = {
			colspan: this.settings.colwidths && this.settings.colwidths.subject || 6,
			type: "Subject",
			title: "Name"
		};
		if (this.meta.title_field) {
			name_column.title = frappe.meta.get_docfield(this.doctype, this.meta.title_field).label;
		}
		this.columns.push(name_column);
		this.total_colspans = this.columns[0].colspan;

		if(frappe.has_indicator(this.doctype)) {
			// indicator
			this.columns.push({
				colspan: this.settings.colwidths && this.settings.colwidths.indicator || 3,
				type: "Indicator",
				title: "Status"
			});
			this.total_colspans += this.columns[1].colspan;
		}

		// overridden
		var overridden = $.map(this.settings.add_columns || [], function(d) {
			return d.content;
		});
		var docfields_in_list_view = frappe.get_children("DocType", this.doctype, "fields",
			{"in_list_view":1}).sort(function(a, b) { return a.idx - b.idx })

		$.each(docfields_in_list_view, function(i,d) {
			if(in_list(overridden, d.fieldname) || d.fieldname === me.title_field) {
				return;
			}
			if(me.total_colspans < 12) {
				me.add_column(d);
			}
		});

		// additional columns
		if(this.settings.add_columns) {
			$.each(this.settings.add_columns, function(i, d) {
				if(me.total_colspans < 12) {
					if(typeof d==="string") {
						me.add_column(frappe.meta.get_docfield(me.doctype, d));
					} else {
						me.columns.push(d);
						me.total_colspans += parseInt(d.colspan);
					}
				}
			});
		}

		var empty_cols = flt(12 - this.total_colspans);
		while(empty_cols > 0) {
			for(var i=0, l=this.columns.length; i < l && empty_cols > 0; i++) {
				this.columns[i].colspan = cint(this.columns[i].colspan) + 1;
				empty_cols = empty_cols - 1;
			}
		}
	},
	add_column: function(df) {
		// field width
		var colspan = 3;
		if(in_list(["Int", "Percent"], df.fieldtype)) {
			colspan = 2;
		} else if(in_list(["Check", "Image"], df.fieldtype)) {
			colspan = 1;
		} else if(in_list(["name", "subject", "title"], df.fieldname)) { // subjects are longer
			colspan = 4;
		} else if(df.fieldtype=="Text Editor" || df.fieldtype=="Text") {
			colspan = 4;
		}
		if(df.columns && df.columns>0){
			colspan = df.columns;
		}
		else if(this.settings.column_colspan && this.settings.column_colspan[df.fieldname]) {
			colspan = this.settings.column_colspan[df.fieldname];
		}
		this.total_colspans += parseInt(colspan);
		var col = {
			colspan: colspan,
			content: df.fieldname,
			type: df.fieldtype,
			df:df,
			fieldtype: df.fieldtype,
			fieldname: df.fieldname,
			title:__(df.label)
		};
		if(this.settings.column_render && this.settings.column_render[df.fieldname]) {
			col.render = this.settings.column_render[df.fieldname];
		}
		this.columns.push(col);

	},
	render: function(row, data) {
		this.prepare_data(data);

		// maintain id_list to avoid duplication incase
		// of filtering by child table
		if(in_list(this.id_list, data.name)) {
			$(row).toggle(false);
			return;
		} else {
			this.id_list.push(data.name);
		}

		this['render_row_' + this.doclistview.current_view](row, data);

		if(this.settings.post_render_item) {
			this.settings.post_render_item(this, row, data);
		}

		this.render_tags(row, data);

	},
	render_row_List: function(row, data) {
		var main = frappe.render_template("list_item_main", {
			data: data,
			columns: this.columns,
			subject: this.get_avatar_and_id(data, true),
			list: this,
			right_column: this.settings.right_column
		});

		$(frappe.render_template("list_item_row", {
			data: data,
			main: main,
			list: this,
			right_column: this.settings.right_column
		})).appendTo(row);
	},
	render_row_Image: function(row, data) {
		this.allowed_type = [
			"Check", "Currency", "Data", "Date",
			"Datetime", "Float", "Int", "Link",
			"Percent", "Select", "Read Only", "Time"
		];
		var image_url = (data.image && window.cordova && data.image.indexOf('http')===-1) ?
			frappe.base_url + data[this.image_field] : data[this.image_field];

		img_col = $(frappe.render_template("image_view_item_row", {
			data: data,
			list: this,
			columns: this.columns,
			allowed_type: this.allowed_type,
			item_image: image_url ? "url('" + image_url + "')" : null,
			color: frappe.get_palette(data.item_name),
			subject: this.get_avatar_and_id(data, true),
			right_column: this.settings.right_column
		}))
		.data("data", data)
		.appendTo($(row).find(".image-view-marker"));
	},
	render_tags: function(row, data) {
		var me = this;
		var row2 = $('
\

\

\

').appendTo(row);

		if(!me.doclistview.tags_shown) {
			row2.addClass("hide");
		}

		// add tags
		var tag_editor = new frappe.ui.TagEditor({
			parent: row2.find(".list-tag"),
			frm: {
				doctype: this.doctype,
				docname: data.name
			},
			list_sidebar: me.doclistview.list_sidebar,
			user_tags: data._user_tags,
			on_change: function(user_tags) {
				data._user_tags = user_tags;
				//me.render_timestamp_and_comments(row, data);
			}
		});
		tag_editor.wrapper.on("click", ".tagit-label", function() {
			me.doclistview.set_filter("_user_tags",
				$(this).text());
		});
	},

	get_avatar_and_id: function(data, without_workflow) {
		data._without_workflow = without_workflow;
		data.css_seen = '';

		if(data._seen) {
			var seen = JSON.parse(data._seen);
			if(seen && seen.indexOf(frappe.session.user) !== -1) {
				data.css_seen = 'seen'
			}
		}

		return frappe.render_template("list_item_subject", data);
	},

	get_indicator: function(doc) {
        var indicator = frappe.get_indicator(doc, this.doctype);
		if(indicator) {
	        return ''+__(indicator[0])+'';
		} else {
			return "";
		}
	},

	get_indicator_dot: function(doc) {
		var indicator = frappe.get_indicator(doc, this.doctype);
		if (!indicator) {
			return "";
		}
		return '';
	},

	prepare_data: function(data) {
		if(data.modified)
			this.prepare_when(data, data.modified);

		data._liked_by = data._liked_by ?
			JSON.parse(data._liked_by) : [];

		data._checkbox = (frappe.model.can_delete(this.doctype) || this.settings.selectable) && !this.no_delete

		data._doctype_encoded = encodeURIComponent(data.doctype);
		data._name = data.name.replace(/"/g, '\"');
		data._name_encoded = encodeURIComponent(data.name);
		data._submittable = frappe.model.is_submittable(this.doctype);

		data._title = strip_html(data[this.title_field || "name"] || data["name"]);
		data._full_title = data._title;

		if(data._title.length > 40) {
			data._title = data._title.slice(0, 40) + "...";
		}

		data._workflow = null;
		if(this.workflow_state_fieldname) {
			data._workflow = {
				fieldname: this.workflow_state_fieldname,
				value: data[this.workflow_state_fieldname],
				style: frappe.utils.guess_style(data[this.workflow_state_fieldname])
			}
		}
		data._user = user;

		data._tags = $.map((data._user_tags || "").split(","),
			function(v) { return v ? v : null; });
		data._assign_list = data._assign ? JSON.parse(data._assign) : [];

		// nulls as strings
		for(key in data) {
			if(data[key]==null) {
				data[key]='';
			}
		}

		// prepare data in settings
		if(this.settings.prepare_data)
			this.settings.prepare_data(data);
	},

	prepare_when: function(data, date_str) {
		if (!date_str) date_str = data.modified;
		// when
		data.when = (dateutil.str_to_user(date_str)).split(' ')[0];
		var diff = dateutil.get_diff(dateutil.get_today(), date_str.split(' ')[0]);
		if(diff==0) {
			data.when = comment_when(date_str);
		}
		if(diff == 1) {
			data.when = __('Yesterday')
		}
		if(diff == 2) {
			data.when = __('2 days ago')
		}
	},

	render_bar_graph: function(parent, data, field, label) {
		var args = {
			percent: data[field],
			label: __(label)
		}
		$(parent).append(repl(' \
			\
		', args));
	},
	render_icon: function(parent, icon_class, label) {
		var icon_html = "";
		$(parent).append(repl(icon_html, {icon_class: icon_class, label: __(label) || ''}));
	}
});
<|endoftext|>


<commit_before>describe('references', function () {
  var Observable = require('../../../../../lib/observable')
  var measure = {
    obs: {}
  }
  var referencedObs, referencedObs2, obs

  it('create reference observables', function () {
    measure.obs.val = 0
    referencedObs = new Observable({
      key: 'referencedObs',
      val: 'a string'
    })
    obs = new Observable({
      key: 'obs2',
      on: {
        data: {
          val: function () {
            measure.obs.val++
          }
        }
      },
      val: referencedObs
    })
    expect(measure.obs.val).msg('val listener').to.equal(0)
    expect(obs).to.have.property('listensOnBase')
  })

  it('should have added a listener on the referenced observable', function () {
    expect(referencedObs._on.data.base).ok
    expect(referencedObs._on.data.base[1]).equals(obs)
  })

  it('should have correct listen object', function () {
    var keyCount = 0
    obs.listensOnBase.each(function (property, key) {
      keyCount++
    })
    expect(keyCount).msg('amount of emitters on listensOnBase').to.equal(1)
    expect(obs.listensOnBase[1]).msg('equal referencedObs change emitter')
      .to.equal(referencedObs._on.data)
  })

  it('should create the correct key for the listener', function () {
    expect(obs.listensOnBase).to.have.property(1)
  })

  it('changing value on referenced observable should fire listener', function () {
    referencedObs.val = 'changed a string'
    expect(measure.obs.val).msg('val listener').to.equal(1)
  })

  it('changing value to another observable should fire listeners', function () {
    referencedObs2 = new Observable({
      key: 'referencedObs',
      val: 'a string'
    })
    obs.val = referencedObs2
    expect(measure.obs.val).msg('val listener').to.equal(2)
  })

  it('should have added listeners on the new referenced object', function () {
    expect(referencedObs2._on.data.base).be.ok
    expect(referencedObs2._on.data.base[1]).equals(obs)
  })

  it('should have removed listeners on the previous value', function () {
    expect(referencedObs._on.data.base).not.ok
  })

  it('should have correct listen object', function () {
    var keyCount = 0
    obs.listensOnBase.each(function (property, key) {
      keyCount++
    })
    expect(keyCount).msg('amount of emitters on listensOnBase').to.equal(1)
    expect(obs.listensOnBase[2]).msg('equal referencedObs2 change emitter')
      .to.equal(referencedObs2._on.data)
  })

  it('should not fire when val is the same', function () {
    obs.val = referencedObs2
    expect(measure.obs.val).msg('val listener').to.equal(2)
  })

  it('should fire when changing referenced observable', function () {
    referencedObs2.val = 'changed a string'
    expect(measure.obs.val).msg('val listener').to.equal(3)
  })
})
<commit_msg>refactored reference tests direct/emitter<commit_after>describe('references', function () {
  var Observable = require('../../../../../lib/observable')
  var measure = {
    obs: {}
  }
  var referencedObs, referencedObs2, obs

  it('create reference observables', function () {
    measure.obs.val = 0
    referencedObs = new Observable({
      key: 'referencedObs',
      val: 'a string'
    })
    obs = new Observable({
      key: 'obs2',
      on: {
        data: {
          val: function () {
            measure.obs.val++
          }
        }
      },
      val: referencedObs
    })
    expect(measure.obs.val).msg('val listener').to.equal(0)
    expect(obs).to.have.property('listensOnBase')
  })

  it('should have added a listener on the referenced observable', function () {
    expect(referencedObs._on.data.base).ok
    expect(referencedObs._on.data.base[obs.uid]).equals(obs)
  })

  it('should have correct listen object', function () {
    var keyCount = 0
    obs.listensOnBase.each(function (property, key) {
      keyCount++
    })
    expect(keyCount).msg('amount of emitters on listensOnBase').to.equal(1)
    expect(obs.listensOnBase[1]).msg('equal referencedObs change emitter')
      .to.equal(referencedObs._on.data)
  })

  it('should create the correct key for the listener', function () {
    expect(obs.listensOnBase).to.have.property(1)
  })

  it('changing value on referenced observable should fire listener', function () {
    referencedObs.val = 'changed a string'
    expect(measure.obs.val).msg('val listener').to.equal(1)
  })

  it('changing value to another observable should fire listeners', function () {
    referencedObs2 = new Observable({
      key: 'referencedObs',
      val: 'a string'
    })
    obs.val = referencedObs2
    expect(measure.obs.val).msg('val listener').to.equal(2)
  })

  it('should have added listeners on the new referenced object', function () {
    expect(referencedObs2._on.data.base).be.ok
    expect(referencedObs2._on.data.base[obs.uid]).equals(obs)
  })

  it('should have removed listeners on the previous value', function () {
    expect(referencedObs._on.data.base).not.ok
  })

  it('should have correct listen object', function () {
    var keyCount = 0
    obs.listensOnBase.each(function (property, key) {
      keyCount++
    })
    expect(keyCount).msg('amount of emitters on listensOnBase').to.equal(1)
    expect(obs.listensOnBase[2]).msg('equal referencedObs2 change emitter')
      .to.equal(referencedObs2._on.data)
  })

  it('should not fire when val is the same', function () {
    obs.val = referencedObs2
    expect(measure.obs.val).msg('val listener').to.equal(2)
  })

  it('should fire when changing referenced observable', function () {
    referencedObs2.val = 'changed a string'
    expect(measure.obs.val).msg('val listener').to.equal(3)
  })
})
<|endoftext|>