<commit_before>'use strict';

angular.module('GreatMath.session-scheduler', ['GreatMath.topic-registry'])

.factory('sessionScheduler', ['topicRegistry',function(topicRegistry) {
  //rows are weeks,
  //columns are topics
  var distributionTable=[
    [1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0],
    [1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1],
    [0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0],
    [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1],
    [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0],
    [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1],
    [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0],
    [1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1],
    [0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1],
    [1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0],
    [1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1],
    [0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0],
    [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1],
    [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0],
    [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1],
    [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0],
    [1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1],
    [0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1],
    [1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0],
    [1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1],
    [0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0],
    [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1],
    [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0],
    [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1],
    [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0],
    [1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1],
    [0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1]

  ];

  function scheduleKeySkillsQuestions(week,weekIndex,resolve){

    topicRegistry.getTopics({class:'keySkills'},function(topics){
      //distributionTable.forEach(function(row,weekIndex){
        /*while(schedule.weeks.length<=weekIndex){
          schedule.weeks.push({});
        }*/
        var row=distributionTable[weekIndex];
        week.keySkills={questionSpecs:[]};
        row.forEach(function(cell,topicIndex){
          if(cell>0){
            var topicId=null;
            if(topicIndex<topics.length){
              topicId=topics[topicIndex].id;
            }
            week.keySkills.questionSpecs.push({id:topicId});
          }
        });
      //});
      resolve();
    });

  }
  return {
    /*calls the callback with an array of objects.  Each object represents a week and contains 3 arrays of topic ids

    */
    createDistribution : function (callback){
        var numberOfWeeks                             = 39;
        var numberOfSessionsPerWeek                   =  5;
        var numberOfTimesTableQuestionsPerSession     = 10;
        var numberOfKeySkillsQuestionsPerSession      = 10;
        var i=0;

        var result = {
          weeks:[
          ]
        };

        //mental strategies
        topicRegistry.getTopics({class:'mentalStrategies'},function(topics){
          distributionTable.forEach(function(row,weekIndex){
            var week = {
              number : weekIndex+1,
              mentalStrategies:{
                topics : []
              }
            };
            row.forEach(function(cell,topicIndex){
              //0 means no questions on that topic this week.
              //1 ( or anything greater than 0, for that matter) means there is one question on that topic this week
              if(cell>0 ){
                week.mentalStrategies.topics.push({
                  id: topicIndex>=topics.length ? null : topics[topicIndex].id //use null as placeholder when there are less than 26 topics
                });
              }
            });
            week.timesTable={
              questionSpecs:[]
            };

            //times tables
            topicRegistry.getTopics({class:'timesTable'},function(ttTopics){
              var ttTopicId;
              if(ttTopics.length==0){
                ttTopicId=null;
              }else{
                ttTopicId=ttTopics[0].id;
              }
              for(var questionNumber=1;questionNumber<=10;questionNumber++){
                var multiplier = 2 + Math.floor( 9 * Math.random());

                week.timesTable.questionSpecs.push(
                {
                  id         : ttTopicId,
                  multiplier : multiplier
                });

              }

              scheduleKeySkillsQuestions(week,weekIndex,
              function(){//TODO refactor: use promise pattern
                setTimeout(function(){
                  callback(result);
                },0);
              });

            });
            result.weeks.push(week);
          });

        });

    }
  };
}]);<commit_msg>refactor<commit_after>'use strict';

angular.module('GreatMath.session-scheduler', ['GreatMath.topic-registry'])

.factory('sessionScheduler', ['topicRegistry',function(topicRegistry) {
  //rows are weeks,
  //columns are topics
  var distributionTable=[
    [1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0],
    [1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1],
    [0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0],
    [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1],
    [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0],
    [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1],
    [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0],
    [1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1],
    [0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1],
    [1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0],
    [1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1],
    [0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0],
    [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1],
    [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0],
    [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1],
    [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0],
    [1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1],
    [0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1],
    [1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0],
    [1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1],
    [0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0],
    [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1],
    [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0],
    [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1],
    [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0],
    [1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1],
    [0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1]

  ];

  function scheduleKeySkillsQuestions(week,weekIndex,resolve){

    topicRegistry.getTopics({class:'keySkills'},function(topics){
      //distributionTable.forEach(function(row,weekIndex){
        /*while(schedule.weeks.length<=weekIndex){
          schedule.weeks.push({});
        }*/
        var row=distributionTable[weekIndex];
        week.keySkills={questionSpecs:[]};
        row.forEach(function(cell,topicIndex){
          if(cell>0){
            var topicId=null;
            if(topicIndex<topics.length){
              topicId=topics[topicIndex].id;
            }
            week.keySkills.questionSpecs.push({id:topicId});
          }
        });
      //});
      resolve();
    });

  }

  function scheduleMentalStrategyQuestion(week,weekIndex,callback){

    topicRegistry.getTopics({class:'mentalStrategies'},function(topics){
      var row = distributionTable[weekIndex];
      row.forEach(function(cell,topicIndex){
        //0 means no questions on that topic this week.
        //1 ( or anything greater than 0, for that matter) means there is one question on that topic this week
        if(cell>0 ){
          week.mentalStrategies.topics.push({
            id: topicIndex>=topics.length ? null : topics[topicIndex].id //use null as placeholder when there are less than 26 topics
          });
        }
      });

      //times tables
      week.timesTable={
        questionSpecs:[]
      };
      topicRegistry.getTopics({class:'timesTable'},function(ttTopics){
        var ttTopicId;
        if(ttTopics.length==0){
          ttTopicId=null;
        }else{
          ttTopicId=ttTopics[0].id;
        }
        for(var questionNumber=1;questionNumber<=10;questionNumber++){
          var multiplier = 2 + Math.floor( 9 * Math.random());

          week.timesTable.questionSpecs.push(
          {
            id         : ttTopicId,
            multiplier : multiplier
          });

        }
        callback();

      });
    });

  }

  return {
    /*calls the callback with an array of objects.  Each object represents a week and contains 3 arrays of topic ids

    */
    createDistribution : function (callback){
        var numberOfWeeks                             = 39;
        var numberOfSessionsPerWeek                   =  5;
        var numberOfTimesTableQuestionsPerSession     = 10;
        var numberOfKeySkillsQuestionsPerSession      = 10;
        var i=0;

        var result = {
          weeks:[
          ]
        };
        for(var i=0;i<numberOfWeeks;i++){
          var weekIndex=i;
          var week = {
            number : weekIndex+1,
            mentalStrategies:{
              topics : []
            }
          };
          result.weeks.push(week);
          //mental strategies
          (function(week,weekIndex){
            scheduleMentalStrategyQuestion(
              week,
              weekIndex,
              function(){//TODO refactor: use promise pattern
                scheduleKeySkillsQuestions(
                  week,
                  weekIndex,
                  function(){
                    setTimeout(function(){
                      callback(result);
                    },0);
                  }
                );
              }
            );
          })(week,
            weekIndex);

        }

    }
  };
}]);<|endoftext|>


