<commit_before>/*
 *  Manifest - organize a program of songs for an ensemble
 */

function Manifest(manifest) {

	var manifest = manifest ;

	var __Manifest = function(that) {
		that.manifest = this.manifest ;
		console.log('Creating manifest ', that.manifest) ;
	}(this) ;

    this.displaySong = function(song, baseUrl) {

    	console.log('song is ', song) ;

		var scoreIndex,
		    songIndex,
		    score,
		    part,
		    href,
			webDir = baseUrl + song.fileLocation + '/pdf/',
		    html = '
' + song.title + '
' +
				"
Composed by " + song.composer ;

		if ( song.hasOwnProperty('arranger') &&
			 song.arranger !== '' &&
			 song.composer !== song.arranger ) {
			html += ', Arranged by ' + song.arranger ;
		}

		html += "
\n" ;

		if ( song.hasOwnProperty('recordings') ) {
			console.log('        it says we have song.recordings:', song.recordings) ;
			html += this.displayRecordings(song) ;
		}

		html += this.displayScoresAndParts(song, baseUrl) ;

		return html ;
	} ;

	this.displayRecordings = function(song) {

		var name,
			recording,
			href,
			html = "
Recordings
\n
\n" ;

		for ( name in song.recordings ) {
	 		recording = song.recordings[name] ;
			href = recordings[name] ;
			html += '
' + name + "
\n" ;
		};

		html += "
\n" ;

		return html ;
	} ;

	this.getBaseUrl = function(song) {

		if ( song.hasOwnProperty('baseUrl') && song.baseUrl !== '' ) {
			return song.baseUrl ;
		}
		if ( this.manifest.hasOwnProperty('baseUrl') && this.manifest.baseUrl !== '' ) {
			return this.manifest.baseUrl ;
		}
		return '' ;
	} ;

	this.displayScoresAndParts = function(song, baseUrl) {

		var name,
			score,
			href,
			baseUrl = '',
			html = "
Scores
\n
\n" ;

		for ( name in song.scores ) {
	 		score = song.scores[name] ;
			href = this.getBaseUrl(song) + song.filePrefix + score.fileSuffix + '.pdf' ;
			html += '
' + name + "
\n" ;
		}

		html += "
\n
Parts
\n" ;

		for ( name in song.parts ) {
			part = song.parts[name] ;
			href = this.getBaseUrl(song) + song.filePrefix + part.fileSuffix + '.pdf' ;
			html += '
' + name + "
\n" ;
		};
		html += "
\n" ;

		return html ;
	} ;

	this.displayProgram = function() {

		console.log('in displayProgram with this.manifest', this.manifest,
		    "\n    and this.manifest.songs ", this.manifest.songs,
		    "\n    and this.manifest.programOrder ", this.manifest.programOrder,
		    "\n    and this.manifest.programOrder.length ", this.manifest.programOrder.length ) ;

		var programIndex, number, songIndex, song, baseUrl, html ;
		for ( programIndex = 0 ; programIndex < this.manifest.programOrder.length ; programIndex++ ) {

			number = this.manifest.programOrder[programIndex] ;
			songIndex = this.manifest.program[number] ;
			console.log('        got songIndex ' + songIndex) ;

			song = this.manifest.songs[songIndex] ;
			console.log('        got song ', song) ;

			html += this.displaySong(song) ;
			console.log('in displayProgram with number ' + number +
				', songIndex ' + songIndex +
				', this.manifest.songs ', this.manifest.songs +
				' and song ' + song) ;
		}

		return html ;
	} ;

	this.displayPartsInBook = function(chair, partsLists) {

		var songId,
			song,
			partsList,
			partIndex,
			part,
			href,
			html = '
' + chair + '
' +
				"\n\n
\n" ;

		Object.keys(partsLists).forEach(function(songId) {

	    	song = this.manifest.song[songId] ;
			partsList = partsLists[songId] ;
			html += '
' + song.title ;
			for ( partIndex = 0 ; partIndex < partsList.length ; partIndex++ ) {
				part = partsList[partIndex] ;
				href = webDir + song.filePrefix + song.parts[part].fileSuffix + '.pdf' ;
				html += ' ' + part + '' ;
				if ( partIndex+1 < partsList.length ) {
					html += ',' ;
				}
			}
			html += "
\n" ;
		});

		html += "
\n" ;

		return html ;
	} ;

	this.displayPartsInBooks = function() {

		var html, key,
			books = this.manifest.partsInBooks ;

		for ( key in books ) {

			if ( books.hasOwnProperty(key) ) {

				html += this.displayPartsInBook( key, books[key] ) ;

			}
		}
	} ;

	this.displayManifest = function() {
		this.displayProgram() ;
		this.displayPartsInBooks() ;
	}
}

<commit_msg>incremental edits<commit_after>/*
 *  Manifest - organize a program of songs for an ensemble
 */

function Manifest(manifest) {

	var manifest = manifest ;

	var __Manifest = function(that) {
		that.manifest = this.manifest ;
		console.log('Creating manifest ', that.manifest) ;
	}(this) ;

    this.displaySong = function(song, baseUrl) {

    	console.log('song is ', song) ;

		var scoreIndex,
		    songIndex,
		    score,
		    part,
		    href,
			webDir = baseUrl + song.fileLocation + '/pdf/',
		    html = '
' + song.title + '
' +
				"
Composed by " + song.composer ;

		if ( song.hasOwnProperty('arranger') &&
			 song.arranger !== '' &&
			 song.composer !== song.arranger ) {
			html += ', Arranged by ' + song.arranger ;
		}

		html += "
\n" ;

		if ( song.hasOwnProperty('recordings') ) {
			html += this.displayRecordings(song) ;
		}

		html += this.displayScoresAndParts(song, baseUrl) ;

		return html ;
	} ;

	this.displayRecordings = function(song) {

		var name,
			recording,
			href,
			html = "
Recordings
\n
\n" ;

		console.log('In displayRecordings, song is ', song,
			'and song.recordings is ', song.recordings ) ;

		for ( name in song.recordings ) {
			console.log('    looping through recording names:', name) ;
	 		recording = song.recordings[name] ;
			href = recordings[name] ;
			html += '
' + name + "
\n" ;
		};

		html += "
\n" ;

		return html ;
	} ;

	this.getBaseUrl = function(song) {

		if ( song.hasOwnProperty('baseUrl') && song.baseUrl !== '' ) {
			return song.baseUrl ;
		}
		if ( this.manifest.hasOwnProperty('baseUrl') && this.manifest.baseUrl !== '' ) {
			return this.manifest.baseUrl ;
		}
		return '' ;
	} ;

	this.displayScoresAndParts = function(song, baseUrl) {

		var name,
			score,
			href,
			baseUrl = '',
			html = "
Scores
\n
\n" ;

		for ( name in song.scores ) {
	 		score = song.scores[name] ;
			href = this.getBaseUrl(song) + song.filePrefix + score.fileSuffix + '.pdf' ;
			html += '
' + name + "
\n" ;
		}

		html += "
\n
Parts
\n" ;

		for ( name in song.parts ) {
			part = song.parts[name] ;
			href = this.getBaseUrl(song) + song.filePrefix + part.fileSuffix + '.pdf' ;
			html += '
' + name + "
\n" ;
		};
		html += "
\n" ;

		return html ;
	} ;

	this.displayProgram = function() {

		console.log('in displayProgram with this.manifest', this.manifest,
		    "\n    and this.manifest.songs ", this.manifest.songs,
		    "\n    and this.manifest.programOrder ", this.manifest.programOrder,
		    "\n    and this.manifest.programOrder.length ", this.manifest.programOrder.length ) ;

		var programIndex, number, songIndex, song, baseUrl, html ;
		for ( programIndex = 0 ; programIndex < this.manifest.programOrder.length ; programIndex++ ) {

			number = this.manifest.programOrder[programIndex] ;
			songIndex = this.manifest.program[number] ;
			console.log('        got songIndex ' + songIndex) ;

			song = this.manifest.songs[songIndex] ;
			console.log('        got song ', song) ;

			html += this.displaySong(song) ;
			console.log('in displayProgram with number ' + number +
				', songIndex ' + songIndex +
				', this.manifest.songs ', this.manifest.songs +
				' and song ' + song) ;
		}

		return html ;
	} ;

	this.displayPartsInBook = function(chair, partsLists) {

		var songId,
			song,
			partsList,
			partIndex,
			part,
			href,
			html = '
' + chair + '
' +
				"\n\n
\n" ;

		Object.keys(partsLists).forEach(function(songId) {

	    	song = this.manifest.song[songId] ;
			partsList = partsLists[songId] ;
			html += '
' + song.title ;
			for ( partIndex = 0 ; partIndex < partsList.length ; partIndex++ ) {
				part = partsList[partIndex] ;
				href = webDir + song.filePrefix + song.parts[part].fileSuffix + '.pdf' ;
				html += ' ' + part + '' ;
				if ( partIndex+1 < partsList.length ) {
					html += ',' ;
				}
			}
			html += "
\n" ;
		});

		html += "
\n" ;

		return html ;
	} ;

	this.displayPartsInBooks = function() {

		var html, key,
			books = this.manifest.partsInBooks ;

		for ( key in books ) {

			if ( books.hasOwnProperty(key) ) {

				html += this.displayPartsInBook( key, books[key] ) ;

			}
		}
	} ;

	this.displayManifest = function() {
		this.displayProgram() ;
		this.displayPartsInBooks() ;
	}
}

<|endoftext|>