<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.object.keyvalue.propertiespanel");
pimcore.object.keyvalue.propertiespanel = Class.create({

    initialize: function () {
    },

    getPanel: function () {
        if (this.layout == null) {
            this.layout = new Ext.Panel({
                title: t("keyValue_properties"),
                border: false,
                layout: "fit",
                region: "center"
            });

            this.createGrid();
        }

        this.layout.on("activate", this.panelActivated.bind(this));

        return this.layout;
    },

    panelActivated: function() {
        if (this.store) {
            this.store.reload();
        }
    },

    createGrid: function(response) {
        this.fields = ['id', 'name', 'description', 'type', 'unit', 'group', 'groupdescription','possiblevalues',
            'translator', 'mandatory','creationDate', 'modificationDate'];

        var readerFields = [];
        for (var i = 0; i < this.fields.length; i++) {
            readerFields.push({name: this.fields[i]});
        }

        var proxy = {
            type: 'ajax',
            url: "/admin/key-value/properties",
            reader: {
                type: 'json',
                rootProperty: 'data'
            },
            writer: {
                type: 'json'
            },
            extraParams: this.baseParams
        };

        var listeners = {};

        listeners.write = function(store, action, result, response, rs) {};
        listeners.exception = function (conn, mode, action, request, response, store) {
            if(action == "update") {
                Ext.MessageBox.alert(t('error'), t('cannot_save_object_please_try_to_edit_the_object_in_detail_view'));
                this.store.rejectChanges();
            }
        }.bind(this);

        this.store = new Ext.data.Store({
            autoSync: true,
            proxy: proxy,
            fields: readerFields,
            listeners: listeners,

        });

        var gridColumns = [];

        gridColumns.push({header: "ID", width: 40, sortable: true, dataIndex: 'id'});
        gridColumns.push({header: t("name"), width: 200, sortable: true, dataIndex: 'name',editor: new Ext.form.TextField({}), filter: 'string'});
        gridColumns.push({header: t("description"), width: 200, sortable: true, dataIndex: 'description',editor: new Ext.form.TextField({}), filter: 'string'});
        gridColumns.push({header: t("type"), width: 100, sortable: true, dataIndex: 'type',
            editor: new Ext.form.ComboBox({
                triggerAction: 'all',
                editable: false,
                store: ["text","number","bool","select","translated","translatedSelect", "range"]

            }), filter: 'string'});

        var mandatory = Ext.create('Ext.grid.column.Check', {
            header: t("mandatory"),
            dataIndex: "mandatory",
            width: 50
        });

        gridColumns.push({
            hideable: false,
            xtype: 'actioncolumn',
            width: 30,
            items: [
                {
                    tooltip: t("keyvalue_detailed_configuration"),
                    icon: "/pimcore/static/img/icon/building_edit.png",
                    handler: function (grid, rowIndex) {
                        var data = grid.getStore().getAt(rowIndex);
                        var id = data.data.id;

                        var type = data.data.type;
                        var possiblevalues = data.data.possiblevalues;

                        if (type == 'select' || type == 'translatedSelect') {
                            var specialConfigWindow = new pimcore.object.keyvalue.specialconfigwindow(
                                Ext.util.JSON.decode(possiblevalues), data.id, this);
                            specialConfigWindow.show();
                        } else if (type == 'translated') {
                            var translatorConfigWindow = new pimcore.object.keyvalue.translatorconfigwindow(
                                data.id, this, data.data.translator).show();
                        } else {
                            alert(t("keyvalue_define_select_values_error"));
                        }
                    }.bind(this)
                }
            ]
        });

        gridColumns.push({header: t("keyvalue_unit"), width: 100, sortable: true, dataIndex: 'unit',
            editor: new Ext.form.TextField({})});
        gridColumns.push({header: t("keyvalue_col_groupid"), width: 40, sortable: true, dataIndex: 'group'});
        gridColumns.push({header: t("keyvalue_col_groupdescription"), width: 200, sortable: false,
            dataIndex: 'groupdescription', filter: 'string'});

        gridColumns.push(mandatory);

        gridColumns.push(
            {header: t("creationDate"), sortable: true, dataIndex: 'creationDate', editable: false, width: 130,
                hidden: true,
                renderer: function(d) {
                    if (d !== undefined) {
                        var date = new Date(d * 1000);
                        return Ext.Date.format(date, "Y-m-d H:i:s");
                    } else {
                        return "";
                    }
                }
            }
        );

        gridColumns.push(
            {header: t("modificationDate"), sortable: true, dataIndex: 'modificationDate', editable: false, width: 130,
                hidden: true,
                renderer: function(d) {
                    if (d !== undefined) {
                        var date = new Date(d * 1000);
                        return Ext.Date.format(date, "Y-m-d H:i:s");
                    } else {
                        return "";
                    }
                }
            }
        );

        gridColumns.push({
            hideable: false,
            xtype: 'actioncolumn',
            width: 30,
            items: [
                {
                    tooltip: t('keyvalue_find_group'),
                    icon: "/pimcore/static/img/icon/magnifier.png",
                    handler: function (grid, rowIndex) {
                        var data = grid.getStore().getAt(rowIndex);
                        var id = data.data.id;
                        this.selectData = data;
                        this.showSearchWindow();
                    }.bind(this)
                }
            ]
        });

        gridColumns.push({
            hideable: false,
            xtype: 'actioncolumn',
            width: 30,
            items: [
                {
                    tooltip: t('remove'),
                    icon: "/pimcore/static/img/icon/cross.png",
                    handler: function (grid, rowIndex) {
                        var data = grid.getStore().getAt(rowIndex);
                        var id = data.data.id;

                        Ext.Ajax.request({
                            url: "/admin/key-value/deleteproperty",
                            params: {
                                id: id
                            },
                            success: function (response) {
                                this.store.reload();
                            }.bind(this)});
                    }.bind(this)
                }
            ]
        });

        gridColumns.push({header: t("keyvalue_col_translator"), width: 40, sortable: true, dataIndex: 'translator'});

        this.pagingtoolbar = new Ext.PagingToolbar({
            pageSize: 15,
            store: this.store,
            displayInfo: true,
            displayMsg: '{0} - {1} / {2}',
            emptyMsg: t("keyvalue_no_keys")
        });

        //var configuredFilters = [{
        //    type: "string",
        //    dataIndex: "name"
        //},
        //    {
        //        type: "string",
        //        dataIndex: "description"
        //    },
        //    {
        //        type: "string",
        //        dataIndex: "type"
        //    },
        //    {
        //        type: "string",
        //        dataIndex: "unit"
        //    },
        //    {
        //        type: "string",
        //        dataIndex: "group"
        //    }
        //];
        //this.gridfilters = new Ext.ux.grid.GridFilters({
        //    encode: true,
        //    local: false,
        //    filters: configuredFilters
        //});
        this.cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1
        });

        var plugins = ['gridfilters', this.cellEditing];

        var gridConfig = {
            frame: false,
            store: this.store,
            border: true,
            columns: gridColumns,
            loadMask: true,
            columnLines: true,
            plugins: plugins,
            stripeRows: true,
            trackMouseOver: true,
            viewConfig: {
                forceFit: false
            },
            selModel: Ext.create('Ext.selection.RowModel', {}),
            bbar: this.pagingtoolbar,
            tbar: [

                {
                    text: t('add'),
                    handler: this.onAdd.bind(this),
                    iconCls: "pimcore_icon_add"
                }
            ],
            listeners: {
                rowdblclick: function (grid, record, tr, rowIndex, e, eOpts ) {

                }.bind(this)
            }
        } ;

        this.grid = Ext.create('Ext.grid.Panel' ,gridConfig);

        this.store.load();

        this.layout.removeAll();
        this.layout.add(this.grid);
        this.layout.doLayout();
    },

    applyTranslatorConfig: function(keyid, value) {
        var data = this.store.getById(keyid);
        data.set("translator", value);
    },

    applyDetailedConfig: function(keyid, value) {
        var data = this.store.getById(keyid);
        data.set("possiblevalues",  Ext.util.JSON.encode(value));
        //  this.store.save();
    },

    onAdd: function () {
        Ext.MessageBox.prompt(t('keyvalue_mbx_enterkey_title'), t('keyvalue_mbx_enterkey_prompt'),
            this.addFieldComplete.bind(this), null, null, "");
    },

    addFieldComplete: function (button, value, object) {

        value = value.trim();
        if (button == "ok" && value.length > 1) {
            Ext.Ajax.request({
                url: "/admin/key-value/addproperty",
                params: {
                    name: value
                },
                success: function (response) {
                    var data = Ext.decode(response.responseText);

                    if(!data || !data.success) {
                        Ext.Msg.alert(t("keyvalue_error_addkey_title"), t("keyvalue_error_addkey_msg"));
                    } else {

                        this.store.reload({
                                callback: function() {
                                    var rowIndex = this.store.find('name', value);
                                    // alert(rowIndex);
                                    if (rowIndex != -1) {
                                        var sm = this.grid.getSelectionModel();
                                        sm.select(rowIndex);
                                    }

                                    var lastOptions = this.store.lastOptions;
                                    Ext.apply(lastOptions.params, {
                                        overrideSort: "false"
                                    });

//                                    this.store.setBaseParam("overrideSort", "false");
                                }.bind(this),
                                params: {
                                    "overrideSort": "true"
                                }

                            }

                        );
                    }
                }.bind(this)
            });
        }
        else if (button == "cancel") {
            return;
        }
        else {
            Ext.Msg.alert(t("keyvalue_configuration"), t("keyvalue_invalidname"));
        }
    },

    showSearchWindow: function() {

        this.searchfield = new Ext.form.TextField({
            width: 300,
            style: "float: left;",
            fieldLabel: t("search")
        });

        var resultPanel = this.getResultPanel();

        this.searchWindow = new Ext.Window({
            modal: true,
            width: 600,
            height: 500,
            layout: "fit",
            resizable: false,
            title: t("keyvalue_select_group"),
            items: [resultPanel],
            tbar: [this.searchfield,
                {
                    xtype: "button",
                    text: t("search"),
                    icon: "/pimcore/static/img/icon/magnifier.png",
                    handler: function () {
                        var formValue = this.searchfield.getValue();

                        var filter = [{
                            "field": "description",
                            "value" :formValue},
                            {
                                "field": "name",
                                "value" :formValue}
                        ];
                        this.groupStore.baseparams = {};

                        this.groupStore.getProxy().setExtraParam("filter", Ext.util.JSON.encode(filter));

                        this.groupPagingtoolbar.moveFirst();
                    }.bind(this)
                }],
            bbar: ["->",{
                xtype: "button",
                text: t("cancel"),
                icon: "/pimcore/static/img/icon/cancel.png",
                handler: function () {
                    this.searchWindow.close();
                }.bind(this)
            },{
                xtype: "button",
                text: t("apply"),
                iconCls: "pimcore_icon_apply",
                handler: function () {
                    var data = this.getData();
                    if (data) {
                        this.selectData.set("group", data.id);
                        this.selectData.set("groupdescription", data.description);
                    } else {
                        this.selectData.set("group", null);
                        this.selectData.set("groupdescription", null);
                    }
                    this.store.save();
                    this.searchWindow.close();
                }.bind(this)
            }],
            plain: true
        });

        this.searchWindow.show();
    },

    getResultPanel: function () {
        this.resultPanel = new Ext.Panel({
            layout: "fit"
        });

        this.getGridPanel();
        return this.resultPanel;
    },

    getData: function () {
        var selected = this.groupGridPanel.getSelectionModel().getSelected();
        if(selected) {
            return selected.data;
        }
        return null;
    },

    getGridPanel: function() {

        this.groupFields = ['id', 'name', 'description'];

        var readerFields = [];
        for (var i = 0; i < this.groupFields.length; i++) {
            readerFields.push({name: this.groupFields[i], allowBlank: true});
        }

        var gridColumns = [];
        gridColumns.push({header: "ID", width: 40, sortable: true, dataIndex: 'id'});
        gridColumns.push({header: t("name"), width: 200, sortable: true, dataIndex: 'name'});
        gridColumns.push({header: t("description"), width: 340, sortable: true, dataIndex: 'description'});

        var proxy = new Ext.data.HttpProxy({
            url: "/admin/key-value/groups",
            method: 'post'
        });

        var reader = new Ext.data.JsonReader({
            totalProperty: 'total',
            successProperty: 'success',
            root: 'data'
        }, readerFields);

        this.groupStore = new Ext.data.Store({
            restful: false,
            idProperty: 'id',
            remoteSort: true,
            proxy: proxy,
            reader: reader
        });

        this.groupPagingtoolbar = new Ext.PagingToolbar({
            pageSize: 50,
            store: this.groupStore,
            displayInfo: true,
            displayMsg: '{0} - {1} / {2}',
            emptyMsg: t("keyvalue_no_groups")
        });

        this.groupGridPanel = new Ext.grid.GridPanel({
            store: this.groupStore,
            border: false,
            columns: gridColumns,
            loadMask: true,
            columnLines: true,
            stripeRows: true,
            sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
            bbar: this.groupPagingtoolbar,
            listeners: {
                rowdblclick: function (grid, record, tr, rowIndex, e, eOpts ) {
                    var data = grid.getStore().getAt(rowIndex);

                    this.selectData.set("group", data.id);
                    this.selectData.set("groupdescription", data.data.description);
                    this.store.save();
                    this.searchWindow.close();

                }.bind(this)
            }
        });

        this.groupStore.load();

        this.resultPanel.removeAll();
        this.resultPanel.add(this.groupGridPanel);
        this.resultPanel.doLayout();
    }
});<commit_msg>keyvalue defintion: made group search window work again<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.object.keyvalue.propertiespanel");
pimcore.object.keyvalue.propertiespanel = Class.create({

    initialize: function () {
    },

    getPanel: function () {
        if (this.layout == null) {
            this.layout = new Ext.Panel({
                title: t("keyValue_properties"),
                border: false,
                layout: "fit",
                region: "center"
            });

            this.createGrid();
        }

        this.layout.on("activate", this.panelActivated.bind(this));

        return this.layout;
    },

    panelActivated: function() {
        if (this.store) {
            this.store.reload();
        }
    },

    createGrid: function(response) {
        this.fields = ['id', 'name', 'description', 'type', 'unit', 'group', 'groupdescription','possiblevalues',
            'translator', 'mandatory','creationDate', 'modificationDate'];

        var readerFields = [];
        for (var i = 0; i < this.fields.length; i++) {
            readerFields.push({name: this.fields[i]});
        }

        var proxy = {
            type: 'ajax',
            url: "/admin/key-value/properties",
            reader: {
                type: 'json',
                rootProperty: 'data'
            },
            writer: {
                type: 'json'
            },
            extraParams: this.baseParams
        };

        var listeners = {};

        listeners.write = function(store, action, result, response, rs) {};
        listeners.exception = function (conn, mode, action, request, response, store) {
            if(action == "update") {
                Ext.MessageBox.alert(t('error'), t('cannot_save_object_please_try_to_edit_the_object_in_detail_view'));
                this.store.rejectChanges();
            }
        }.bind(this);

        this.store = new Ext.data.Store({
            autoSync: true,
            proxy: proxy,
            fields: readerFields,
            listeners: listeners
        });

        var gridColumns = [];

        gridColumns.push({header: "ID", width: 40, sortable: true, dataIndex: 'id'});
        gridColumns.push({header: t("name"), width: 200, sortable: true, dataIndex: 'name',editor: new Ext.form.TextField({}), filter: 'string'});
        gridColumns.push({header: t("description"), width: 200, sortable: true, dataIndex: 'description',editor: new Ext.form.TextField({}), filter: 'string'});
        gridColumns.push({header: t("type"), width: 100, sortable: true, dataIndex: 'type',
            editor: new Ext.form.ComboBox({
                triggerAction: 'all',
                editable: false,
                store: ["text","number","bool","select","translated","translatedSelect", "range"]

            }), filter: 'string'});

        var mandatory = Ext.create('Ext.grid.column.Check', {
            header: t("mandatory"),
            dataIndex: "mandatory",
            width: 50
        });

        gridColumns.push({
            hideable: false,
            xtype: 'actioncolumn',
            width: 30,
            items: [
                {
                    tooltip: t("keyvalue_detailed_configuration"),
                    icon: "/pimcore/static/img/icon/building_edit.png",
                    handler: function (grid, rowIndex) {
                        var data = grid.getStore().getAt(rowIndex);
                        var id = data.data.id;

                        var type = data.data.type;
                        var possiblevalues = data.data.possiblevalues;

                        if (type == 'select' || type == 'translatedSelect') {
                            var specialConfigWindow = new pimcore.object.keyvalue.specialconfigwindow(
                                Ext.util.JSON.decode(possiblevalues), data.id, this);
                            specialConfigWindow.show();
                        } else if (type == 'translated') {
                            var translatorConfigWindow = new pimcore.object.keyvalue.translatorconfigwindow(
                                data.id, this, data.data.translator).show();
                        } else {
                            alert(t("keyvalue_define_select_values_error"));
                        }
                    }.bind(this)
                }
            ]
        });

        gridColumns.push({header: t("keyvalue_unit"), width: 100, sortable: true, dataIndex: 'unit',
            editor: new Ext.form.TextField({})});
        gridColumns.push({header: t("keyvalue_col_groupid"), width: 40, sortable: true, dataIndex: 'group'});
        gridColumns.push({header: t("keyvalue_col_groupdescription"), width: 200, sortable: false,
            dataIndex: 'groupdescription', filter: 'string'});

        gridColumns.push(mandatory);

        gridColumns.push(
            {header: t("creationDate"), sortable: true, dataIndex: 'creationDate', editable: false, width: 130,
                hidden: true,
                renderer: function(d) {
                    if (d !== undefined) {
                        var date = new Date(d * 1000);
                        return Ext.Date.format(date, "Y-m-d H:i:s");
                    } else {
                        return "";
                    }
                }
            }
        );

        gridColumns.push(
            {header: t("modificationDate"), sortable: true, dataIndex: 'modificationDate', editable: false, width: 130,
                hidden: true,
                renderer: function(d) {
                    if (d !== undefined) {
                        var date = new Date(d * 1000);
                        return Ext.Date.format(date, "Y-m-d H:i:s");
                    } else {
                        return "";
                    }
                }
            }
        );

        gridColumns.push({
            hideable: false,
            xtype: 'actioncolumn',
            width: 30,
            items: [
                {
                    tooltip: t('keyvalue_find_group'),
                    icon: "/pimcore/static/img/icon/magnifier.png",
                    handler: function (grid, rowIndex) {
                        var data = grid.getStore().getAt(rowIndex);
                        var id = data.data.id;
                        this.selectData = data;
                        this.showSearchWindow();
                    }.bind(this)
                }
            ]
        });

        gridColumns.push({
            hideable: false,
            xtype: 'actioncolumn',
            width: 30,
            items: [
                {
                    tooltip: t('remove'),
                    icon: "/pimcore/static/img/icon/cross.png",
                    handler: function (grid, rowIndex) {
                        var data = grid.getStore().getAt(rowIndex);
                        var id = data.data.id;

                        Ext.Ajax.request({
                            url: "/admin/key-value/deleteproperty",
                            params: {
                                id: id
                            },
                            success: function (response) {
                                this.store.reload();
                            }.bind(this)});
                    }.bind(this)
                }
            ]
        });

        gridColumns.push({header: t("keyvalue_col_translator"), width: 40, sortable: true, dataIndex: 'translator'});

        this.pagingtoolbar = new Ext.PagingToolbar({
            pageSize: 15,
            store: this.store,
            displayInfo: true,
            displayMsg: '{0} - {1} / {2}',
            emptyMsg: t("keyvalue_no_keys")
        });

        //var configuredFilters = [{
        //    type: "string",
        //    dataIndex: "name"
        //},
        //    {
        //        type: "string",
        //        dataIndex: "description"
        //    },
        //    {
        //        type: "string",
        //        dataIndex: "type"
        //    },
        //    {
        //        type: "string",
        //        dataIndex: "unit"
        //    },
        //    {
        //        type: "string",
        //        dataIndex: "group"
        //    }
        //];
        //this.gridfilters = new Ext.ux.grid.GridFilters({
        //    encode: true,
        //    local: false,
        //    filters: configuredFilters
        //});
        this.cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1
        });

        var plugins = ['gridfilters', this.cellEditing];

        var gridConfig = {
            frame: false,
            store: this.store,
            border: true,
            columns: gridColumns,
            loadMask: true,
            columnLines: true,
            plugins: plugins,
            stripeRows: true,
            trackMouseOver: true,
            viewConfig: {
                forceFit: false
            },
            selModel: Ext.create('Ext.selection.RowModel', {}),
            bbar: this.pagingtoolbar,
            tbar: [

                {
                    text: t('add'),
                    handler: this.onAdd.bind(this),
                    iconCls: "pimcore_icon_add"
                }
            ],
            listeners: {
                rowdblclick: function (grid, record, tr, rowIndex, e, eOpts ) {

                }.bind(this)
            }
        } ;

        this.grid = Ext.create('Ext.grid.Panel' ,gridConfig);

        this.store.load();

        this.layout.removeAll();
        this.layout.add(this.grid);
        this.layout.doLayout();
    },

    applyTranslatorConfig: function(keyid, value) {
        var data = this.store.getById(keyid);
        data.set("translator", value);
    },

    applyDetailedConfig: function(keyid, value) {
        var data = this.store.getById(keyid);
        data.set("possiblevalues",  Ext.util.JSON.encode(value));
        //  this.store.save();
    },

    onAdd: function () {
        Ext.MessageBox.prompt(t('keyvalue_mbx_enterkey_title'), t('keyvalue_mbx_enterkey_prompt'),
            this.addFieldComplete.bind(this), null, null, "");
    },

    addFieldComplete: function (button, value, object) {

        value = value.trim();
        if (button == "ok" && value.length > 1) {
            Ext.Ajax.request({
                url: "/admin/key-value/addproperty",
                params: {
                    name: value
                },
                success: function (response) {
                    var data = Ext.decode(response.responseText);

                    if(!data || !data.success) {
                        Ext.Msg.alert(t("keyvalue_error_addkey_title"), t("keyvalue_error_addkey_msg"));
                    } else {

                        this.store.reload({
                                callback: function() {
                                    var rowIndex = this.store.find('name', value);
                                    // alert(rowIndex);
                                    if (rowIndex != -1) {
                                        var sm = this.grid.getSelectionModel();
                                        sm.select(rowIndex);
                                    }

                                    var lastOptions = this.store.lastOptions;
                                    Ext.apply(lastOptions.params, {
                                        overrideSort: "false"
                                    });

//                                    this.store.setBaseParam("overrideSort", "false");
                                }.bind(this),
                                params: {
                                    "overrideSort": "true"
                                }

                            }

                        );
                    }
                }.bind(this)
            });
        }
        else if (button == "cancel") {
            return;
        }
        else {
            Ext.Msg.alert(t("keyvalue_configuration"), t("keyvalue_invalidname"));
        }
    },

    showSearchWindow: function() {

        this.searchfield = new Ext.form.TextField({
            width: 300,
            style: "float: left;",
            fieldLabel: t("search")
        });

        var resultPanel = this.getResultPanel();

        this.searchWindow = new Ext.Window({
            modal: true,
            width: 600,
            height: 500,
            layout: "fit",
            resizable: false,
            title: t("keyvalue_select_group"),
            items: [resultPanel],
            tbar: [this.searchfield,
                {
                    xtype: "button",
                    text: t("search"),
                    icon: "/pimcore/static/img/icon/magnifier.png",
                    handler: function () {
                        var formValue = this.searchfield.getValue();

                        var filter = [{
                            "field": "description",
                            "value" :formValue},
                            {
                                "field": "name",
                                "value" :formValue}
                        ];
                        this.groupStore.baseparams = {};

                        this.groupStore.getProxy().setExtraParam("filter", Ext.util.JSON.encode(filter));

                        this.groupPagingtoolbar.moveFirst();
                    }.bind(this)
                }],
            bbar: ["->",{
                xtype: "button",
                text: t("cancel"),
                icon: "/pimcore/static/img/icon/cancel.png",
                handler: function () {
                    this.searchWindow.close();
                }.bind(this)
            },{
                xtype: "button",
                text: t("apply"),
                iconCls: "pimcore_icon_apply",
                handler: function () {
                    var data = this.getData();
                    if (data) {
                        this.selectData.set("group", data.id);
                        this.selectData.set("groupdescription", data.description);
                    } else {
                        this.selectData.set("group", null);
                        this.selectData.set("groupdescription", null);
                    }
                    this.store.save();
                    this.searchWindow.close();
                }.bind(this)
            }],
            plain: true
        });

        this.searchWindow.show();
    },

    getResultPanel: function () {
        this.resultPanel = new Ext.Panel({
            layout: "fit"
        });

        this.getGridPanel();
        return this.resultPanel;
    },

    getData: function () {
        var selected = this.groupGridPanel.getSelectionModel().getSelected();
        if(selected) {
            return selected.data;
        }
        return null;
    },

    getGridPanel: function() {

        this.groupFields = ['id', 'name', 'description'];

        var readerFields = [];
        for (var i = 0; i < this.groupFields.length; i++) {
            readerFields.push({name: this.groupFields[i], allowBlank: true});
        }

        var gridColumns = [];
        gridColumns.push({header: "ID", width: 40, sortable: true, dataIndex: 'id'});
        gridColumns.push({header: t("name"), width: 200, sortable: true, dataIndex: 'name'});
        gridColumns.push({header: t("description"), width: 340, sortable: true, dataIndex: 'description'});

        var proxy = {
            type: 'ajax',
            url: "/admin/key-value/groups",
            reader: {
                type: 'json',
                totalProperty: 'total',
                successProperty: 'success',
                rootProperty: 'data'
            }
        };

        this.groupStore = new Ext.data.Store({
            remoteSort: true,
            proxy: proxy,
            fields: readerFields
        });

        this.groupPagingtoolbar = new Ext.PagingToolbar({
            pageSize: 50,
            store: this.groupStore,
            displayInfo: true,
            displayMsg: '{0} - {1} / {2}',
            emptyMsg: t("keyvalue_no_groups")
        });

        this.groupGridPanel = new Ext.grid.GridPanel({
            store: this.groupStore,
            border: false,
            columns: gridColumns,
            loadMask: true,
            columnLines: true,
            stripeRows: true,
            selModel: Ext.create('Ext.selection.RowModel', {}),
            bbar: this.groupPagingtoolbar,
            listeners: {
                rowdblclick: function (grid, record, tr, rowIndex, e, eOpts ) {
                    var data = grid.getStore().getAt(rowIndex);

                    this.selectData.set("group", data.id);
                    this.selectData.set("groupdescription", data.data.description);
                    this.store.save();
                    this.searchWindow.close();

                }.bind(this)
            }
        });

        this.groupStore.load();

        this.resultPanel.removeAll();
        this.resultPanel.add(this.groupGridPanel);
        this.resultPanel.doLayout();
    }
});<|endoftext|>


<commit_before>/** @jsx React.DOM */
'use strict';
var React = require('react');
var url = require('url');
var _ = require('underscore');
var globals = require('./globals');
var dataset = require('./dataset');
var fetched = require('./fetched');
var dbxref = require('./dbxref');
var image = require('./image');
var statuslabel = require('./statuslabel');

var Attachment = image.Attachment;
var DbxrefList = dbxref.DbxrefList;
var FetchedItems = fetched.FetchedItems;
var ExperimentTable = dataset.ExperimentTable;
var StatusLabel = statuslabel.StatusLabel;

var Lot = module.exports.Lot = React.createClass({
    render: function() {
        var context = this.props.context;

        // Sort characterization arrays
        var sortedChars = _(context.characterizations).sortBy(function(characterization) {
            return [characterization.target.label, characterization.target.organism.name];
        });

        // Build array of characterization panels
        var characterizations = sortedChars.map(function(item) {
            return globals.panel_views.lookup(item)({context: item, key: item['@id']});
        });

        // Build antibody status panel
        var antibodyStatuses = globals.panel_views.lookup(context)({context: context, key: context['@id']});

        // Make an array of targets with no falsy entries and no repeats
        var targets = {};
        if (context.lot_reviews && context.lot_reviews.length) {
            context.lot_reviews.forEach(function(lot_review) {
                lot_review.targets.forEach(function(target) {
                    targets[target['@id']] = target;
                });
            });
        }
        var targetKeys = Object.keys(targets);

        // Make string of alternate accessions
        var altacc = context.alternate_accessions ? context.alternate_accessions.join(', ') : undefined;

        // To search list of linked experiments
        var experiments_url = '/search/?type=experiment&replicates.antibody.accession=' + context.accession;

        return (

{context.accession}

                        {altacc ?
Replaces {altacc}
 : null}

                            {targetKeys.length ?
                                Antibody against {Object.keys(targets).map(function(target, i) {
                                    var targetObj = targets[target];
                                    return {i !== 0 ? ', ' : ''}{targetObj.organism.scientific_name}{' ' + targetObj.label};
                                })}
                            :
                                Antibody
                            }

                {context.lot_reviews && context.lot_reviews.length ?

                        {antibodyStatuses}

                :

                        <StatusLabel status="Awaiting lab characterization" />

                }

Source (vendor)

{context.source.title}

Product ID

{context.product_id}

Lot ID

{context.lot_id}

                        {Object.keys(targets).length ?

Targets

                                    {targetKeys.map(function(target, i) {
                                        var targetObj = targets[target];
                                        return {i !== 0 ? ', ' : ''}{targetObj.label}{' ('}{targetObj.organism.scientific_name}{')'};
                                    })}

                        : null}

                        {context.lot_id_alias && context.lot_id_alias.length ?

Lot ID aliases

{context.lot_id_alias.join(', ')}

                        : null}

Host

{context.host_organism.name}

                        {context.clonality ?

Clonality

{context.clonality}

                        : null}

                        {context.purifications && context.purifications.length ?

Purification

{context.purifications.join(', ')}

                        : null}

                        {context.isotype ?

Isotype

{context.isotype}

                        : null}

                        {context.antigen_description ?

Antigen description

{context.antigen_description}

                        : null}

                        {context.antigen_sequence ?

Antigen sequence

{context.antigen_sequence}

                        : null}

                        {context.aliases && context.aliases.length ?

Aliases

{context.aliases.join(", ")}

                        : null}

                        {context.dbxrefs && context.dbxrefs.length ?

External resources

<DbxrefList values={context.dbxrefs} />

                        : null}

                    {characterizations}

                {this.transferPropsTo(
                    <FetchedItems url={experiments_url} Component={ExperimentsUsingAntibody} />
                )}

        );
    }
});