<commit_before>define({
    options: {
        title: "",
        displayQuickAddButton : false,
        displaySearchbox: false,
        onHeaderClick : function(){S.tool.getDialog("#update-fiche-information-dialog").showModal()}
    },
    route: {
        data: function () {
            var ret;
            var deferred = new $.Deferred()
            var ficheId = this.$route.params.fiche_id;
            S.db.config.getUsers().then(function(userlist){
              console.log(userlist);
            //S.db.config.getUsers().then(function(userlist){              console.log(userlist);
              S.db.fiches.getByID(ficheId).then(function (doc) {
                console.log(doc);
                S.vue.router.app.$children[0].$data.options.title = doc.patient.firstname +" "+ doc.patient.lastname;
                ret = {
                  fiche:doc,
                  user:S.user._current,
                  history: [],
                  config : S.config.fiche,
                  lang : S.lang,
                  users : userlist
                };
                console.log(ret);
                deferred.resolve(ret);
                if(!ret.fiche.origin || ret.fiche.origin === ""){ // L'ogine n'est pas saisie on force la saisie
                    S.tool.getDialog("#add-origin-dialog").showModal();
                }
                /*
                console.log("Fetching change for fiche in background ... ",ret.fiche, this)
                S.db.fiches.getChanges(ret.fiche._id).then(function (changes) {
                  console.log(changes)
                  ret.history.push("Done ("+changes.results.length+"/"+changes.last_seq+")");
                  console.log(ret);
                }).catch(function (err) {
                  console.log(err);
                });
                */
              });

            })
            return deferred.promise();
        }
    },
    computed: {
      _patient_age: function () {
        return moment(this.fiche.patient.birthdate).fromNow(true)
      },
      _last_update: function () { //Get the timestamp of the last update and format it to be shown
        return (this.fiche.events.length>0)? moment(this.fiche.events[this.fiche.events.length-1].timestamp).fromNow():"" ;//TODO better order and get the most new timestamp other than the last el in array
      }
    },
    methods: {
      showUpdateInformation: function () {
          S.tool.getDialog("#update-fiche-information-dialog").showModal();
      },
      closeUpdateInformation: function () {
          var data = this._data
          S.tool.getDialog("#update-fiche-information-dialog").close();
          S.db.fiches.getByID(this.$route.params.fiche_id).then(function (doc) {
            $.extend(true,data.fiche, doc) //Reset to what is in localDB
          });
      },
      changeInformation: function () {
        var ask= (!S.config.local["ask-for"]["changeInformation-validation"] || confirm(S.lang["ask-confirm"]+" ?")); //TODO replace with navigator.notification.confirm
        if(ask){
          console.log(this._data.fiche);
          this._data.fiche.events.push({
            type : "action",
            action : "changeInformation",
            message : S.user._current.name+" a mis à jour les informations : {TODO}", //TODO make diff between in DB and in Vue object
            timestamp : Date.now(),
            user :  S.user._current.name
          })
          //Update this._data.fiche with additionnal data from data or update them
          //$.extend(true, this._data.fiche, data); //TODO be more strict on wath can be edited
          //DATA is already updated by vue in live
          S.vue.router.app.$children[0].$data.options.title = this._data.fiche.patient.firstname +" "+ this._data.fiche.patient.lastname;
          S.tool.getDialog("#update-fiche-information-dialog").close();

          S.db.fiches.put(this._data.fiche);//Saving
        }
      },
      changePrimaryAffection: function (event) {
        var newPrimaryID = $(event.srcElement).val();
        var oldPrimary = S.lang.fiche.pathologys[this._data.fiche.primaryAffection] || this._data.fiche.primaryAffection;
        var newPrimary = S.lang.fiche.pathologys[newPrimaryID] || newPrimaryID;
        var ask= (!S.config.local["ask-for"]["changePrimaryAffection-validation"] || confirm(S.lang["ask-confirm-choice"]+""+newPrimary+" ?"));  //TODO replace with navigator.notification.confirm
        if(ask){
            console.log(this._data.fiche);
            this._data.fiche.events.push({
              type : "action",
              action : "changePrimaryAffection",
              message : S.user._current.name+" "+S.lang.log["change-primary"]+" "+oldPrimary+" "+S.lang["to"]+" "+newPrimary+"",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            this._data.fiche.primaryAffection = newPrimaryID;
            S.db.fiches.put(this._data.fiche);
        }
      },
      addOrigin: function (event) {
        var origin = $(event.srcElement).text();
        var originId = $.trim($(event.srcElement).attr("data-id"));
        S.tool.getDialog("#add-origin-dialog").close();
        var ask= (!S.config.local["ask-for"]["addOrigin-validation"] || confirm(S.lang["ask-confirm-choice"]+" : "+origin+" ?"));
        if(ask){
            console.log(this._data.fiche);
            this._data.fiche.events.push({
              type : "action",
              action : "addOrigin",
              message : S.user._current.name+" "+S.lang.log['set-origin']+" : "+origin+"",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            this._data.fiche.origin = originId;
            S.db.fiches.put(this._data.fiche);
        }
      },
      showAddPathologyModal: function () {
          S.tool.getDialog("#add-path-dialog").showModal();
      },
      closeAddPathologyModal: function () {
          S.tool.getDialog("#add-path-dialog").close();
      },
      addPathology: function (event) {
        //TODO check if already exist and display it
        var el = $(event.srcElement);
        if(! el.is(".mdl-list__item-primary-content")){ //Find the content if it is the li that trigger
          el = el.find(".mdl-list__item-primary-content");
        }
        var path = $.trim(el.text());
        var pathId = $.trim(el.attr("data-id"));
        S.tool.getDialog("#add-path-dialog").close();
        var ask= !S.config.local["ask-for"]["addPathology-validation"] || confirm("Etes-vous sûr d'ajouter "+path+" ?");
        if(ask){
            console.log(this._data.fiche);
            this._data.fiche.events.push({
              type : "action",
              action : "addPathology",
              message : S.user._current.name+" "+S.lang.log["add-path"]+" : "+path+"",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            if(this._data.fiche.pathologys.length === 0){
               this._data.fiche.primaryAffection = pathId; // By default we use the first added patho
            }
            this._data.fiche.pathologys.push(pathId);
            S.db.fiches.put(this._data.fiche);

            //Update ui if needed by interface
            if(typeof S.platform.events.afterPageLoad === "function"){
                S.platform.events.afterPageLoad();
            }

        }
       },
      reopen: function () {
         var ask= !S.config.local["ask-for"]["reopen-validation"] || confirm(S.lang["ask-confirm"]+" ?");
         if(ask){
             console.log(this._data.fiche);
             this._data.fiche.events.push({
               type : "action",
               action : "reopen",
               message : S.user._current.name+" "+S.lang.log["reopen-fiche"]+".",
               timestamp : Date.now(),
               user :  S.user._current.name
             })
             this._data.fiche.closed = false;
             this._data.fiche.close_context = {};
             S.db.fiches.put(this._data.fiche);
         }
       },
      undelete: function () {
        if(S.user._current.isAdmin()){
          //We are admin
          var ask= !S.config.local["ask-for"]["delete-validation"] || confirm("Etes-vous sûr d'annuler la suppression de la fiche ?");
          if(ask){
            this._data.fiche.deleted = false;
            this._data.fiche.events.push({
              type : "action",
              action : "undelete",
              message : S.user._current.name+" "+S.lang.log["cancel-del"]+".",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            S.db.fiches.put(this._data.fiche);
          }
        }else{
          //Else we do nothing
        }
      },
      delete: function () {
        if(S.user._current.isAdmin()){
          //We are admin
          var ask= !S.config.local["ask-for"]["delete-validation"] || confirm("Etes-vous sûr de supprimer la fiche ?");
          if(ask){
            this._data.fiche.deleted = true;
            this._data.fiche.events.push({
              type : "action",
              action : "delete",
              message : S.user._current.name+" "+S.lang.log["del-fiche"]+".",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            S.db.fiches.put(this._data.fiche);
          }
        }else{
          //Else we do nothing
        }
      },
      closeCloseModal: function () {
           S.tool.getDialog("#close-fiche-dialog").close();
      },
      submitClose: function () {
        S.tool.getDialog("#close-fiche-dialog").close();
        this._data.fiche.closed = true;
        var close_context = {};
        $.each($("#close-fiche-dialog form").serializeArray(), function(id,value){
          close_context[value.name] = value.value;
        });
        this._data.fiche.close_context = close_context;
        this._data.fiche.events.push({
          type : "action",
          action : "close",
          message : S.user._current.name+" "+S.lang.log["close-fiche"]+".",
          close_context : this._data.fiche.close_context,
          timestamp : Date.now(),
          user :  S.user._current.name
        })

        S.db.fiches.put(this._data.fiche);
      },
      close: function () {
          S.tool.getDialog("#close-fiche-dialog").showModal();
      },
      take: function () {
         var ask= !S.config.local["ask-for"]["take-validation"] || confirm(S.lang["ask-confirm"]+" ?");
         if(ask){
             console.log(this._data.fiche);
             this._data.fiche.events.push({
               type : "action",
               action : "take",
               message : S.user._current.name+" "+S.lang.log["take-fiche-from"]+" "+this._data.fiche.owner_id,
               timestamp : Date.now(),
               user :  S.user._current.name
             })
             this._data.fiche.owner_id = S.user._current.name
             S.db.fiches.put(this._data.fiche);
         }
      },
      setGiveForm : function(event){
        this._data.fiche.owner_id = $.trim($(event.srcElement).text());
      },
      giveTicket : function(){
      var fiche = this._data.fiche;
       var ask= !S.config.local["ask-for"]["give-validation"] || confirm("Etes-vous sûr de tranferer à "+fiche.owner_id+" ?");
         S.db.fiches.getByID(this.$route.params.fiche_id).then(function (old) {
           if(ask){ //We have consent or it's auto-validate by config
               console.log(fiche);
               fiche.events.push({
                 type : "action",
                 action : "take",
                 message : S.user._current.name+" "+S.lang.log["give-fiche-to"]+" "+ fiche.owner_id +" ("+S.lang.log["old-prop"]+" : "+old.owner_id+")",
                 timestamp : Date.now(),
                 user :  S.user._current.name
               })
               S.db.fiches.put(fiche);
            }else{
              $.extend(true,fiche, old) //Reset to what is in localDB
            }
            S.tool.getDialog("#give-ticket-dialog").close();
       });
      },
      cancelGiveForm : function(){
        var data = this._data
        S.db.fiches.getByID(this.$route.params.fiche_id).then(function (doc) {
          $.extend(true,data.fiche, doc) //Reset to what is in localDB
        });
        S.tool.getDialog("#give-ticket-dialog").close()
      },
      showGiveModal: function () {
        S.tool.getDialog("#give-ticket-dialog").showModal();
      }
    }
})
<commit_msg>Implement the possibity the add checkin event<commit_after>define({
    options: {
        title: "",
        displayQuickAddButton : false,
        displaySearchbox: false,
        onHeaderClick : function(){S.tool.getDialog("#update-fiche-information-dialog").showModal()}
    },
    route: {
        data: function () {
            var ret;
            var deferred = new $.Deferred()
            var ficheId = this.$route.params.fiche_id;
            S.db.config.getUsers().then(function(userlist){
              console.log(userlist);
            //S.db.config.getUsers().then(function(userlist){              console.log(userlist);
              S.db.fiches.getByID(ficheId).then(function (doc) {
                console.log(doc);
                S.vue.router.app.$children[0].$data.options.title = doc.patient.firstname +" "+ doc.patient.lastname;
                ret = {
                  fiche:doc,
                  user:S.user._current,
                  history: [],
                  config : S.config.fiche,
                  lang : S.lang,
                  users : userlist
                };
                console.log(ret);
                deferred.resolve(ret);
                if(!ret.fiche.origin || ret.fiche.origin === ""){ // L'ogine n'est pas saisie on force la saisie
                    S.tool.getDialog("#add-origin-dialog").showModal();
                }
                /*
                console.log("Fetching change for fiche in background ... ",ret.fiche, this)
                S.db.fiches.getChanges(ret.fiche._id).then(function (changes) {
                  console.log(changes)
                  ret.history.push("Done ("+changes.results.length+"/"+changes.last_seq+")");
                  console.log(ret);
                }).catch(function (err) {
                  console.log(err);
                });
                */
              });

            })
            return deferred.promise();
        }
    },
    computed: {
      _patient_age: function () {
        return moment(this.fiche.patient.birthdate).fromNow(true)
      },
      _last_update: function () { //Get the timestamp of the last update and format it to be shown
        return (this.fiche.events.length>0)? moment(this.fiche.events[this.fiche.events.length-1].timestamp).fromNow():"" ;//TODO better order and get the most new timestamp other than the last el in array
      }
    },
    methods: {
      showUpdateInformation: function () {
          S.tool.getDialog("#update-fiche-information-dialog").showModal();
      },
      closeUpdateInformation: function () {
          var data = this._data
          S.tool.getDialog("#update-fiche-information-dialog").close();
          S.db.fiches.getByID(this.$route.params.fiche_id).then(function (doc) {
            $.extend(true,data.fiche, doc) //Reset to what is in localDB
          });
      },
      changeInformation: function () {
        var ask= (!S.config.local["ask-for"]["changeInformation-validation"] || confirm(S.lang["ask-confirm"]+" ?")); //TODO replace with navigator.notification.confirm
        if(ask){
          console.log(this._data.fiche);
          this._data.fiche.events.push({
            type : "action",
            action : "changeInformation",
            message : S.user._current.name+" a mis à jour les informations : {TODO}", //TODO make diff between in DB and in Vue object
            timestamp : Date.now(),
            user :  S.user._current.name
          })
          //Update this._data.fiche with additionnal data from data or update them
          //$.extend(true, this._data.fiche, data); //TODO be more strict on wath can be edited
          //DATA is already updated by vue in live
          S.vue.router.app.$children[0].$data.options.title = this._data.fiche.patient.firstname +" "+ this._data.fiche.patient.lastname;
          S.tool.getDialog("#update-fiche-information-dialog").close();

          S.db.fiches.put(this._data.fiche);//Saving
        }
      },
      changePrimaryAffection: function (event) {
        var newPrimaryID = $(event.srcElement).val();
        var oldPrimary = S.lang.fiche.pathologys[this._data.fiche.primaryAffection] || this._data.fiche.primaryAffection;
        var newPrimary = S.lang.fiche.pathologys[newPrimaryID] || newPrimaryID;
        var ask= (!S.config.local["ask-for"]["changePrimaryAffection-validation"] || confirm(S.lang["ask-confirm-choice"]+""+newPrimary+" ?"));  //TODO replace with navigator.notification.confirm
        if(ask){
            console.log(this._data.fiche);
            this._data.fiche.events.push({
              type : "action",
              action : "changePrimaryAffection",
              message : S.user._current.name+" "+S.lang.log["change-primary"]+" "+oldPrimary+" "+S.lang["to"]+" "+newPrimary+"",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            this._data.fiche.primaryAffection = newPrimaryID;
            S.db.fiches.put(this._data.fiche);
        }
      },
      addOrigin: function (event) {
        var origin = $(event.srcElement).text();
        var originId = $.trim($(event.srcElement).attr("data-id"));
        S.tool.getDialog("#add-origin-dialog").close();
        var ask= (!S.config.local["ask-for"]["addOrigin-validation"] || confirm(S.lang["ask-confirm-choice"]+" : "+origin+" ?"));
        if(ask){
            console.log(this._data.fiche);
            this._data.fiche.events.push({
              type : "action",
              action : "addOrigin",
              message : S.user._current.name+" "+S.lang.log['set-origin']+" : "+origin+"",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            this._data.fiche.origin = originId;
            S.db.fiches.put(this._data.fiche);
        }
      },
      showAddPathologyModal: function () {
          S.tool.getDialog("#add-path-dialog").showModal();
      },
      closeAddPathologyModal: function () {
          S.tool.getDialog("#add-path-dialog").close();
      },
      addPathology: function (event) {
        //TODO check if already exist and display it
        var el = $(event.srcElement);
        if(! el.is(".mdl-list__item-primary-content")){ //Find the content if it is the li that trigger
          el = el.find(".mdl-list__item-primary-content");
        }
        var path = $.trim(el.text());
        var pathId = $.trim(el.attr("data-id"));
        S.tool.getDialog("#add-path-dialog").close();
        var ask= !S.config.local["ask-for"]["addPathology-validation"] || confirm("Etes-vous sûr d'ajouter "+path+" ?");
        if(ask){
            console.log(this._data.fiche);
            this._data.fiche.events.push({
              type : "action",
              action : "addPathology",
              message : S.user._current.name+" "+S.lang.log["add-path"]+" : "+path+"",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            if(this._data.fiche.pathologys.length === 0){
               this._data.fiche.primaryAffection = pathId; // By default we use the first added patho
            }
            this._data.fiche.pathologys.push(pathId);
            S.db.fiches.put(this._data.fiche);

            //Update ui if needed by interface
            if(typeof S.platform.events.afterPageLoad === "function"){
                S.platform.events.afterPageLoad();
            }

        }
       },
      addCheckIn: function () {
         //TODO only allow the team responsible the checkin
         var ask= !S.config.local["ask-for"]["checkin-validation"] || confirm(S.lang["ask-confirm"]+" ?");
         if(ask){
             console.log(this._data.fiche);
             this._data.fiche.events.push({
               type : "action",
               action : "checkin",
               message : S.user._current.name+" "+S.lang.log["add-checkin"]+".",
               timestamp : Date.now(),
               user :  S.user._current.name
             })
             S.db.fiches.put(this._data.fiche);
         }
       },
      reopen: function () {
         var ask= !S.config.local["ask-for"]["reopen-validation"] || confirm(S.lang["ask-confirm"]+" ?");
         if(ask){
             console.log(this._data.fiche);
             this._data.fiche.events.push({
               type : "action",
               action : "reopen",
               message : S.user._current.name+" "+S.lang.log["reopen-fiche"]+".",
               timestamp : Date.now(),
               user :  S.user._current.name
             })
             this._data.fiche.closed = false;
             this._data.fiche.close_context = {};
             S.db.fiches.put(this._data.fiche);
         }
       },
      undelete: function () {
        if(S.user._current.isAdmin()){
          //We are admin
          var ask= !S.config.local["ask-for"]["delete-validation"] || confirm("Etes-vous sûr d'annuler la suppression de la fiche ?");
          if(ask){
            this._data.fiche.deleted = false;
            this._data.fiche.events.push({
              type : "action",
              action : "undelete",
              message : S.user._current.name+" "+S.lang.log["cancel-del"]+".",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            S.db.fiches.put(this._data.fiche);
          }
        }else{
          //Else we do nothing
        }
      },
      delete: function () {
        if(S.user._current.isAdmin()){
          //We are admin
          var ask= !S.config.local["ask-for"]["delete-validation"] || confirm("Etes-vous sûr de supprimer la fiche ?");
          if(ask){
            this._data.fiche.deleted = true;
            this._data.fiche.events.push({
              type : "action",
              action : "delete",
              message : S.user._current.name+" "+S.lang.log["del-fiche"]+".",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            S.db.fiches.put(this._data.fiche);
          }
        }else{
          //Else we do nothing
        }
      },
      closeCloseModal: function () {
           S.tool.getDialog("#close-fiche-dialog").close();
      },
      submitClose: function () {
        S.tool.getDialog("#close-fiche-dialog").close();
        this._data.fiche.closed = true;
        var close_context = {};
        $.each($("#close-fiche-dialog form").serializeArray(), function(id,value){
          close_context[value.name] = value.value;
        });
        this._data.fiche.close_context = close_context;
        this._data.fiche.events.push({
          type : "action",
          action : "close",
          message : S.user._current.name+" "+S.lang.log["close-fiche"]+".",
          close_context : this._data.fiche.close_context,
          timestamp : Date.now(),
          user :  S.user._current.name
        })

        S.db.fiches.put(this._data.fiche);
      },
      close: function () {
          S.tool.getDialog("#close-fiche-dialog").showModal();
      },
      take: function () {
         var ask= !S.config.local["ask-for"]["take-validation"] || confirm(S.lang["ask-confirm"]+" ?");
         if(ask){
             console.log(this._data.fiche);
             this._data.fiche.events.push({
               type : "action",
               action : "take",
               message : S.user._current.name+" "+S.lang.log["take-fiche-from"]+" "+this._data.fiche.owner_id,
               timestamp : Date.now(),
               user :  S.user._current.name
             })
             this._data.fiche.owner_id = S.user._current.name
             S.db.fiches.put(this._data.fiche);
         }
      },
      setGiveForm : function(event){
        this._data.fiche.owner_id = $.trim($(event.srcElement).text());
      },
      giveTicket : function(){
      var fiche = this._data.fiche;
       var ask= !S.config.local["ask-for"]["give-validation"] || confirm("Etes-vous sûr de tranferer à "+fiche.owner_id+" ?");
         S.db.fiches.getByID(this.$route.params.fiche_id).then(function (old) {
           if(ask){ //We have consent or it's auto-validate by config
               console.log(fiche);
               fiche.events.push({
                 type : "action",
                 action : "take",
                 message : S.user._current.name+" "+S.lang.log["give-fiche-to"]+" "+ fiche.owner_id +" ("+S.lang.log["old-prop"]+" : "+old.owner_id+")",
                 timestamp : Date.now(),
                 user :  S.user._current.name
               })
               S.db.fiches.put(fiche);
            }else{
              $.extend(true,fiche, old) //Reset to what is in localDB
            }
            S.tool.getDialog("#give-ticket-dialog").close();
       });
      },
      cancelGiveForm : function(){
        var data = this._data
        S.db.fiches.getByID(this.$route.params.fiche_id).then(function (doc) {
          $.extend(true,data.fiche, doc) //Reset to what is in localDB
        });
        S.tool.getDialog("#give-ticket-dialog").close()
      },
      showGiveModal: function () {
        S.tool.getDialog("#give-ticket-dialog").showModal();
      }
    }
})
<|endoftext|>


<commit_before>"use strict";
define({
    options: {
        title: "",
        displayQuickAddButton : false,
        displaySearchbox: false,
        onHeaderClick : function(){S.tool.getDialog("#update-fiche-information-dialog").showModal();}
    },
    route: {
        data: function () {
            var ret;
            var deferred = new $.Deferred();
            var ficheId = this.$route.params.fiche_id;
            S.db.config.getUsers().then(function(userlist){
              console.log(userlist);
            //S.db.config.getUsers().then(function(userlist){              console.log(userlist);
              S.db.fiches.getByID(ficheId).then(function (doc) {
                console.log(doc);
                S.vue.router.app.$children[0].$data.options.title = doc.patient.firstname +" "+ doc.patient.lastname;
                ret = {
                  fiche:doc,
                  user:S.user._current,
                  history: [],
                  config : S.config.fiche,
                  lang : S.lang,
                  users : userlist
                };
                console.log(ret);
                deferred.resolve(ret);
                if(!ret.fiche.origin || ret.fiche.origin === ""){ // L'ogine n'est pas saisie on force la saisie
                    S.tool.getDialog("#add-origin-dialog").showModal();
                }
                /*
                console.log("Fetching change for fiche in background ... ",ret.fiche, this)
                S.db.fiches.getChanges(ret.fiche._id).then(function (changes) {
                  console.log(changes)
                  ret.history.push("Done ("+changes.results.length+"/"+changes.last_seq+")");
                  console.log(ret);
                }).catch(function (err) {
                  console.log(err);
                });
                */
              });

            })
            return deferred.promise();
        }
    },
    computed: {
      _patient_age: function () {
        return moment(this.fiche.patient.birthdate).fromNow(true)
      },
      _last_update: function () { //Get the timestamp of the last update and format it to be shown
        return (this.fiche.events.length>0)? moment(this.fiche.events[this.fiche.events.length-1].timestamp).fromNow():"" ;//TODO better order and get the most new timestamp other than the last el in array
      }
    },
    methods: {
      showUpdateInformation: function () {
          S.tool.getDialog("#update-fiche-information-dialog").showModal();
      },
      closeUpdateInformation: function () {
          var data = this._data
          S.tool.getDialog("#update-fiche-information-dialog").close();
          S.db.fiches.getByID(this.$route.params.fiche_id).then(function (doc) {
            $.extend(true,data.fiche, doc) //Reset to what is in localDB
          });
      },
      closeDiffModal: function () {
          S.tool.getDialog("#show-diff-dialog").close();
      },
      showDiffInformation: function(event){
        var el = $(event.srcElement);
        if(el.not("button")){
          el = el.parent();
        }
        //console.log(el,el.attr("data-event"), el.data('event'));
        console.log(el,el.attr("data-diff"), el.data('diff'));
        $("#show-diff-dialog>.mdl-dialog__content").html(objectDiff.convertToXMLString(el.data('diff')))
        S.tool.getDialog("#show-diff-dialog").showModal();
      },
      changeInformation: function () {
        var ask= (!S.config.local["ask-for"]["changeInformation-validation"] || confirm(S.lang["ask-confirm"]+" ?")); //TODO replace with navigator.notification.confirm
        if(ask){
          var f = this._data.fiche;
          S.db.fiches.getByID(this.$route.params.fiche_id).then(function (doc) {
            console.log(f,this);
            f.events.push({
              type : "action",
              action : "changeInformation",
              message : S.user._current.name+" "+S.lang.log["has-updated-information"]+" !",
              diff : objectDiff.diff(doc.patient, f.patient),
              timestamp : Date.now(),
              user :  S.user._current.name
            });
            //Update this._data.fiche with additionnal data from data or update them
            //$.extend(true, this._data.fiche, data); //TODO be more strict on wath can be edited
            //DATA is already updated by vue in live
            S.vue.router.app.$children[0].$data.options.title = f.patient.firstname +" "+ f.patient.lastname;
            S.tool.getDialog("#update-fiche-information-dialog").close();

            S.db.fiches.put(f);//Saving
          });
        }
      },
      changePrimaryAffection: function (event) {
        var newPrimaryID = $(event.srcElement).val();
        var oldPrimary = S.lang.fiche.pathologys[this._data.fiche.primaryAffection] || this._data.fiche.primaryAffection;
        var newPrimary = S.lang.fiche.pathologys[newPrimaryID] || newPrimaryID;
        var ask= (!S.config.local["ask-for"]["changePrimaryAffection-validation"] || confirm(S.lang["ask-confirm-choice"]+""+newPrimary+" ?"));  //TODO replace with navigator.notification.confirm
        if(ask){
            console.log(this._data.fiche);
            this._data.fiche.events.push({
              type : "action",
              action : "changePrimaryAffection",
              message : S.user._current.name+" "+S.lang.log["change-primary"]+" "+oldPrimary+" "+S.lang["to"]+" "+newPrimary+"",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            this._data.fiche.primaryAffection = newPrimaryID;
            S.db.fiches.put(this._data.fiche);
        }
      },
      addOrigin: function (event) {
        var origin = $(event.srcElement).text();
        var originId = $.trim($(event.srcElement).attr("data-id"));
        S.tool.getDialog("#add-origin-dialog").close();
        var ask= (!S.config.local["ask-for"]["addOrigin-validation"] || confirm(S.lang["ask-confirm-choice"]+" : "+origin+" ?"));
        if(ask){
            console.log(this._data.fiche);
            this._data.fiche.events.push({
              type : "action",
              action : "addOrigin",
              message : S.user._current.name+" "+S.lang.log['set-origin']+" : "+origin+"",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            this._data.fiche.origin = originId;
            S.db.fiches.put(this._data.fiche);
        }
      },
      showAddPathologyModal: function () {
          S.tool.getDialog("#add-path-dialog").showModal();
      },
      closeAddPathologyModal: function () {
          S.tool.getDialog("#add-path-dialog").close();
      },
      addPathology: function (event) {
        //TODO check if already exist and display it
        var el = $(event.srcElement);
        if(! el.is(".mdl-list__item-primary-content")){ //Find the content if it is the li that trigger
          el = el.find(".mdl-list__item-primary-content");
        }
        var path = $.trim(el.text());
        var pathId = $.trim(el.attr("data-id"));
        S.tool.getDialog("#add-path-dialog").close();
        var ask= !S.config.local["ask-for"]["addPathology-validation"] || confirm("Etes-vous sûr d'ajouter "+path+" ?");
        if(ask){
            console.log(this._data.fiche);
            this._data.fiche.events.push({
              type : "action",
              action : "addPathology",
              message : S.user._current.name+" "+S.lang.log["add-path"]+" : "+path+"",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            if(this._data.fiche.pathologys.length === 0){
               this._data.fiche.primaryAffection = pathId; // By default we use the first added patho
            }
            this._data.fiche.pathologys.push(pathId);
            S.db.fiches.put(this._data.fiche);

            //Update ui if needed by interface
            if(typeof S.platform.events.afterPageLoad === "function"){
                S.platform.events.afterPageLoad();
            }

        }
       },
      addCheckIn: function () {
         //TODO only allow the team responsible the checkin
         var ask= !S.config.local["ask-for"]["checkin-validation"] || confirm(S.lang["ask-confirm"]+" ?");
         if(ask){
             console.log(this._data.fiche);
             this._data.fiche.events.push({
               type : "action",
               action : "checkin",
               message : S.user._current.name+" "+S.lang.log["add-checkin"]+".",
               timestamp : Date.now(),
               user :  S.user._current.name
             })
             S.db.fiches.put(this._data.fiche);
         }
       },
      reopen: function () {
         var ask= !S.config.local["ask-for"]["reopen-validation"] || confirm(S.lang["ask-confirm"]+" ?");
         if(ask){
             console.log(this._data.fiche);
             this._data.fiche.events.push({
               type : "action",
               action : "reopen",
               message : S.user._current.name+" "+S.lang.log["reopen-fiche"]+".",
               timestamp : Date.now(),
               user :  S.user._current.name
             })
             this._data.fiche.closed = false;
             this._data.fiche.close_context = {};
             S.db.fiches.put(this._data.fiche);
         }
       },
      undelete: function () {
        if(S.user._current.isAdmin()){
          //We are admin
          var ask= !S.config.local["ask-for"]["delete-validation"] || confirm("Etes-vous sûr d'annuler la suppression de la fiche ?");
          if(ask){
            this._data.fiche.deleted = false;
            this._data.fiche.events.push({
              type : "action",
              action : "undelete",
              message : S.user._current.name+" "+S.lang.log["cancel-del"]+".",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            S.db.fiches.put(this._data.fiche);
          }
        }else{
          //Else we do nothing
        }
      },
      delete: function () {
        if(S.user._current.isAdmin()){
          //We are admin
          var ask= !S.config.local["ask-for"]["delete-validation"] || confirm("Etes-vous sûr de supprimer la fiche ?");
          if(ask){
            this._data.fiche.deleted = true;
            this._data.fiche.events.push({
              type : "action",
              action : "delete",
              message : S.user._current.name+" "+S.lang.log["del-fiche"]+".",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            S.db.fiches.put(this._data.fiche);
          }
        }else{
          //Else we do nothing
        }
      },
      closeCloseModal: function () {
           S.tool.getDialog("#close-fiche-dialog").close();
      },
      submitClose: function () {
        S.tool.getDialog("#close-fiche-dialog").close();
        this._data.fiche.closed = true;
        var close_context = {};
        $.each($("#close-fiche-dialog form").serializeArray(), function(id,value){
          close_context[value.name] = value.value;
        });
        this._data.fiche.close_context = close_context;
        this._data.fiche.events.push({
          type : "action",
          action : "close",
          message : S.user._current.name+" "+S.lang.log["close-fiche"]+".",
          close_context : this._data.fiche.close_context,
          timestamp : Date.now(),
          user :  S.user._current.name
        })

        S.db.fiches.put(this._data.fiche);
      },
      close: function () {
          if(this._data.fiche.pathologys.length == 0 || typeof this._data.fiche.primaryAffection === "undefined" || this._data.fiche.primaryAffection === ""){
            return navigator.notification.alert(S.lang.alert["no-primaryAffection"]+"!")
          }
          S.tool.getDialog("#close-fiche-dialog").showModal();
      },
      take: function () {
         var ask= !S.config.local["ask-for"]["take-validation"] || confirm(S.lang["ask-confirm"]+" ?");
         if(ask){
             console.log(this._data.fiche);
             this._data.fiche.events.push({
               type : "action",
               action : "take",
               message : S.user._current.name+" "+S.lang.log["take-fiche-from"]+" "+this._data.fiche.owner_id,
               timestamp : Date.now(),
               user :  S.user._current.name
             })
             this._data.fiche.owner_id = S.user._current.name
             S.db.fiches.put(this._data.fiche);
         }
      },
      setGiveForm : function(event){
        this._data.fiche.owner_id = $.trim($(event.srcElement).text());
      },
      giveTicket : function(){
      var fiche = this._data.fiche;
       var ask= !S.config.local["ask-for"]["give-validation"] || confirm("Etes-vous sûr de tranferer à "+fiche.owner_id+" ?");
         S.db.fiches.getByID(this.$route.params.fiche_id).then(function (old) {
           if(ask){ //We have consent or it's auto-validate by config
               console.log(fiche);
               fiche.events.push({
                 type : "action",
                 action : "take",
                 message : S.user._current.name+" "+S.lang.log["give-fiche-to"]+" "+ fiche.owner_id +" ("+S.lang.log["old-prop"]+" : "+old.owner_id+")",
                 timestamp : Date.now(),
                 user :  S.user._current.name
               })
               S.db.fiches.put(fiche);
            }else{
              $.extend(true,fiche, old) //Reset to what is in localDB
            }
            S.tool.getDialog("#give-ticket-dialog").close();
       });
      },
      cancelGiveForm : function(){
        var data = this._data
        S.db.fiches.getByID(this.$route.params.fiche_id).then(function (doc) {
          $.extend(true,data.fiche, doc) //Reset to what is in localDB
        });
        S.tool.getDialog("#give-ticket-dialog").close()
      },
      showGiveModal: function () {
        S.tool.getDialog("#give-ticket-dialog").showModal();
      }
    }
})
<commit_msg>Update fiche.js<commit_after>"use strict";
define({
    options: {
        title: "",
        displayQuickAddButton : false,
        displaySearchbox: false,
        onHeaderClick : function(){S.tool.getDialog("#update-fiche-information-dialog").showModal();}
    },
    route: {
        data: function () {
            var ret;
            var deferred = new $.Deferred();
            var ficheId = this.$route.params.fiche_id;
            S.db.config.getUsers().then(function(userlist){
              console.log(userlist);
            //S.db.config.getUsers().then(function(userlist){              console.log(userlist);
              S.db.fiches.getByID(ficheId).then(function (doc) {
                console.log(doc);
                S.vue.router.app.$children[0].$data.options.title = doc.patient.firstname +" "+ doc.patient.lastname;
                ret = {
                  fiche:doc,
                  user:S.user._current,
                  history: [],
                  config : S.config.fiche,
                  lang : S.lang,
                  users : userlist
                };
                console.log(ret);
                deferred.resolve(ret);
                if(!ret.fiche.origin || ret.fiche.origin === ""){ // L'ogine n'est pas saisie on force la saisie
                    S.tool.getDialog("#add-origin-dialog").showModal();
                }
                /*
                console.log("Fetching change for fiche in background ... ",ret.fiche, this)
                S.db.fiches.getChanges(ret.fiche._id).then(function (changes) {
                  console.log(changes)
                  ret.history.push("Done ("+changes.results.length+"/"+changes.last_seq+")");
                  console.log(ret);
                }).catch(function (err) {
                  console.log(err);
                });
                */
              });

            })
            return deferred.promise();
        }
    },
    computed: {
      _patient_age: function () {
        return moment(this.fiche.patient.birthdate).fromNow(true)
      },
      _last_update: function () { //Get the timestamp of the last update and format it to be shown
        return (this.fiche.events.length>0)? moment(this.fiche.events[this.fiche.events.length-1].timestamp).fromNow():"" ;//TODO better order and get the most new timestamp other than the last el in array
      }
    },
    methods: {
      showUpdateInformation: function () {
          S.tool.getDialog("#update-fiche-information-dialog").showModal();
      },
      closeUpdateInformation: function () {
          var data = this._data
          S.tool.getDialog("#update-fiche-information-dialog").close();
          S.db.fiches.getByID(this.$route.params.fiche_id).then(function (doc) {
            $.extend(true,data.fiche, doc) //Reset to what is in localDB
          });
      },
      closeDiffModal: function () {
          S.tool.getDialog("#show-diff-dialog").close();
      },
      showDiffInformation: function(event){
        var el = $(event.srcElement);
        if(el.not("button")){
          el = el.parent();
        }
        //console.log(el,el.attr("data-event"), el.data('event'));
        console.log(el,el.attr("data-diff"), el.data('diff'));
        $("#show-diff-dialog>.mdl-dialog__content").html(objectDiff.convertToXMLString(el.data('diff')))
        S.tool.getDialog("#show-diff-dialog").showModal();
      },
      changeInformation: function () {
        var ask= (!S.config.local["ask-for"]["changeInformation-validation"] || confirm(S.lang["ask-confirm"]+" ?")); //TODO replace with navigator.notification.confirm
        if(ask){
          var f = this._data.fiche;
          S.db.fiches.getByID(this.$route.params.fiche_id).then(function (doc) {
            console.log(f,this);
            f.events.push({
              type : "action",
              action : "changeInformation",
              message : S.user._current.name+" "+S.lang.log["has-updated-information"]+" !",
              diff : objectDiff.diff(doc.patient, f.patient),
              timestamp : Date.now(),
              user :  S.user._current.name
            });
            //Update this._data.fiche with additionnal data from data or update them
            //$.extend(true, this._data.fiche, data); //TODO be more strict on wath can be edited
            //DATA is already updated by vue in live
            S.vue.router.app.$children[0].$data.options.title = f.patient.firstname +" "+ f.patient.lastname;
            S.tool.getDialog("#update-fiche-information-dialog").close();

            S.db.fiches.put(f);//Saving
          });
        }
      },
      changePrimaryAffection: function (event) {
        var newPrimaryID = $(event.srcElement).val();
        var oldPrimary = S.lang.fiche.pathologys[this._data.fiche.primaryAffection] || this._data.fiche.primaryAffection;
        var newPrimary = S.lang.fiche.pathologys[newPrimaryID] || newPrimaryID;
        var ask= (!S.config.local["ask-for"]["changePrimaryAffection-validation"] || confirm(S.lang["ask-confirm-choice"]+""+newPrimary+" ?"));  //TODO replace with navigator.notification.confirm
        if(ask){
            console.log(this._data.fiche);
            this._data.fiche.events.push({
              type : "action",
              action : "changePrimaryAffection",
              message : S.user._current.name+" "+S.lang.log["change-primary"]+" "+oldPrimary+" "+S.lang["to"]+" "+newPrimary+"",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            this._data.fiche.primaryAffection = newPrimaryID;
            S.db.fiches.put(this._data.fiche);
        }
      },
      addOrigin: function (event) {
        var origin = $(event.srcElement).text();
        var originId = $.trim($(event.srcElement).attr("data-id"));
        S.tool.getDialog("#add-origin-dialog").close();
        var ask= (!S.config.local["ask-for"]["addOrigin-validation"] || confirm(S.lang["ask-confirm-choice"]+" : "+origin+" ?"));
        if(ask){
            console.log(this._data.fiche);
            this._data.fiche.events.push({
              type : "action",
              action : "addOrigin",
              message : S.user._current.name+" "+S.lang.log['set-origin']+" : "+origin+"",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            this._data.fiche.origin = originId;
            S.db.fiches.put(this._data.fiche);
        }
      },
      showAddPathologyModal: function () {
          S.tool.getDialog("#add-path-dialog").showModal();
      },
      closeAddPathologyModal: function () {
          S.tool.getDialog("#add-path-dialog").close();
      },
      addPathology: function (event) {
        //TODO check if already exist and display it
        var el = $(event.srcElement);
        if(! el.is(".mdl-list__item-primary-content")){ //Find the content if it is the li that trigger
          el = el.find(".mdl-list__item-primary-content");
        }
        var path = $.trim(el.text());
        var pathId = $.trim(el.attr("data-id"));
        S.tool.getDialog("#add-path-dialog").close();
        var ask= !S.config.local["ask-for"]["addPathology-validation"] || confirm("Etes-vous sûr d'ajouter "+path+" ?");
        if(ask){
            console.log(this._data.fiche);
            this._data.fiche.events.push({
              type : "action",
              action : "addPathology",
              message : S.user._current.name+" "+S.lang.log["add-path"]+" : "+path+"",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            if(this._data.fiche.pathologys.length === 0){
               this._data.fiche.primaryAffection = pathId; // By default we use the first added patho
            }
            this._data.fiche.pathologys.push(pathId);
            S.db.fiches.put(this._data.fiche);

            //Update ui if needed by interface
            if(typeof S.platform.events.afterPageLoad === "function"){
                S.platform.events.afterPageLoad();
            }

        }
       },
      addCheckIn: function () {
         //TODO only allow the team responsible the checkin
         var ask= !S.config.local["ask-for"]["checkin-validation"] || confirm(S.lang["ask-confirm"]+" ?");
         if(ask){
             console.log(this._data.fiche);
             this._data.fiche.events.push({
               type : "action",
               action : "checkin",
               message : S.user._current.name+" "+S.lang.log["add-checkin"]+".",
               timestamp : Date.now(),
               user :  S.user._current.name
             })
             S.db.fiches.put(this._data.fiche);
         }
       },
      reopen: function () {
         var ask= !S.config.local["ask-for"]["reopen-validation"] || confirm(S.lang["ask-confirm"]+" ?");
         if(ask){
             console.log(this._data.fiche);
             this._data.fiche.events.push({
               type : "action",
               action : "reopen",
               message : S.user._current.name+" "+S.lang.log["reopen-fiche"]+".",
               timestamp : Date.now(),
               user :  S.user._current.name
             })
             this._data.fiche.closed = false;
             this._data.fiche.close_context = {};
             S.db.fiches.put(this._data.fiche);
         }
       },
      undelete: function () {
        if(S.user._current.isAdmin()){
          //We are admin
          var ask= !S.config.local["ask-for"]["delete-validation"] || confirm("Etes-vous sûr d'annuler la suppression de la fiche ?");
          if(ask){
            this._data.fiche.deleted = false;
            this._data.fiche.events.push({
              type : "action",
              action : "undelete",
              message : S.user._current.name+" "+S.lang.log["cancel-del"]+".",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            S.db.fiches.put(this._data.fiche);
          }
        }else{
          //Else we do nothing
        }
      },
      showDeleteModal: function () {
        if(S.user._current.isAdmin()){
          S.tool.getDialog("#delete-fiche-dialog").showModal();
        }else{
          //Else we do nothing
        }
      },
      closeDeleteModal: function () {
          S.tool.getDialog("#delete-fiche-dialog").close();
      },
      submitDelete: function () {
        if(S.user._current.isAdmin()){
          //We are admin
          var ask= !S.config.local["ask-for"]["delete-validation"] || confirm("Etes-vous sûr de supprimer la fiche ?");
          if(ask){
            this._data.fiche.deleted = true;
            this._data.fiche.events.push({
              type : "action",
              action : "delete",
              message : S.user._current.name+" "+S.lang.log["del-fiche"]+" : "+$("#delete-fiche-dialog #deleteReason").val(),
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            S.db.fiches.put(this._data.fiche);
          }
        }else{
          //Else we do nothing
        }
      },
	  /*
      delete: function () {
        if(S.user._current.isAdmin()){
          //We are admin
          var ask= !S.config.local["ask-for"]["delete-validation"] || confirm("Etes-vous sûr de supprimer la fiche ?");
          if(ask){
            this._data.fiche.deleted = true;
            this._data.fiche.events.push({
              type : "action",
              action : "delete",
              message : S.user._current.name+" "+S.lang.log["del-fiche"]+".",
              timestamp : Date.now(),
              user :  S.user._current.name
            })
            S.db.fiches.put(this._data.fiche);
          }
        }else{
          //Else we do nothing
        }
      },
	  */
      closeCloseModal: function () {
           S.tool.getDialog("#close-fiche-dialog").close();
      },
      submitClose: function () {
        S.tool.getDialog("#close-fiche-dialog").close();
        this._data.fiche.closed = true;
        var close_context = {};
        $.each($("#close-fiche-dialog form").serializeArray(), function(id,value){
          close_context[value.name] = value.value;
        });
        this._data.fiche.close_context = close_context;
        this._data.fiche.events.push({
          type : "action",
          action : "close",
          message : S.user._current.name+" "+S.lang.log["close-fiche"]+".",
          close_context : this._data.fiche.close_context,
          timestamp : Date.now(),
          user :  S.user._current.name
        })

        S.db.fiches.put(this._data.fiche);
      },
      close: function () {
          if(this._data.fiche.pathologys.length == 0 || typeof this._data.fiche.primaryAffection === "undefined" || this._data.fiche.primaryAffection === ""){
            return navigator.notification.alert(S.lang.alert["no-primaryAffection"]+"!")
          }
          S.tool.getDialog("#close-fiche-dialog").showModal();
      },
      take: function () {
         var ask= !S.config.local["ask-for"]["take-validation"] || confirm(S.lang["ask-confirm"]+" ?");
         if(ask){
             console.log(this._data.fiche);
             this._data.fiche.events.push({
               type : "action",
               action : "take",
               message : S.user._current.name+" "+S.lang.log["take-fiche-from"]+" "+this._data.fiche.owner_id,
               timestamp : Date.now(),
               user :  S.user._current.name
             })
             this._data.fiche.owner_id = S.user._current.name
             S.db.fiches.put(this._data.fiche);
         }
      },
      setGiveForm : function(event){
        this._data.fiche.owner_id = $.trim($(event.srcElement).text());
      },
      giveTicket : function(){
      var fiche = this._data.fiche;
       var ask= !S.config.local["ask-for"]["give-validation"] || confirm("Etes-vous sûr de tranferer à "+fiche.owner_id+" ?");
         S.db.fiches.getByID(this.$route.params.fiche_id).then(function (old) {
           if(ask){ //We have consent or it's auto-validate by config
               console.log(fiche);
               fiche.events.push({
                 type : "action",
                 action : "take",
                 message : S.user._current.name+" "+S.lang.log["give-fiche-to"]+" "+ fiche.owner_id +" ("+S.lang.log["old-prop"]+" : "+old.owner_id+")",
                 timestamp : Date.now(),
                 user :  S.user._current.name
               })
               S.db.fiches.put(fiche);
            }else{
              $.extend(true,fiche, old) //Reset to what is in localDB
            }
            S.tool.getDialog("#give-ticket-dialog").close();
       });
      },
      cancelGiveForm : function(){
        var data = this._data
        S.db.fiches.getByID(this.$route.params.fiche_id).then(function (doc) {
          $.extend(true,data.fiche, doc) //Reset to what is in localDB
        });
        S.tool.getDialog("#give-ticket-dialog").close()
      },
      showGiveModal: function () {
        S.tool.getDialog("#give-ticket-dialog").showModal();
      }
    }
})
<|endoftext|>


<commit_before>
describe('monitoring', function() {
    'use strict';

    beforeEach(module('superdesk.monitoring'));

    it('can preview an item', inject(function($controller, $rootScope) {
        var scope = $rootScope.$new(),
            ctrl = $controller('Monitoring', {$scope: scope}),
            item = {};

        expect(ctrl.state['with-preview']).toBeFalsy();

        ctrl.preview(item);

        expect(ctrl.previewItem).toBe(item);
        expect(ctrl.state['with-preview']).toBeTruthy();

        ctrl.closePreview();
        expect(ctrl.previewItem).toBe(null);
        expect(ctrl.state['with-preview']).toBeFalsy();
    }));

    it('can edit item', inject(function($controller, $rootScope) {
        var scope = $rootScope.$new(),
            ctrl = $controller('Monitoring', {$scope: scope}),
            item = {};

        expect(ctrl.state['with-authoring']).toBeFalsy();

        ctrl.edit(item);
        expect(ctrl.editItem).toBe(item);
        expect(ctrl.state['with-authoring']).toBeTruthy();
    }));

    describe('cards service', function() {
        it('can get criteria for stage', inject(function(cards) {
            var card = {_id: '123'};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.filter.and).toContain({
                term: {'task.stage': card._id}
            });

            criteria = cards.criteria(card, 'foo');
            expect(criteria.source.query.filtered.filter.and).toContain({
                query: {query_string: {query: 'foo', lenient: false}}
            });
        }));

        it('can get criteria for personal', inject(function(cards, session) {
            var card = {type: 'personal'};
            session.identity = {_id: 'foo'};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.filter.and).toContain({
                bool: {
                    must: {term: {original_creator: session.identity._id}},
                    must_not: {exists: {field: 'task.desk'}}
                }
            });
        }));

        it('can get criteria for saved search', inject(function(cards) {
            var card = {type: 'search', search: {filter: {query: {q: 'foo'}}}};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.query.query_string.query).toBe('foo');
        }));

        it('can get criteria for spike desk', inject(function(cards) {
            var card = {type: 'spike'};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.filter.and).toContain({
                term: {'task.desk': card._id}
            });
            expect(criteria.source.query.filtered.filter.and).toContain({
                term: {'state': 'spiked'}
            });
        }));

        it('can get criteria for highlight', inject(function(cards) {
            var card = {type: 'highlights'};
            var queryParam = {highlight: '123'};
            var criteria = cards.criteria(card, null, queryParam);
            expect(criteria.source.query.filtered.filter.and).toContain({
                and: [{term: {'highlights': queryParam.highlight}}]
            });
        }));

        it('can get criteria for stage with search', inject(function(cards) {
            var card = {_id: '123', query: 'test'};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.query.query_string.query).toBe('test');
        }));

        it('can get criteria for personal with search', inject(function(cards, session) {
            var card = {type: 'personal', query: 'test'};
            session.identity = {_id: 'foo'};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.query.query_string.query).toBe('test');
        }));

        it('can get criteria for spike with search', inject(function(cards) {
            var card = {_id: '123', type: 'spike', query: 'test'};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.query.query_string.query).toBe('test');
        }));

        it('can get criteria for highlight with search', inject(function(cards) {
            var card = {type: 'highlights', query: 'test'};
            var queryParam = {highlight: '123'};
            var criteria = cards.criteria(card, null, queryParam);
            expect(criteria.source.query.filtered.query.query_string.query).toBe('test');
        }));

        it('can get criteria for file type filter', inject(function(cards) {
            var card = {_id: '123', fileType: JSON.stringify(['text'])};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.filter.and).toContain({
                terms: {type: ['text']}
            });
        }));

        it('can get criteria for saved search with search', inject(function(cards) {
            var card = {_id: '123', type: 'search', query: 'test',
                        search: {filter: {query: {q: 'foo', type: '[\"picture\"]'}}}
            };
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.query.query_string.query).toBe('(test) foo');
            expect(criteria.source.post_filter.and).toContain({terms: {type: ['picture']}});
        }));

        it('can get criteria for file type filter with search', inject(function(cards) {
            var card = {_id: '123', fileType: JSON.stringify(['text']), query: 'test'};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.filter.and).toContain({
                terms: {type: ['text']}
            });
        }));

        it('can get criteria for multiple file type filter', inject(function(cards) {
            var card = {_id: '123', fileType: JSON.stringify(['text', 'picture'])};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.filter.and).toContain({
                terms: {type: ['text', 'picture']}
            });
        }));
    });

    describe('monitoring group directive', function() {

        beforeEach(module('templates'));

        beforeEach(inject(function($templateCache) {
            // change template not to require aggregate config but rather render single group
            $templateCache.put('scripts/superdesk-monitoring/views/monitoring-view.html',
                '

');
        }));

        it('can update items on content:update event',
        inject(function($rootScope, $compile, $q, api, $timeout) {
            var scope = $rootScope.$new();
            $compile('

')(scope);
            scope.$digest();

            spyOn(api, 'query').and.returnValue($q.when({_items: [], _meta: {total: 0}}));
            scope.$broadcast('content:update', {stages: {'bar': 1}});
            scope.$digest();
            $timeout.flush(500);
            expect(api.query).not.toHaveBeenCalled();

            scope.$broadcast('content:update', {stages: {'foo': 1}});
            scope.$digest();
            $timeout.flush(500);
            expect(api.query).toHaveBeenCalled();
        }));

        it('can generate unique track by id',
        inject(function($rootScope, $compile, $templateCache) {
            var scope = $rootScope.$new();
            var $elm = $compile('

')(scope);
            scope.$digest();
            var sdGroupElement = $elm.find('#group');
            var iScope = sdGroupElement.isolateScope();
            var item = {state: 'ingested', _id: '123', '_current_version': 'dddd'};
            expect(iScope.uuid(item)).toBe('123');
            item = {state: 'foo', _id: 'test', _current_version: '123'};
            expect(iScope.uuid(item)).toBe('test:123');
        }));
    });
});
<commit_msg>Fix (spkied list): Test for edit added<commit_after>
describe('monitoring', function() {
    'use strict';

    beforeEach(module('superdesk.monitoring'));

    it('can preview an item', inject(function($controller, $rootScope) {
        var scope = $rootScope.$new(),
            ctrl = $controller('Monitoring', {$scope: scope}),
            item = {};

        expect(ctrl.state['with-preview']).toBeFalsy();

        ctrl.preview(item);

        expect(ctrl.previewItem).toBe(item);
        expect(ctrl.state['with-preview']).toBeTruthy();

        ctrl.closePreview();
        expect(ctrl.previewItem).toBe(null);
        expect(ctrl.state['with-preview']).toBeFalsy();
    }));

    it('can edit item', inject(function($controller, $rootScope) {
        var scope = $rootScope.$new(),
            ctrl = $controller('Monitoring', {$scope: scope}),
            item = {};

        expect(ctrl.state['with-authoring']).toBeFalsy();

        ctrl.edit(item);
        expect(ctrl.editItem).toBe(item);
        expect(ctrl.state['with-authoring']).toBeTruthy();
    }));

    describe('cards service', function() {
        it('can get criteria for stage', inject(function(cards) {
            var card = {_id: '123'};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.filter.and).toContain({
                term: {'task.stage': card._id}
            });

            criteria = cards.criteria(card, 'foo');
            expect(criteria.source.query.filtered.filter.and).toContain({
                query: {query_string: {query: 'foo', lenient: false}}
            });
        }));

        it('can get criteria for personal', inject(function(cards, session) {
            var card = {type: 'personal'};
            session.identity = {_id: 'foo'};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.filter.and).toContain({
                bool: {
                    must: {term: {original_creator: session.identity._id}},
                    must_not: {exists: {field: 'task.desk'}}
                }
            });
        }));

        it('can get criteria for saved search', inject(function(cards) {
            var card = {type: 'search', search: {filter: {query: {q: 'foo'}}}};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.query.query_string.query).toBe('foo');
        }));

        it('can get criteria for spike desk', inject(function(cards) {
            var card = {type: 'spike'};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.filter.and).toContain({
                term: {'task.desk': card._id}
            });
            expect(criteria.source.query.filtered.filter.and).toContain({
                term: {'state': 'spiked'}
            });
        }));

        it('can get criteria for highlight', inject(function(cards) {
            var card = {type: 'highlights'};
            var queryParam = {highlight: '123'};
            var criteria = cards.criteria(card, null, queryParam);
            expect(criteria.source.query.filtered.filter.and).toContain({
                and: [{term: {'highlights': queryParam.highlight}}]
            });
        }));

        it('can get criteria for stage with search', inject(function(cards) {
            var card = {_id: '123', query: 'test'};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.query.query_string.query).toBe('test');
        }));

        it('can get criteria for personal with search', inject(function(cards, session) {
            var card = {type: 'personal', query: 'test'};
            session.identity = {_id: 'foo'};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.query.query_string.query).toBe('test');
        }));

        it('can get criteria for spike with search', inject(function(cards) {
            var card = {_id: '123', type: 'spike', query: 'test'};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.query.query_string.query).toBe('test');
        }));

        it('can get criteria for highlight with search', inject(function(cards) {
            var card = {type: 'highlights', query: 'test'};
            var queryParam = {highlight: '123'};
            var criteria = cards.criteria(card, null, queryParam);
            expect(criteria.source.query.filtered.query.query_string.query).toBe('test');
        }));

        it('can get criteria for file type filter', inject(function(cards) {
            var card = {_id: '123', fileType: JSON.stringify(['text'])};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.filter.and).toContain({
                terms: {type: ['text']}
            });
        }));

        it('can get criteria for saved search with search', inject(function(cards) {
            var card = {_id: '123', type: 'search', query: 'test',
                        search: {filter: {query: {q: 'foo', type: '[\"picture\"]'}}}
            };
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.query.query_string.query).toBe('(test) foo');
            expect(criteria.source.post_filter.and).toContain({terms: {type: ['picture']}});
        }));

        it('can get criteria for file type filter with search', inject(function(cards) {
            var card = {_id: '123', fileType: JSON.stringify(['text']), query: 'test'};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.filter.and).toContain({
                terms: {type: ['text']}
            });
        }));

        it('can get criteria for multiple file type filter', inject(function(cards) {
            var card = {_id: '123', fileType: JSON.stringify(['text', 'picture'])};
            var criteria = cards.criteria(card);
            expect(criteria.source.query.filtered.filter.and).toContain({
                terms: {type: ['text', 'picture']}
            });
        }));
    });

    describe('monitoring group directive', function() {

        beforeEach(module('templates'));

        beforeEach(inject(function($templateCache) {
            // change template not to require aggregate config but rather render single group
            $templateCache.put('scripts/superdesk-monitoring/views/monitoring-view.html',
                '

');
        }));

        it('can update items on content:update event',
        inject(function($rootScope, $compile, $q, api, $timeout) {
            var scope = $rootScope.$new();
            $compile('

')(scope);
            scope.$digest();

            spyOn(api, 'query').and.returnValue($q.when({_items: [], _meta: {total: 0}}));
            scope.$broadcast('content:update', {stages: {'bar': 1}});
            scope.$digest();
            $timeout.flush(500);
            expect(api.query).not.toHaveBeenCalled();

            scope.$broadcast('content:update', {stages: {'foo': 1}});
            scope.$digest();
            $timeout.flush(500);
            expect(api.query).toHaveBeenCalled();
        }));

        it('can generate unique track by id', inject(function($rootScope, $compile) {
            var scope = $rootScope.$new(),
                $elm = $compile('

')(scope);
            scope.$digest();

            var sdGroupElement = $elm.find('#group'),
                iScope = sdGroupElement.isolateScope(),
                item = {state: 'ingested', _id: '123', '_current_version': 'dddd'};

            expect(iScope.uuid(item)).toBe('123');
            item = {state: 'foo', _id: 'test', _current_version: '123'};
            expect(iScope.uuid(item)).toBe('test:123');
        }));

        it('can edit non spiked item', inject(function($controller, $rootScope, $compile, authoringWorkspace) {
            var scope = $rootScope.$new(),
                $elm = $compile('

')(scope);
            scope.$digest();
            spyOn(authoringWorkspace, 'edit');

            var sdGroupElement = $elm.find('#group'),
                iScope = sdGroupElement.isolateScope(),
                item1 = {state: 'spiked'},
                item2 = {state: 'fetched'};

            iScope.edit(item1, true);
            expect(authoringWorkspace.edit).not.toHaveBeenCalled();

            iScope.edit(item2, true)
            expect(authoringWorkspace.edit).toHaveBeenCalled();
        }));
    });
});
<|endoftext|>


<commit_before>/**
 *  This file is part of PerSE. PerSE is a visual analytics app for
 *  event periodicity detection and analysis.
 *  Copyright (C) 2015  Brian Swedberg
 */

define([
    'jquery',
    'data/filter',
    'perwheel/timewheel',
    // no namespace
    '$.calendars',
    'bootstrap'
], function ($, filter, timewheel) {

    var perwheel = {};

    perwheel.PerWheel = function () {
        this.container = $('<div>').attr({'class': 'panel-body perse-panel-body'});
        this.calendarName = 'gregorian';
        this.listeners = [];
        this.timeWheel = undefined;
        this.filterButton = undefined;
        this.calendarButtons = {gregorian: undefined, islamic: undefined};
        this.filter = new filter.Filter({
            uniqueId: 'perse-perwheel',
            property: 'julianDate',
            filterOn: function () {return true; }
        });
    };

    perwheel.PerWheel.prototype.render = function (parent) {
        var title = $('<p>')
                .attr({'class': 'perse-header-title'})
                .text('Time-Wheel'),
            panelHeader = $('<div>')
                .attr({'class': 'panel-heading perse-panel-heading'})
                .append($('<div>').attr({'class': 'panel-title'}).append(title, this.createControls())),
            panel = $('<div>')
                .attr({'class': 'panel panel-default perse-perwheel'})
                .append(panelHeader, this.container);

        $(parent).append(panel);
        this.container.append(this.createTimeWheel());
        return this;
    };

    perwheel.PerWheel.prototype.createControls = function () {
        var cal = this.createCalendarButtonGroup(),
            filterBG = this.createFilterControlButtonGroup();
        return $('<div>')
            .attr({'class': 'btn-toolbar perse-header-toolbar', 'role': 'toolbar'})
            .append(cal, filterBG);
    };

    perwheel.PerWheel.prototype.createFilterControlButtonGroup = function () {
        var filterIcon = $('<span>')
                .attr({'class': 'glyphicon glyphicon-filter', 'aria-hidden': 'true'}),
            filterButton = $('<button>')
                .attr({'class': 'btn btn-default btn-xs', 'type': 'button', 'title': 'Reset Filter'})
                .append(filterIcon);

        filterButton.on('mouseup', $.proxy(function () {
            $(filterButton).blur();
            this.onReset();
            this.notifyListeners('onFilterChanged', {context: this, filter: this.getFilter()});
        }, this));

        this.filterButton = filterButton;

        return $('<div>').attr({'class': 'btn-group', 'role': 'group'}).append(filterButton);
    };

    perwheel.PerWheel.prototype.createCalendarButtonGroup = function () {
        var // menu
            calendarHeader = $('<li>').attr({'class': 'dropdown-header', 'role': 'presentation'}).text('Calendar'),
            gregorian = $('<a>').attr({'role': 'menuitem'}).text('Gregorian ').append($('<span>').attr({'class': 'glyphicon glyphicon-ok-sign', 'aria-hidden': 'true'})),
            islamic = $('<a>').attr({'role': 'menuitem'}).text('Islamic '),
            menu = $('<ul>')
            .attr({'class': 'dropdown-menu', 'role': 'menu'})
            .append([
                calendarHeader,
                $('<li>').attr({'role': 'presentation'}).append(gregorian),
                $('<li>').attr({'role': 'presentation'}).append(islamic)
            ]),
        // button
            calendarIcon = $('<span>').attr({'class': 'glyphicon glyphicon-calendar', 'aria-hidden': 'true'}),
            calendarButton = $('<button>')
                .attr({'class': 'btn btn-default btn-xs dropdown-toggle', 'type': 'button', 'data-toggle': 'dropdown', 'title': 'Change Calendar System'})
                .append(calendarIcon, ' ', $('<span>').attr({'class': 'caret'}));

        // add events here
        gregorian.on('mouseup', $.proxy(function () {
            this.setCalendar('gregorian');
        }, this));

        islamic.on('mouseup', $.proxy(function () {
            this.setCalendar('islamic');
        }, this));

        this.calendarButtons.gregorian = gregorian;
        this.calendarButtons.islamic = islamic;

        return $('<div>').attr({'class': 'btn-group', 'role': 'group'}).append(calendarButton, menu);
    };

    perwheel.PerWheel.prototype.createTimeWheel = function () {
        var timeWheelDiv = $('<div>');
        this.timeWheel = new timewheel.TimeWheel(this.calendarName)
            .render(timeWheelDiv.get(0))
            .registerListener({
                context: this,
                onTimeWheelSelectionChanged: function () {
                    this.validateFilterButton();
                    this.notifyListeners('onFilterChanged', {context: this, filter: this.getFilter()});
                }
            });
        return timeWheelDiv;
    };

    perwheel.PerWheel.prototype.validateFilterButton = function () {
        var twData = this.getData(),
            shouldEnable = Object.keys(twData.periodicity).every(function (key) {
                return twData.periodicity[key].data.every(function (cycle) {
                    return cycle.enabled;
                });
            });
        this.filterButton.toggleClass('disabled', shouldEnable);
    };

    perwheel.PerWheel.prototype.getData = function () {
        return {
            calendarName: this.calendarName,
            periodicity: this.timeWheel.getData()
        };
    };

    perwheel.PerWheel.prototype.getFilter = function () {
        var data = this.getData(),
            cal = $.calendars.instance(data.calendarName);
        this.filter.filterOn = function (julianDate) {
            var date = cal.fromJD(julianDate);
            if (!data.periodicity.dayOfWeek.data[date.dayOfWeek()].isEnabled) {
                return false;
            }
            if (!data.periodicity.dayOfMonth.data[date.day() - 1].isEnabled) {
                return false;
            }
            if (!data.periodicity.monthOfYear.data[date.month() - 1].isEnabled) {
                return false;
            }
            return true;
        };
        return this.filter;
    };

    perwheel.PerWheel.prototype.setContentAttribute = function (contentAttribute) {
        this.timeWheel.setContentAttribute(contentAttribute);
    };

    perwheel.PerWheel.prototype.setCalendar = function (calendarName) {
        if (this.calendarButtons.hasOwnProperty(calendarName)) {
            [this.calendarButtons.islamic, this.calendarButtons.gregorian].forEach(function (b) {
                b.find('.glyphicon').remove();
            });
            this.calendarButtons[calendarName].append(
                $('<span>').attr({'class': 'glyphicon glyphicon-ok-sign', 'aria-hidden': 'true'})
            );

            this.calendarName = calendarName;
            this.timeWheel.setCalendar(this.calendarName);
            this.filter.filterOn = function () {return true; };
            this.notifyListeners('onFilterChanged', {context: this, filter: this.filter});
        }
    };

    perwheel.PerWheel.prototype.onReset = function () {
        this.filterButton.toggleClass('disabled', true);
        this.filter.filterOn = function () {return true; };
        this.timeWheel.setAllEnabled();
    };

    perwheel.PerWheel.prototype.notifyListeners = function (callbackStr, event) {
        this.listeners.forEach(function (listenerObj) {
            listenerObj[callbackStr].call(listenerObj.context, event);
        }, this);
    };

    perwheel.PerWheel.prototype.registerListener = function (callbackObj) {
        this.listeners.push(callbackObj);
        return this;
    };

    perwheel.PerWheel.prototype.onSelectionChanged = function (data) {
        this.timeWheel.onSelectionChanged(data);
    };

    perwheel.PerWheel.prototype.onDataSetChanged = function (data, metadata) {
        this.metadata = metadata;
        this.timeWheel.onDataSetChanged(data, metadata);
        this.filterButton.toggleClass('disabled', true);
    };

    return perwheel;

});
<commit_msg>fixed filter disable/enable bug<commit_after>/**
 *  This file is part of PerSE. PerSE is a visual analytics app for
 *  event periodicity detection and analysis.
 *  Copyright (C) 2015  Brian Swedberg
 */

define([
    'jquery',
    'data/filter',
    'perwheel/timewheel',
    // no namespace
    '$.calendars',
    'bootstrap'
], function ($, filter, timewheel) {

    var perwheel = {};

    perwheel.PerWheel = function () {
        this.container = $('<div>').attr({'class': 'panel-body perse-panel-body'});
        this.calendarName = 'gregorian';
        this.listeners = [];
        this.timeWheel = undefined;
        this.filterButton = undefined;
        this.calendarButtons = {gregorian: undefined, islamic: undefined};
        this.filter = new filter.Filter({
            uniqueId: 'perse-perwheel',
            property: 'julianDate',
            filterOn: function () {return true; }
        });
    };

    perwheel.PerWheel.prototype.render = function (parent) {
        var title = $('<p>')
                .attr({'class': 'perse-header-title'})
                .text('Time-Wheel'),
            panelHeader = $('<div>')
                .attr({'class': 'panel-heading perse-panel-heading'})
                .append($('<div>').attr({'class': 'panel-title'}).append(title, this.createControls())),
            panel = $('<div>')
                .attr({'class': 'panel panel-default perse-perwheel'})
                .append(panelHeader, this.container);

        $(parent).append(panel);
        this.container.append(this.createTimeWheel());
        return this;
    };

    perwheel.PerWheel.prototype.createControls = function () {
        var cal = this.createCalendarButtonGroup(),
            filterBG = this.createFilterControlButtonGroup();
        return $('<div>')
            .attr({'class': 'btn-toolbar perse-header-toolbar', 'role': 'toolbar'})
            .append(cal, filterBG);
    };

    perwheel.PerWheel.prototype.createFilterControlButtonGroup = function () {
        var filterIcon = $('<span>')
                .attr({'class': 'glyphicon glyphicon-filter', 'aria-hidden': 'true'}),
            filterButton = $('<button>')
                .attr({'class': 'btn btn-default btn-xs', 'type': 'button', 'title': 'Reset Filter'})
                .append(filterIcon);

        filterButton.on('mouseup', $.proxy(function () {
            $(filterButton).blur();
            this.onReset();
            this.notifyListeners('onFilterChanged', {context: this, filter: this.getFilter()});
        }, this));

        this.filterButton = filterButton;

        return $('<div>').attr({'class': 'btn-group', 'role': 'group'}).append(filterButton);
    };

    perwheel.PerWheel.prototype.createCalendarButtonGroup = function () {
        var // menu
            calendarHeader = $('<li>').attr({'class': 'dropdown-header', 'role': 'presentation'}).text('Calendar'),
            gregorian = $('<a>').attr({'role': 'menuitem'}).text('Gregorian ').append($('<span>').attr({'class': 'glyphicon glyphicon-ok-sign', 'aria-hidden': 'true'})),
            islamic = $('<a>').attr({'role': 'menuitem'}).text('Islamic '),
            menu = $('<ul>')
            .attr({'class': 'dropdown-menu', 'role': 'menu'})
            .append([
                calendarHeader,
                $('<li>').attr({'role': 'presentation'}).append(gregorian),
                $('<li>').attr({'role': 'presentation'}).append(islamic)
            ]),
        // button
            calendarIcon = $('<span>').attr({'class': 'glyphicon glyphicon-calendar', 'aria-hidden': 'true'}),
            calendarButton = $('<button>')
                .attr({'class': 'btn btn-default btn-xs dropdown-toggle', 'type': 'button', 'data-toggle': 'dropdown', 'title': 'Change Calendar System'})
                .append(calendarIcon, ' ', $('<span>').attr({'class': 'caret'}));

        // add events here
        gregorian.on('mouseup', $.proxy(function () {
            this.setCalendar('gregorian');
        }, this));

        islamic.on('mouseup', $.proxy(function () {
            this.setCalendar('islamic');
        }, this));

        this.calendarButtons.gregorian = gregorian;
        this.calendarButtons.islamic = islamic;

        return $('<div>').attr({'class': 'btn-group', 'role': 'group'}).append(calendarButton, menu);
    };

    perwheel.PerWheel.prototype.createTimeWheel = function () {
        var timeWheelDiv = $('<div>');
        this.timeWheel = new timewheel.TimeWheel(this.calendarName)
            .render(timeWheelDiv.get(0))
            .registerListener({
                context: this,
                onTimeWheelSelectionChanged: function () {
                    this.notifyListeners('onFilterChanged', {context: this, filter: this.getFilter()});
                    this.validateFilterButton();
                }
            });
        return timeWheelDiv;
    };

    perwheel.PerWheel.prototype.validateFilterButton = function () {
        var twData = this.getData(),
            shouldEnable = Object.keys(twData.periodicity).every(function (key) {
                return twData.periodicity[key].data.every(function (cycle) {
                    return cycle.isEnabled;
                });
            });
        this.filterButton.toggleClass('disabled', shouldEnable);
    };

    perwheel.PerWheel.prototype.getData = function () {
        return {
            calendarName: this.calendarName,
            periodicity: this.timeWheel.getData()
        };
    };

    perwheel.PerWheel.prototype.getFilter = function () {
        var data = this.getData(),
            cal = $.calendars.instance(data.calendarName);
        this.filter.filterOn = function (julianDate) {
            var date = cal.fromJD(julianDate);
            if (!data.periodicity.dayOfWeek.data[date.dayOfWeek()].isEnabled) {
                return false;
            }
            if (!data.periodicity.dayOfMonth.data[date.day() - 1].isEnabled) {
                return false;
            }
            if (!data.periodicity.monthOfYear.data[date.month() - 1].isEnabled) {
                return false;
            }
            return true;
        };
        return this.filter;
    };

    perwheel.PerWheel.prototype.setContentAttribute = function (contentAttribute) {
        this.timeWheel.setContentAttribute(contentAttribute);
    };

    perwheel.PerWheel.prototype.setCalendar = function (calendarName) {
        if (this.calendarButtons.hasOwnProperty(calendarName)) {
            [this.calendarButtons.islamic, this.calendarButtons.gregorian].forEach(function (b) {
                b.find('.glyphicon').remove();
            });
            this.calendarButtons[calendarName].append(
                $('<span>').attr({'class': 'glyphicon glyphicon-ok-sign', 'aria-hidden': 'true'})
            );

            this.calendarName = calendarName;
            this.timeWheel.setCalendar(this.calendarName);
            this.filter.filterOn = function () {return true; };
            this.notifyListeners('onFilterChanged', {context: this, filter: this.filter});
        }
    };

    perwheel.PerWheel.prototype.onReset = function () {
        this.filterButton.toggleClass('disabled', true);
        this.filter.filterOn = function () {return true; };
        this.timeWheel.setAllEnabled();
    };

    perwheel.PerWheel.prototype.notifyListeners = function (callbackStr, event) {
        this.listeners.forEach(function (listenerObj) {
            listenerObj[callbackStr].call(listenerObj.context, event);
        }, this);
    };

    perwheel.PerWheel.prototype.registerListener = function (callbackObj) {
        this.listeners.push(callbackObj);
        return this;
    };

    perwheel.PerWheel.prototype.onSelectionChanged = function (data) {
        this.timeWheel.onSelectionChanged(data);
    };

    perwheel.PerWheel.prototype.onDataSetChanged = function (data, metadata) {
        this.metadata = metadata;
        this.timeWheel.onDataSetChanged(data, metadata);
        this.filterButton.toggleClass('disabled', true);
    };

    return perwheel;

});
<|endoftext|>