globals.content_views.register(Lot, 'antibody_lot');

var ExperimentsUsingAntibody = React.createClass({
    render: function () {
        var context = this.props.context;

        return (

                    View all

Experiments using antibody {context.accession}

                    {this.transferPropsTo(
                        <ExperimentTable limit={5} total={this.props.total} />
                    )}

        );
    }
});

var StandardsDocuments = React.createClass({
    render: function() {
        return (

                {this.props.docs.map(function(doc, i) {
                    var attachmentHref = url.resolve(doc['@id'], doc.attachment.href);
                    return (

                                {doc.aliases[0]}

                    );
                })}

        );
    }
});

var Characterization = module.exports.Characterization = React.createClass({
    render: function() {
        var context = this.props.context;
        var figure = <Attachment context={this.props.context} className="characterization" />;

        var attachmentHref, download;
        if (context.attachment) {
            attachmentHref = url.resolve(context['@id'], context.attachment.href);
            download = (

                    {context.attachment.download}

            );
        } else {
            download = (
                Document not available
            );
        }

        // Compile a list of attached standards documents
        var standardsDocuments = [];
        if (context.documents) {
            standardsDocuments = context.documents.filter(function(doc) {
                return doc.document_type === "standards document";
            });
        }

        return (

{context.target.label} ({context.target.organism.scientific_name})

                            {figure}

                                {context.status}

                            {context.characterization_method ?

Method

{context.characterization_method}

                            : null}

Target species

{context.target.organism.scientific_name}

                            {context.caption ?

Caption

{context.caption}

                            : null}

                            {context.submitted_by && context.submitted_by.title ?

Submitted by

{context.submitted_by.title}

                            : null}

Lab

{context.lab.title}

Grant

{context.award.name}

Image

<StatusLabel status={context.status} />

                            {standardsDocuments.length ?

Standards documents

<StandardsDocuments docs={standardsDocuments} />

                            : null}

 Download

{download}

        );
    }
});

globals.panel_views.register(Characterization, 'antibody_characterization');

var AntibodyStatus = module.exports.AntibodyStatus = React.createClass({
    render: function() {
        var context = this.props.context;

        // Build antibody display object as a hierarchy: status=>organism=>biosample_term_name
        var statusTree = {};
        context.lot_reviews.forEach(function(lot_review) {
            // Status at top of hierarchy. If haven’t seen this status before, remember it
            if (!statusTree[lot_review.status]) {
                statusTree[lot_review.status] = {};
            }

            // Look at all organisms in current lot_review. They go under this lot_review's status
            var statusNode = statusTree[lot_review.status];
            lot_review.organisms.forEach(function(organism) {
                // If haven’t seen this organism with this status before, remember it
                if (!statusNode[organism.scientific_name]) {
                    statusNode[organism.scientific_name] = {};
                }

                // If haven't seen this biosample term name for this organism, remember it
                var organismNode = statusNode[organism.scientific_name];
                if (!organismNode[lot_review.biosample_term_name]) {
                    organismNode[lot_review.biosample_term_name] = true;
                }
            });
        });

        return (

                        {Object.keys(statusTree).map(function(status) {
                            var organisms = statusTree[status];
                            return (

                                    {Object.keys(organisms).map(function(organism, i) {
                                        var terms = Object.keys(organisms[organism]);
                                        return (

                                                    {i === 0 ? {status} : ''}

                                                    {organism}

                                                    {terms.length === 1 && terms[0] === 'not specified' ? '' : terms.join(', ')}

                                        );
                                    })}

                            );
                        })}

        );
    }
});

globals.panel_views.register(AntibodyStatus, 'antibody_lot');
<commit_msg>Add same fix to antibody characterizations<commit_after>/** @jsx React.DOM */
'use strict';
var React = require('react');
var url = require('url');
var _ = require('underscore');
var globals = require('./globals');
var dataset = require('./dataset');
var fetched = require('./fetched');
var dbxref = require('./dbxref');
var image = require('./image');
var statuslabel = require('./statuslabel');

var Attachment = image.Attachment;
var DbxrefList = dbxref.DbxrefList;
var FetchedItems = fetched.FetchedItems;
var ExperimentTable = dataset.ExperimentTable;
var StatusLabel = statuslabel.StatusLabel;

var Lot = module.exports.Lot = React.createClass({
    render: function() {
        var context = this.props.context;

        // Sort characterization arrays
        var sortedChars = _(context.characterizations).sortBy(function(characterization) {
            return [characterization.target.label, characterization.target.organism.name];
        });

        // Build array of characterization panels
        var characterizations = sortedChars.map(function(item) {
            return globals.panel_views.lookup(item)({context: item, key: item['@id']});
        });

        // Build antibody status panel
        var antibodyStatuses = globals.panel_views.lookup(context)({context: context, key: context['@id']});

        // Make an array of targets with no falsy entries and no repeats
        var targets = {};
        if (context.lot_reviews && context.lot_reviews.length) {
            context.lot_reviews.forEach(function(lot_review) {
                lot_review.targets.forEach(function(target) {
                    targets[target['@id']] = target;
                });
            });
        }
        var targetKeys = Object.keys(targets);

        // Make string of alternate accessions
        var altacc = context.alternate_accessions ? context.alternate_accessions.join(', ') : undefined;

        // To search list of linked experiments
        var experiments_url = '/search/?type=experiment&replicates.antibody.accession=' + context.accession;

        return (

{context.accession}

                        {altacc ?
Replaces {altacc}
 : null}

                            {targetKeys.length ?
                                Antibody against {Object.keys(targets).map(function(target, i) {
                                    var targetObj = targets[target];
                                    return {i !== 0 ? ', ' : ''}{targetObj.organism.scientific_name}{' ' + targetObj.label};
                                })}
                            :
                                Antibody
                            }

                {context.lot_reviews && context.lot_reviews.length ?

                        {antibodyStatuses}

                :

                        <StatusLabel status="Awaiting lab characterization" />

                }

Source (vendor)

{context.source.title}

Product ID

{context.product_id}

Lot ID

{context.lot_id}

                        {Object.keys(targets).length ?

Targets

                                    {targetKeys.map(function(target, i) {
                                        var targetObj = targets[target];
                                        return {i !== 0 ? ', ' : ''}{targetObj.label}{' ('}{targetObj.organism.scientific_name}{')'};
                                    })}

                        : null}

                        {context.lot_id_alias && context.lot_id_alias.length ?

Lot ID aliases

{context.lot_id_alias.join(', ')}

                        : null}

Host

{context.host_organism.name}

                        {context.clonality ?

Clonality

{context.clonality}

                        : null}

                        {context.purifications && context.purifications.length ?

Purification

{context.purifications.join(', ')}

                        : null}

                        {context.isotype ?

Isotype

{context.isotype}

                        : null}

                        {context.antigen_description ?

Antigen description

{context.antigen_description}

                        : null}

                        {context.antigen_sequence ?

Antigen sequence

{context.antigen_sequence}

                        : null}

                        {context.aliases && context.aliases.length ?

Aliases

{context.aliases.join(", ")}

                        : null}

                        {context.dbxrefs && context.dbxrefs.length ?

External resources

<DbxrefList values={context.dbxrefs} />

                        : null}

                    {characterizations}

                {this.transferPropsTo(
                    <FetchedItems url={experiments_url} Component={ExperimentsUsingAntibody} />
                )}

        );
    }
});

globals.content_views.register(Lot, 'antibody_lot');

var ExperimentsUsingAntibody = React.createClass({
    render: function () {
        var context = this.props.context;

        return (

                    View all

Experiments using antibody {context.accession}

                    {this.transferPropsTo(
                        <ExperimentTable limit={5} total={this.props.total} />
                    )}

        );
    }
});

var StandardsDocuments = React.createClass({
    render: function() {
        return (

                {this.props.docs.map(function(doc, i) {
                    var attachmentHref = url.resolve(doc['@id'], doc.attachment.href);
                    return (

                                {doc.aliases[0]}

                    );
                })}

        );
    }
});

var Characterization = module.exports.Characterization = React.createClass({
    render: function() {
        var context = this.props.context;
        var figure = <Attachment context={this.props.context} className="characterization" />;

        var attachmentHref, download;
        if (context.attachment && context.attachment.href && context.attachment.download) {
            attachmentHref = url.resolve(context['@id'], context.attachment.href);
            download = (

                    {context.attachment.download}

            );
        } else {
            download = (
                Document not available
            );
        }

        // Compile a list of attached standards documents
        var standardsDocuments = [];
        if (context.documents) {
            standardsDocuments = context.documents.filter(function(doc) {
                return doc.document_type === "standards document";
            });
        }

        return (

{context.target.label} ({context.target.organism.scientific_name})

                            {figure}

                                {context.status}

                            {context.characterization_method ?

Method

{context.characterization_method}

                            : null}

Target species

{context.target.organism.scientific_name}

                            {context.caption ?

Caption

{context.caption}

                            : null}

                            {context.submitted_by && context.submitted_by.title ?

Submitted by

{context.submitted_by.title}

                            : null}

Lab

{context.lab.title}

Grant

{context.award.name}

Image

<StatusLabel status={context.status} />

                            {standardsDocuments.length ?

Standards documents

<StandardsDocuments docs={standardsDocuments} />

                            : null}

 Download

{download}

        );
    }
});

globals.panel_views.register(Characterization, 'antibody_characterization');

var AntibodyStatus = module.exports.AntibodyStatus = React.createClass({
    render: function() {
        var context = this.props.context;

        // Build antibody display object as a hierarchy: status=>organism=>biosample_term_name
        var statusTree = {};
        context.lot_reviews.forEach(function(lot_review) {
            // Status at top of hierarchy. If haven’t seen this status before, remember it
            if (!statusTree[lot_review.status]) {
                statusTree[lot_review.status] = {};
            }

            // Look at all organisms in current lot_review. They go under this lot_review's status
            var statusNode = statusTree[lot_review.status];
            lot_review.organisms.forEach(function(organism) {
                // If haven’t seen this organism with this status before, remember it
                if (!statusNode[organism.scientific_name]) {
                    statusNode[organism.scientific_name] = {};
                }

                // If haven't seen this biosample term name for this organism, remember it
                var organismNode = statusNode[organism.scientific_name];
                if (!organismNode[lot_review.biosample_term_name]) {
                    organismNode[lot_review.biosample_term_name] = true;
                }
            });
        });

        return (

                        {Object.keys(statusTree).map(function(status) {
                            var organisms = statusTree[status];
                            return (

                                    {Object.keys(organisms).map(function(organism, i) {
                                        var terms = Object.keys(organisms[organism]);
                                        return (

                                                    {i === 0 ? {status} : ''}

                                                    {organism}

                                                    {terms.length === 1 && terms[0] === 'not specified' ? '' : terms.join(', ')}

                                        );
                                    })}

                            );
                        })}

        );
    }
});

globals.panel_views.register(AntibodyStatus, 'antibody_lot');
<|endoftext|>


<commit_before>(function ($, window, undefined) {

/**
 * @module Assets-tools
 */

/**
 * Implements an input field that send search string to Amazon Product store and retrieve top ten relevant products
 * @class Assets Amazon tool
 * @constructor
 * @param {Object} [options] options to pass to this tool, so far nothing
 * @return {Q.Tool}
 */

Handlebars.registerHelper("debug", function(optionalValue) {
  console.log("Current Context");
  console.log("====================");
  console.log(this);

  if (optionalValue) {
    console.log("Value");
    console.log("====================");
    console.log(optionalValue);
  }
});

Q.Tool.define("Assets/amazon/preview", "Streams/preview", function(options, preview) {

  if (!Q.Users.loggedInUser) {
      tool.element.style.display = 'none';
      console.warn("Assets/amazon: Don't render tool when user is not logged in");
      return;
  }

  var ps = preview.state;
  this.preview = preview;

  // proceed to construct the tool
  var tool = this;
  var state = tool.state;
  var $te = $(tool.element);

  // draw the tool
  ps.onRefresh.add(this.refresh.bind(this));

  $te.on(Q.Pointer.fastclick, '.Assets_amazon_results_item', tool, function () {

      var stream = tool.preview.stream;

      var asin = $(this).attr('data-asin');
      var title = $(this).attr('data-title');

      stream.fields.title = title;
      stream.set({'asin': asin, 'title': title});
      stream.save();

      console.log(stream);

      tool.filter = Q.Tool.from(tool.$('.Q_filter_tool'), 'Q/filter');
      tool.filter.input = tool.filter.$('.Q_filter_input');
      tool.filter.input.attr('value', '');
      tool.filter.input.next().show();
      tool.filter.end();
  }
  );

},

{ // DEFAULT OPTIONS
  onChoose: new Q.Event(),
  onSelect: new Q.Event(),
  onFilter: new Q.Event(),
  onCreate: new Q.Event(),
  onUpdate: new Q.Event(),
  onRefresh: new Q.Event()
},

{ // YOUR TOOL'S METHODS

  refresh: function (callback) {
    var tool = this;
    var state = tool.state;
    var $te = $(tool.element);

    var options = tool.options;
    var stream = tool.stream = options.stream = state.stream = tool.preview.stream;

    $items = tool.$('[data-assets-amazon], .Assets_amazon_preview_tool');

    Q.Template.render(
        'Assets/amazon/response/wishlist',
        $items,
        function (err, html) {

            if (err) {
                return;
            }

//            var options = {};

            var filterAmazon = Q.Tool.setUpElement(
                'div',
                'Q/filter',
                options,
                tool.prefix + 'filter'
            );

            var e = Q.Tool.setUpElement('div', "Streams/inplace", options);
            tool.element.appendChild(e);
            Q.activate(e);

            Q.replace(tool.element, null);

            $(filterAmazon)
                .appendTo($te)
                .activate(
                    function () {

                        var tool = this;
                        var state = tool.state;

                        state.onFilter.set(
                          function (query, element) {

                              var latest = Q.latest(tool);

                              Q.req("Assets/amazon", 'results',
                                function (err, response) {

                                  if (Q.latest(tool, latest)) {

                                    var msg = Q.firstErrorMessage(err, response && response.errors);
                                    if (msg) {
                                        return console.warn(msg);
                                    }

                                    var results = response.slots.results;
                                    var fields = {results: ''};
                                    if (results) {
                                        fields = {results: results};
                                    }

                                    Q.Template.render(
                                        'Assets/amazon/response/results',
                                        fields,
                                        function (err, html) {
                                            $(element).html(html);
                                        }
                                    );
                                  }
                                },
                                {
                                  fields: {
                                      input: query
                                  }
                              });

                          }, tool);
                });

            $te.append(html);
            }, options);
  },

  // optional methods for your tool
  // that would be called by Qbix
  Q: {
    onInit: function () {
      // occurs after onInit
      // of all child tools
    },
    beforeRemove: function () {
      // clean up anything you've attached
      // to the elements, such as
      // jQuery event handlers, data, etc.
    },
    onRetain: function (newOptions) {
      // compare newOptions to this.state
      // and update the tool's appearance.
      // after this event, the tool's
      // state will be extended with
      // the new options.
    },
    onLayout: function (elem, container) {
      // Occurs if the layout is being
      // updated for this tool's element.
      // If you want more fine-grained control
      // then use Q.onLayout(element) instead.
    }
  }
});

Q.Template.set('Assets/amazon/response/wishlist',
      ''
//    + '
{{debug options}}
'
//    + '{{&tool "Streams/inplace" publisherId=publisherId streamName=streamName inplaceType="text" inplace-placeholder="Name of the good" attribute="asin"}}'

//    + '{{&tool "Streams/inplace" inplaceType="text" inplace-placeholder="Name of the wish" attribute="title"}}
'
//    + '{{&tool "Streams/inplace" publisherId=publisherId streamName=streamName inplaceType="text" inplace-placeholder="Name of the good"}}'
//    + '
{{&tool "Streams/inplace" publisherId=publisherId streamName=streamName inplaceType="text" inplace-placeholder="Name of the good" field="asin"}}
'
);

Q.Template.set('Assets/amazon/response/results',
    '{{#if results}}'
    + '
'
    + '{{#each results}}'
    + '
'
    + ''
    + '
'
    + '
{{title}}
'
    + '{{price}}'
    + '
'
    + '
'
    + '
'
    + '{{/each}}'
    + '
'
    + '{{/if}}'
);

})(window.jQuery, window);<commit_msg>add options to function parameters and provisioning state.stream across tools<commit_after>(function ($, window, undefined) {

/**
 * @module Assets-tools
 */

/**
 * Implements an input field that send search string to Amazon Product store and retrieve top ten relevant products
 * @class Assets Amazon tool
 * @constructor
 * @param {Object} [options] options to pass to this tool, so far nothing
 * @return {Q.Tool}
 */

Handlebars.registerHelper("debug", function(optionalValue) {
  console.log("Current Context");
  console.log("====================");
  console.log(this);

  if (optionalValue) {
    console.log("Value");
    console.log("====================");
    console.log(optionalValue);
  }
});

Q.Tool.define("Assets/amazon/preview", "Streams/preview", function(options, preview) {

  if (!Q.Users.loggedInUser) {
      tool.element.style.display = 'none';
      console.warn("Assets/amazon: Don't render tool when user is not logged in");
      return;
  }

  var ps = preview.state;
  this.preview = preview;

  // proceed to construct the tool
  var tool = this;
  var state = tool.state;
  var $te = $(tool.element);

  // draw the tool
  ps.onRefresh.add(this.refresh.bind(this));

  $te.on(Q.Pointer.fastclick, '.Assets_amazon_results_item', tool, function () {

      var stream = tool.preview.stream;

      var asin = $(this).attr('data-asin');
      var title = $(this).attr('data-title');

      stream.fields.title = title;
      stream.set({'asin': asin, 'title': title});
      stream.save();

      console.log(stream);

      tool.filter = Q.Tool.from(tool.$('.Q_filter_tool'), 'Q/filter');
      tool.filter.input = tool.filter.$('.Q_filter_input');
      tool.filter.input.attr('value', '');
      tool.filter.input.next().show();
      tool.filter.end();
  });

},

{ // DEFAULT OPTIONS
  onChoose: new Q.Event(),
  onSelect: new Q.Event(),
  onFilter: new Q.Event(),
  onCreate: new Q.Event(),
  onUpdate: new Q.Event(),
  onRefresh: new Q.Event()
},

{ // YOUR TOOL'S METHODS

  refresh: function (callback) {
    var tool = this;
    tool.state = tool.preview.state;
    var state = tool.state;
    var $te = $(tool.element);

    var options = tool.options = tool.preview.options;

    $items = tool.$('[data-assets-amazon], .Assets_amazon_preview_tool');

    Q.Template.render(
        'Assets/amazon/response/wishlist',
        $items,
        function (err, html) {

            if (err) {
                return;
            }

            var filterAmazon = Q.Tool.setUpElement(
                'div',
                'Q/filter',
                options,
                tool.prefix + 'filter'
            );

            var e = Q.Tool.setUpElement(tool.element, "Streams/inplace", options);
            Q.activate(e, options);

            Q.replace(tool.element, null);

            $(filterAmazon)
                .appendTo($te)
                .activate(
                    function () {

                        var tool = this;
                        var state = tool.state;

                        state.onFilter.set(
                          function (query, element) {

                              var latest = Q.latest(tool);

                              Q.req("Assets/amazon", 'results',
                                function (err, response) {

                                  if (Q.latest(tool, latest)) {

                                    var msg = Q.firstErrorMessage(err, response && response.errors);
                                    if (msg) {
                                        return console.warn(msg);
                                    }

                                    var results = response.slots.results;
                                    var fields = {results: ''};
                                    if (results) {
                                        fields = {results: results};
                                    }

                                    Q.Template.render(
                                        'Assets/amazon/response/results',
                                        fields,
                                        function (err, html) {
                                            $(element).html(html);
                                        }
                                    );
                                  }
                                },
                                {
                                  fields: {
                                      input: query
                                  }
                              });

                          }, tool);
                }, options);

            $te.append(html);
            }, options);
  },

  // optional methods for your tool
  // that would be called by Qbix
  Q: {
    onInit: function () {
      // occurs after onInit
      // of all child tools
    },
    beforeRemove: function () {
      // clean up anything you've attached
      // to the elements, such as
      // jQuery event handlers, data, etc.
    },
    onRetain: function (newOptions) {
      // compare newOptions to this.state
      // and update the tool's appearance.
      // after this event, the tool's
      // state will be extended with
      // the new options.
    },
    onLayout: function (elem, container) {
      // Occurs if the layout is being
      // updated for this tool's element.
      // If you want more fine-grained control
      // then use Q.onLayout(element) instead.
    }
  }
});

Q.Template.set('Assets/amazon/response/wishlist',
      ''
//    + '
{{debug options}}
'
//    + '{{&tool "Streams/inplace" publisherId=publisherId streamName=streamName inplaceType="text" inplace-placeholder="Name of the good" attribute="asin"}}'

//    + '{{&tool "Streams/inplace" inplaceType="text" inplace-placeholder="Name of the wish" attribute="title"}}
'
//    + '{{&tool "Streams/inplace" publisherId=publisherId streamName=streamName inplaceType="text" inplace-placeholder="Name of the good"}}'
//    + '
{{&tool "Streams/inplace" publisherId=publisherId streamName=streamName inplaceType="text" inplace-placeholder="Name of the good" field="asin"}}
'
);

Q.Template.set('Assets/amazon/response/results',
    '{{#if results}}'
    + '
'
    + '{{#each results}}'
    + '
'
    + ''
    + '
'
    + '
{{title}}
'
    + '{{price}}'
    + '
'
    + '
'
    + '
'
    + '{{/each}}'
    + '
'
    + '{{/if}}'
);

})(window.jQuery, window);<|endoftext|>


<commit_before>(function ($, window, undefined) {

/**
 * @module Assets-tools
 */

/**
 * Implements an input field that send search string to Amazon Product store and retrieve top ten relevant products
 * @class Assets Amazon tool
 * @constructor
 * @param {Object} [options] options to pass to this tool, so far nothing
 * @return {Q.Tool}
 */

Q.Tool.define("Assets/amazon/preview", "Streams/preview", function(options) {

  if (!Q.Users.loggedInUser) {
      tool.element.style.display = 'none';
      console.warn("Assets/amazon: Don't render tool when user is not logged in");
      return;
  }

  // proceed to construct the tool
  var tool = this;
  var state = tool.state;
  var $te = $(tool.element);

  // draw the tool
  tool.refresh();

  $te.on(Q.Pointer.fastclick, '.Assets_amazon_results_item', tool, function () {

      var asin = $(this).attr('data-asin');

      fields = {
        'publisherId': Q.Users.loggedInUserId(),
        'type': "Assets/amazon",
        'name': "Assets/amazon/" + Q.Users.loggedInUserId() + "/" + asin,
        'attributes': {
          'asin': asin
        }
      };

      Q.Streams.create(fields, function () {
        console.log('item with id ' + asin + ' saved');
      });

      tool.filter = Q.Tool.from(tool.$('.Q_filter_tool'), 'Q/filter');
      return tool.filter.end();
  });
},

{ // DEFAULT OPTIONS

  publisherId: null,
  streamName: null,

  onChoose: new Q.Event(),
  onSelect: new Q.Event(),
  onFilter: new Q.Event(),
  onCreate: new Q.Event(),
  onUpdate: new Q.Event(),
  onRefresh: new Q.Event(),
  templates: {
    view: {
      name: 'Assets/amazon/preview/view',
      fields: { alt: 'icon', titleClass: '', titleTag: 'h2' }
    },
    edit: {
      name: 'Assets/amazon/preview/edit',
      fields: { alt: 'icon', titleClass: '', titleTag: 'h2' }
    },
    create: {
      name: 'Assets/amazon/preview/edit',
      fields: { alt: 'icon', titleClass: '', titleTag: 'h2' }
    }
  }
},

{ // YOUR TOOL'S METHODS

  refresh: function (callback) {
    var tool = this;
    var state = tool.state;
    var $te = $(tool.element);

    $items = tool.$('[data-assets-amazon], .Assets_amazon_tool');

    Q.Template.render(
        'Assets/amazon/response/wishlist',
        $items,
        function (err, html) {

            if (err) {
                return;
            }

            var options = {};

            var filterAmazon = Q.Tool.setUpElement(
                'div',
                'Q/filter',
                options,
                tool.prefix + 'filter'
            );

            tool.$(filterAmazon)
                .appendTo($te)
                .activate(
                    function () {

                        var tool = this;
                        var state = tool.state;

                        state.onFilter.set(
                          function (query, element) {

                              var latest = Q.latest(tool);

                              Q.req("Assets/amazon", 'results',
                                function (err, response) {

                                  if (Q.latest(tool, latest)) {

                                    var msg = Q.firstErrorMessage(err, response && response.errors);
                                    if (msg) {
                                        return console.warn(msg);
                                    }

                                    var results = response.slots.results;
                                    var fields = {results: ''};
                                    if (results) {
                                        fields = {results: results};
                                    }

                                    Q.Template.render(
                                        'Assets/amazon/response/results',
                                        fields,
                                        function (err, html) {
                                            $(element).html(html);
                                        }
                                    );
                                  }
                                },
                                {
                                  fields: {
                                      input: query
                                  }
                              });

                          }, tool);
                });

            $te.append(html);
            });
  },

  // optional methods for your tool
  // that would be called by Qbix
  Q: {
    onInit: function () {
      // occurs after onInit
      // of all child tools
    },
    beforeRemove: function () {
      // clean up anything you've attached
      // to the elements, such as
      // jQuery event handlers, data, etc.
    },
    onRetain: function (newOptions) {
      // compare newOptions to this.state
      // and update the tool's appearance.
      // after this event, the tool's
      // state will be extended with
      // the new options.
    },
    onLayout: function (elem, container) {
      // Occurs if the layout is being
      // updated for this tool's element.
      // If you want more fine-grained control
      // then use Q.onLayout(element) instead.
    }
  }
});

Q.Template.set('Assets/amazon/response/wishlist',
    '
'
    + '
'
    + '
Price:'
    + '
'
);

Q.Template.set('Assets/amazon/response/results',
    '{{#if results}}'
    + '
'
    + '{{#each results}}'
    + '
'
    + ''
    + '
'
    + '
{{title}}
'
    + '{{price}}'
    + '
'
    + '
'
    + '
'
    + '{{/each}}'
    + '
'
    + '{{/if}}'
);

Q.Template.set('Assets/amazon/composer',
  '<button class="Q_button">Wish something new</button>'
);

Q.Template.set('Assets/amazon/preview/view',
  '
'
  + ''
  + '
'
  + '{{#if showTitle}}'
  + '<{{titleTag}} class="Streams_preview_title">{{title}}</{{titleTag}}>'
  + '{{/if}}'
  + '

'
);

Q.Template.set('Assets/amazon/preview/edit',
  '
'
  + ''
  + '
'
  + '{{#if showTitle}}'
  + '<{{titleTag}} class="Streams_preview_title">{{& inplace}}</{{titleTag}}>'
  + '{{/if}}'
  + '

'
);

Q.Template.set('Assets/amazon/preview/create',
  '
'
  + ''
  + '
'
  + '<{{titleTag}} class="Streams_preview_title">{{title}}</{{titleTag}}>'
  + '

'
);

})(window.jQuery, window);<commit_msg>tweak Assets/amazon/preview template to render input Q/filter field<commit_after>(function ($, window, undefined) {

/**
 * @module Assets-tools
 */

/**
 * Implements an input field that send search string to Amazon Product store and retrieve top ten relevant products
 * @class Assets Amazon tool
 * @constructor
 * @param {Object} [options] options to pass to this tool, so far nothing
 * @return {Q.Tool}
 */

Q.Tool.define("Assets/amazon/preview", "Streams/preview", function(options, preview) {

  if (!Q.Users.loggedInUser) {
      tool.element.style.display = 'none';
      console.warn("Assets/amazon: Don't render tool when user is not logged in");
      return;
  }

  var ps = preview.state;
  this.preview = preview;

  // proceed to construct the tool
  var tool = this;
  var state = tool.state;
  var $te = $(tool.element);

  // draw the tool
  ps.onRefresh.add(this.refresh.bind(this));
//  tool.refresh();

  $te.on(Q.Pointer.fastclick, '.Assets_amazon_results_item', tool, function () {

      var asin = $(this).attr('data-asin');

      fields = {
        'publisherId': Q.Users.loggedInUserId(),
        'type': "Assets/amazon",
        'name': "Assets/amazon/" + Q.Users.loggedInUserId() + "/" + asin,
        'attributes': {
          'asin': asin
        }
      };

      tool.filter = Q.Tool.from(tool.$('.Q_filter_tool'), 'Q/filter');
      return tool.filter.end();
  });
},

{ // DEFAULT OPTIONS
  onChoose: new Q.Event(),
  onSelect: new Q.Event(),
  onFilter: new Q.Event(),
  onCreate: new Q.Event(),
  onUpdate: new Q.Event(),
  onRefresh: new Q.Event()
},

{ // YOUR TOOL'S METHODS

  refresh: function (callback) {
    var tool = this;
    var state = tool.state;
    var $te = $(tool.element);

    $items = tool.$('[data-assets-amazon], .Assets_amazon_tool');

    Q.Template.render(
        'Assets/amazon/response/wishlist',
        $items,
        function (err, html) {

            if (err) {
                return;
            }

            var options = {};

            var filterAmazon = Q.Tool.setUpElement(
                'div',
                'Q/filter',
                options,
                tool.prefix + 'filter'
            );

            tool.$(filterAmazon)
                .appendTo($te)
                .activate(
                    function () {

                        var tool = this;
                        var state = tool.state;

                        state.onFilter.set(
                          function (query, element) {

                              var latest = Q.latest(tool);

                              Q.req("Assets/amazon", 'results',
                                function (err, response) {

                                  if (Q.latest(tool, latest)) {

                                    var msg = Q.firstErrorMessage(err, response && response.errors);
                                    if (msg) {
                                        return console.warn(msg);
                                    }

                                    var results = response.slots.results;
                                    var fields = {results: ''};
                                    if (results) {
                                        fields = {results: results};
                                    }

                                    Q.Template.render(
                                        'Assets/amazon/response/results',
                                        fields,
                                        function (err, html) {
                                            $(element).html(html);
                                        }
                                    );
                                  }
                                },
                                {
                                  fields: {
                                      input: query
                                  }
                              });

                          }, tool);
                });

            $te.append(html);
            });
  },

  // optional methods for your tool
  // that would be called by Qbix
  Q: {
    onInit: function () {
      // occurs after onInit
      // of all child tools
    },
    beforeRemove: function () {
      // clean up anything you've attached
      // to the elements, such as
      // jQuery event handlers, data, etc.
    },
    onRetain: function (newOptions) {
      // compare newOptions to this.state
      // and update the tool's appearance.
      // after this event, the tool's
      // state will be extended with
      // the new options.
    },
    onLayout: function (elem, container) {
      // Occurs if the layout is being
      // updated for this tool's element.
      // If you want more fine-grained control
      // then use Q.onLayout(element) instead.
    }
  }
});

Q.Template.set('Assets/amazon/response/wishlist',
    '
'
    + '
'
    + '
Price:'
    + '
'
);

Q.Template.set('Assets/amazon/response/results',
    '{{#if results}}'
    + '
'
    + '{{#each results}}'
    + '
'
    + ''
    + '
'
    + '
{{title}}
'
    + '{{price}}'
    + '
'
    + '
'
    + '
'
    + '{{/each}}'
    + '
'
    + '{{/if}}'
);

Q.Template.set('Assets/amazon/composer',
  '<button class="Q_button">Wish something new</button>'
);

Q.Template.set('Assets/amazon/preview/view',
  '
'
  + ''
  + '
'
  + '{{#if showTitle}}'
  + '<{{titleTag}} class="Streams_preview_title">{{title}}</{{titleTag}}>'
  + '{{/if}}'
  + '

'
);

Q.Template.set('Assets/amazon/preview/edit',
  '
'
  + ''
  + '
'
  + '{{#if showTitle}}'
  + '<{{titleTag}} class="Streams_preview_title">{{& inplace}}</{{titleTag}}>'
  + '{{/if}}'
  + '

'
);

Q.Template.set('Assets/amazon/preview/create',
  '
'
  + ''
  + '
'
  + '<{{titleTag}} class="Streams_preview_title">{{title}}</{{titleTag}}>'
  + '

'
);

})(window.jQuery, window);<|endoftext|>


<commit_before>/**
 * Module Dependencies
 */

var _ = require('lodash');

/**
 * Processes data returned from a SQL query.
 */

var Processor = module.exports = function Processor(schema) {
  this.schema = _.cloneDeep(schema);
  return this;
};

/**
 * Cast special values to proper types.
 *
 * Ex: Array is stored as "[0,1,2,3]" and should be cast to proper
 * array for return values.
 */

Processor.prototype.cast = function(table, values) {

  var self = this;
  var _values = _.cloneDeep(values);

  Object.keys(values).forEach(function(key) {
    self.castValue(table, key, _values[key], _values);
  });

  return _values;
};

/**
 * Cast a value
 *
 * @param {String} key
 * @param {Object|String|Integer|Array} value
 * @param {Object} schema
 * @api private
 */

 Processor.prototype.castValue = function(table, key, value, attributes) {

  var self = this;
  var identity = table;
  var attr;

  // Check for a columnName, serialize so we can do any casting
  Object.keys(this.schema[identity].attributes).forEach(function(attribute) {
    if(self.schema[identity].attributes[attribute].columnName === key) {
      attr = attribute;
      return;
    }
  });

  if(!attr) {
    attr = key;
  }

  // Lookup Schema "Type"
  if(!this.schema[identity] || !this.schema[identity].attributes[attr]) {
    return;
  }

  var type;

  if(!_.isPlainObject(this.schema[identity].attributes[attr])) {
    type = this.schema[identity].attributes[attr];
  } else {
    type = this.schema[identity].attributes[attr].type;
  }

  if(!type) {
    return;
  }

  // Attempt to parse Array
  if(type === 'array') {
    try {
      attributes[key] = JSON.parse(value);
    } catch(e) {
      return;
    }
  }

};
<commit_msg>refactor and just grab the type<commit_after>/**
 * Module Dependencies
 */

var _ = require('lodash');

/**
 * Processes data returned from a SQL query.
 */

var Processor = module.exports = function Processor(schema) {
  this.schema = _.cloneDeep(schema);
  return this;
};

/**
 * Cast special values to proper types.
 *
 * Ex: Array is stored as "[0,1,2,3]" and should be cast to proper
 * array for return values.
 */

Processor.prototype.cast = function(table, values) {

  var self = this;
  var _values = _.cloneDeep(values);

  Object.keys(values).forEach(function(key) {
    self.castValue(table, key, _values[key], _values);
  });

  return _values;
};

/**
 * Cast a value
 *
 * @param {String} key
 * @param {Object|String|Integer|Array} value
 * @param {Object} schema
 * @api private
 */

 Processor.prototype.castValue = function(table, key, value, attributes) {

  var attr = this.schema[table] && this.schema[table].definition && this.schema[table].definition[key];
  if(!attr) {
    return;
  }

  var type = attr.type;

  // Attempt to parse Array
  if(type === 'array') {
    try {
      attributes[key] = JSON.parse(value);
    } catch(e) {
      return;
    }
  }

};
<|endoftext|>