<commit_before>/*
* Extended Grid
* Ability to reorder the grid's row
* @author: Prakash Paudel
*/
Ext.namespace('Ext.ux.plugins');

Ext.ux.plugins.GridRowOrder = function(config){
	Ext.apply(this,config);
}
Ext.extend(Ext.ux.plugins.GridRowOrder, Ext.util.Observable,{
	init: function(grid){
		Ext.apply(grid,{

		});
	}
});

/***
 *
 * This is the custom plugin created for the event correlation triggers wizard
 *
 * @author Prakash Paudel *
 */

//Create a constructor for the plugin
Ext.ux.plugins.IntegrityPolicyTriggers = function(config){
	Ext.apply(this,config,{

	});
}

//Extend the plugin to Ext.util.Observable
Ext.extend(Ext.ux.plugins.IntegrityPolicyTriggers, Ext.util.Observable,{
	init: function(grid){
		Ext.apply(grid,{
			/**
			 * Find all ajax request from the module
			 *
			 */
			actionsModule:'fileinspect',

			/**
			 *  Grid row reorder plugin, if includes row up button
			 */
			rowUp:false,

			/**
			 *  Grid row reorder plugin, if includes row down button
			 */
            rowDown:false,

            /**
			 *  Grid row reorder plugin, if includes row remove button
			 */
            rowRemove: true,

            /**
			 *  Grid row reorder plugin, if includes row edit button
			 */
            rowEdit: true,

            /**
			 *  Grid row reorder plugin, the header of the row reorder column
			 */
            colHeader:'',

            /**
             *  Preserve order state
             */
            preserveOrder:true,

            // Customize the grid on render
			onRender: grid.onRender.createSequence(function(ct, position) {
				var actionsModule = this.actionModule;
				/**
				 * Create a temporary record object
				 */
				// create a Record constructor from a description of the fields
        		var triggerAttr = Ext.data.Record.create([ // creates a subclass of Ext.data.Record
        		    {name: 'location'},
        		    {name: 'action'},
        		    {name: 'is_included'}
        		]);

				/**
				 * Create a form to add new triggers to the gird
				 */
                Ext.QuickTips.init(true);
                //Form panel
                var actionCombo = new Ext.ux.form.LovCombo({
    		    	name:'action',

    		    	/*tpl:new Ext.XTemplate(
    		    		'<tpl for=".">',
    		    			'<tpl if="flag == \'parent\'">
{value}
</tpl>',
    		    			'<tpl if="flag == \'child\'">
{value}
</tpl>',
    		    		'</tpl>'
				    ),*/
				    resizable:true,
				    editable:false,
        		    typeAhead: true,
        		    fieldLabel:'Action',
        		    triggerAction: 'all',
        		    lazyRender:true,
        		    mode: 'local',
        		    store: new Ext.data.JsonStore({
        		        url:'/fileinspect/getIntegrityPolicyFormData?action',
        		        root:'data',
        		        autoLoad:true,
        		        fields: [
        		            'key',
        		            'value'
        		        ]
        		    }),
        		    valueField: 'key',
        		    displayField: 'value',
        		    allowBlank:false
                });
                var form = new Ext.form.FormPanel({
                	bodyStyle:'padding:5px',
                	isEdit: false,
                	record:null,
                	rowIndex:null,
                	items:[{
                		xtype: 'fieldset',
                		title:'Add Location',
                		defaultType: 'textfield',
                		autoHeight:true,
                		defaults:{width:200,msgTarget:'title'},
                		items:[{
                			name:'location',
                    		xtype:'textfield',
                    		fieldLabel:'Location'
                		},
                		    actionCombo,
                		{
                    		name:'is_included',
                    		xtype:'checkbox',
                    		fieldLabel:'Is included?'
                    	}]
                	}],
                	buttons:[{
                		text:'Save',
                		handler: function(){
                			if(form.getForm().isValid()){

		                		var newTrigger = new triggerAttr({
		                		        location: form.getForm().findField('location').getValue(),
		                		        action:""+form.getForm().findField('action').getValue()+""+form.getForm().findField('action').getEl().dom.value,
		                		        is_included: form.getForm().findField('is_included').getValue()
		                		});

		                		// Add the data from the form to the grid's store
		                		// This will add the record at the end of the grid
		                		if(form.isEdit){
		                			grid.getStore().remove(form.record);
		                			grid.getStore().insert(form.rowIndex,newTrigger);
		                			grid.getStore().commitChanges();
		                		}else{
			                		grid.getStore().insert(grid.getStore().getCount(),newTrigger);
			                		grid.getStore().commitChanges();
		                		}
		                		form.getForm().reset();
		                		win.hide();
                			}
                		}
                	}]

                })

                //Window for the popup add trigger form
                var win = new Ext.Window({
                	layout:'form',
                	autoWidth:true,
                	autoHeight:true,
                	closeAction:'hide',
                	items: form
                })

                // Get the toolbar of the grid
                var tb = grid.getTopToolbar();

                // Add a new button to add triggers to the toolbar
                tb.addButton({
                	text:'Add Location',
                	tooltip:'Add new location to the policy',
                	iconCls:'icon-plus',
                	handler: function(){
	                	form.isEdit=false;
	                    form.rowIndex = null;
                		win.show();
                		win.center();
                	}
                })

                // Add a tool separator to the toolbar
                tb.addSeparator();

                // Add a new button to reset the grid's data to the toolbar
                tb.addButton({
                	text:'Reset',
                	tooltip:'Reset the list to original triggers',
                	iconCls:'icon-default',
                	handler: function(){

	                	Ext.Ajax.request({
	                		url:'/fileinspect/storeLocation?reset',
	                		method:"POST",
	                		success: function(){
		                		grid.getStore().reload(Ext.apply(grid.getStore().lastOptions.params,{
		                			fresh:true
		                		}));
	                		},
	                		failure: function(){
	                			mask.hide();
	                			Ext.Msg.alert('Error','Connection to server has been lost
Please try again!')
	                		}
	                	})

                	}
                })

               /* // Add a tool separator to the toolbar
                tb.addSeparator();

                // Add a checkbox for preserving the grid's row order to the toolbar
                tb.addField(new Ext.form.Checkbox({
                	boxLabel:'Preserve order',
                	name:'preserve-row-order'
                }))*/

                // Get the column model of the gird and add a new column at the end
                // for the new grid's row reorder plugin
                var cm = grid.getColumnModel();
                var columns = cm.getColumnsBy(function(c){return true});
                columns.push({
                	header:this.colHeader,
                    menuDisabled:true,
                    dataIndex:null,
                    renderer:function(value,metadata,record,rowIndex,colIndex,store){
                		var r = '
';
                		if(grid.rowUp) r+='';
                		if(grid.rowDown) r+='';
                		if(grid.rowEdit) r+='';
                		if(grid.rowRemove) r+='';
                		r+='
';
                		return r;
                    },
                    toolTip:"Re-order the rows",
                    width: (this.rowUp?30:0)+(this.rowDown?30:0)+(this.rowEdit?30:0)+(this.rowRemove?30:0)
                });
                /* Alternative for reconfigure *****************/
                grid.view.refresh(true)
                grid.view.initData(grid.getStore(), new Ext.grid.ColumnModel(columns));
                grid.store = grid.getStore();
                grid.colModel = new Ext.grid.ColumnModel(columns);
                if(grid.rendered){
                	grid.view.refresh(true);
                }
                /***********************************************/

                // Add cell click event to the grid to catch the row reorder requests..
                grid.on('cellclick',function(grid,rowIndex,columnIndex,e){
                    var target = e.getTarget();

                    // If clicked row up button
                    if(target.className && target.className == 'row-re-order-up'){
                        var record = grid.getStore().getAt(rowIndex);
                        if(rowIndex>0){
                            grid.getStore().remove(record);
                            grid.getStore().insert(rowIndex-1,record);
                            var row = grid.getView().getRow(rowIndex-1);
                            Ext.get(row).syncFx();
                            Ext.get(row).slideIn('b',{
                                easing: 'easeOut',
                                duration: .5,
                                remove: false,
                                useDisplay: false,
                                callback: function(){

                                }
                            });
                            Ext.get(row).highlight("dfe8f6", {
                                attr: "background-color",
                                easing: 'easeIn',
                                duration: 1
                            });
                        }
                    }

                    // If clicked row down button
                    if(target.className && target.className == 'row-re-order-down'){
                        var record = grid.getStore().getAt(rowIndex);
                        if(rowIndex < grid.getStore().getCount()-1){
                            grid.getStore().remove(record);
                            grid.getStore().insert(rowIndex+1,record);
                            var row = grid.getView().getRow(rowIndex+1);
                            Ext.get(row).syncFx();
                            Ext.get(row).slideIn('t', {
                                easing: 'easeOut',
                                duration: .5,
                                remove: false,
                                useDisplay: false,
                                callback: function(){

                                }
                            });
                            Ext.get(row).highlight("dfe8f6", {
                                attr: "background-color",
                                easing: 'easeIn',
                                duration: 1
                            });

                        }
                    }

                    // If clicked row edit button
                    if(target.className && target.className == 'row-re-order-edit'){
                        var record = grid.getStore().getAt(rowIndex);
                        var location,action,is_included;
                        if(record.get('action') != ''){

                			var matches = record.get('action').toString().match(/]*>(.*)<\/span>/i);
                        	if(matches[1])
                        	action = matches[1];
                        }
                        var editTrigger = new triggerAttr({
            		        location: record.get('location'),
            		        action: action,
            		        is_included: record.get('is_included')
                        });

                        win.show();
                        win.center();
                        form.isEdit=true;
                        form.record = record;
                        form.rowIndex = rowIndex;
                        form.getForm().loadRecord(editTrigger);

                    }

                    // If clicked row remove button
                    if(target.className && target.className == 'row-re-order-remove'){
                        var record = grid.getStore().getAt(rowIndex);
                        var row = grid.getView().getRow(rowIndex);
                        Ext.get(row).syncFx();
                        Ext.get(row).fadeOut({
                            duration: .5,
                            callback: function(){
                                grid.getStore().remove(record);
                                grid.getStore().commitChanges();
                            }
                        });
                    }
                },this);
			})
		})
	}
})
<commit_msg>default checked is inclueded<commit_after>/*
* Extended Grid
* Ability to reorder the grid's row
* @author: Prakash Paudel
*/
Ext.namespace('Ext.ux.plugins');

Ext.ux.plugins.GridRowOrder = function(config){
	Ext.apply(this,config);
}
Ext.extend(Ext.ux.plugins.GridRowOrder, Ext.util.Observable,{
	init: function(grid){
		Ext.apply(grid,{

		});
	}
});

/***
 *
 * This is the custom plugin created for the event correlation triggers wizard
 *
 * @author Prakash Paudel *
 */

//Create a constructor for the plugin
Ext.ux.plugins.IntegrityPolicyTriggers = function(config){
	Ext.apply(this,config,{

	});
}

//Extend the plugin to Ext.util.Observable
Ext.extend(Ext.ux.plugins.IntegrityPolicyTriggers, Ext.util.Observable,{
	init: function(grid){
		Ext.apply(grid,{
			/**
			 * Find all ajax request from the module
			 *
			 */
			actionsModule:'fileinspect',

			/**
			 *  Grid row reorder plugin, if includes row up button
			 */
			rowUp:false,

			/**
			 *  Grid row reorder plugin, if includes row down button
			 */
            rowDown:false,

            /**
			 *  Grid row reorder plugin, if includes row remove button
			 */
            rowRemove: true,

            /**
			 *  Grid row reorder plugin, if includes row edit button
			 */
            rowEdit: true,

            /**
			 *  Grid row reorder plugin, the header of the row reorder column
			 */
            colHeader:'',

            /**
             *  Preserve order state
             */
            preserveOrder:true,

            // Customize the grid on render
			onRender: grid.onRender.createSequence(function(ct, position) {
				var actionsModule = this.actionModule;
				/**
				 * Create a temporary record object
				 */
				// create a Record constructor from a description of the fields
        		var triggerAttr = Ext.data.Record.create([ // creates a subclass of Ext.data.Record
        		    {name: 'location'},
        		    {name: 'action'},
        		    {name: 'is_included'}
        		]);

				/**
				 * Create a form to add new triggers to the gird
				 */
                Ext.QuickTips.init(true);
                //Form panel
                var actionCombo = new Ext.ux.form.LovCombo({
    		    	name:'action',

    		    	/*tpl:new Ext.XTemplate(
    		    		'<tpl for=".">',
    		    			'<tpl if="flag == \'parent\'">
{value}
</tpl>',
    		    			'<tpl if="flag == \'child\'">
{value}
</tpl>',
    		    		'</tpl>'
				    ),*/
				    resizable:true,
				    editable:false,
        		    typeAhead: true,
        		    fieldLabel:'Action',
        		    triggerAction: 'all',
        		    lazyRender:true,
        		    mode: 'local',
        		    store: new Ext.data.JsonStore({
        		        url:'/fileinspect/getIntegrityPolicyFormData?action',
        		        root:'data',
        		        autoLoad:true,
        		        fields: [
        		            'key',
        		            'value'
        		        ]
        		    }),
        		    valueField: 'key',
        		    displayField: 'value',
        		    allowBlank:false
                });
                var form = new Ext.form.FormPanel({
                	bodyStyle:'padding:5px',
                	isEdit: false,
                	record:null,
                	rowIndex:null,
                	items:[{
                		xtype: 'fieldset',
                		title:'Add Location',
                		defaultType: 'textfield',
                		autoHeight:true,
                		defaults:{width:200,msgTarget:'title'},
                		items:[{
                			name:'location',
                    		xtype:'textfield',
                    		fieldLabel:'Location'
                		},
                		    actionCombo,
                		{
                    		name:'is_included',
                    		xtype:'checkbox',
                    		fieldLabel:'Is included?',
                    		checked:true
                    	}]
                	}],
                	buttons:[{
                		text:'Save',
                		handler: function(){
                			if(form.getForm().isValid()){

		                		var newTrigger = new triggerAttr({
		                		        location: form.getForm().findField('location').getValue(),
		                		        action:""+form.getForm().findField('action').getValue()+""+form.getForm().findField('action').getEl().dom.value,
		                		        is_included: form.getForm().findField('is_included').getValue()
		                		});

		                		// Add the data from the form to the grid's store
		                		// This will add the record at the end of the grid
		                		if(form.isEdit){
		                			grid.getStore().remove(form.record);
		                			grid.getStore().insert(form.rowIndex,newTrigger);
		                			grid.getStore().commitChanges();
		                		}else{
			                		grid.getStore().insert(grid.getStore().getCount(),newTrigger);
			                		grid.getStore().commitChanges();
		                		}
		                		form.getForm().reset();
		                		win.hide();
                			}
                		}
                	}]

                })

                //Window for the popup add trigger form
                var win = new Ext.Window({
                	layout:'form',
                	autoWidth:true,
                	autoHeight:true,
                	closeAction:'hide',
                	items: form
                })

                // Get the toolbar of the grid
                var tb = grid.getTopToolbar();

                // Add a new button to add triggers to the toolbar
                tb.addButton({
                	text:'Add Location',
                	tooltip:'Add new location to the policy',
                	iconCls:'icon-plus',
                	handler: function(){
	                	form.isEdit=false;
	                    form.rowIndex = null;
                		win.show();
                		win.center();
                	}
                })

                // Add a tool separator to the toolbar
                tb.addSeparator();

                // Add a new button to reset the grid's data to the toolbar
                tb.addButton({
                	text:'Reset',
                	tooltip:'Reset the list to original triggers',
                	iconCls:'icon-default',
                	handler: function(){

	                	Ext.Ajax.request({
	                		url:'/fileinspect/storeLocation?reset',
	                		method:"POST",
	                		success: function(){
		                		grid.getStore().reload(Ext.apply(grid.getStore().lastOptions.params,{
		                			fresh:true
		                		}));
	                		},
	                		failure: function(){
	                			mask.hide();
	                			Ext.Msg.alert('Error','Connection to server has been lost
Please try again!')
	                		}
	                	})

                	}
                })

               /* // Add a tool separator to the toolbar
                tb.addSeparator();

                // Add a checkbox for preserving the grid's row order to the toolbar
                tb.addField(new Ext.form.Checkbox({
                	boxLabel:'Preserve order',
                	name:'preserve-row-order'
                }))*/

                // Get the column model of the gird and add a new column at the end
                // for the new grid's row reorder plugin
                var cm = grid.getColumnModel();
                var columns = cm.getColumnsBy(function(c){return true});
                columns.push({
                	header:this.colHeader,
                    menuDisabled:true,
                    dataIndex:null,
                    renderer:function(value,metadata,record,rowIndex,colIndex,store){
                		var r = '
';
                		if(grid.rowUp) r+='';
                		if(grid.rowDown) r+='';
                		if(grid.rowEdit) r+='';
                		if(grid.rowRemove) r+='';
                		r+='
';
                		return r;
                    },
                    toolTip:"Re-order the rows",
                    width: (this.rowUp?30:0)+(this.rowDown?30:0)+(this.rowEdit?30:0)+(this.rowRemove?30:0)
                });
                /* Alternative for reconfigure *****************/
                grid.view.refresh(true)
                grid.view.initData(grid.getStore(), new Ext.grid.ColumnModel(columns));
                grid.store = grid.getStore();
                grid.colModel = new Ext.grid.ColumnModel(columns);
                if(grid.rendered){
                	grid.view.refresh(true);
                }
                /***********************************************/

                // Add cell click event to the grid to catch the row reorder requests..
                grid.on('cellclick',function(grid,rowIndex,columnIndex,e){
                    var target = e.getTarget();

                    // If clicked row up button
                    if(target.className && target.className == 'row-re-order-up'){
                        var record = grid.getStore().getAt(rowIndex);
                        if(rowIndex>0){
                            grid.getStore().remove(record);
                            grid.getStore().insert(rowIndex-1,record);
                            var row = grid.getView().getRow(rowIndex-1);
                            Ext.get(row).syncFx();
                            Ext.get(row).slideIn('b',{
                                easing: 'easeOut',
                                duration: .5,
                                remove: false,
                                useDisplay: false,
                                callback: function(){

                                }
                            });
                            Ext.get(row).highlight("dfe8f6", {
                                attr: "background-color",
                                easing: 'easeIn',
                                duration: 1
                            });
                        }
                    }

                    // If clicked row down button
                    if(target.className && target.className == 'row-re-order-down'){
                        var record = grid.getStore().getAt(rowIndex);
                        if(rowIndex < grid.getStore().getCount()-1){
                            grid.getStore().remove(record);
                            grid.getStore().insert(rowIndex+1,record);
                            var row = grid.getView().getRow(rowIndex+1);
                            Ext.get(row).syncFx();
                            Ext.get(row).slideIn('t', {
                                easing: 'easeOut',
                                duration: .5,
                                remove: false,
                                useDisplay: false,
                                callback: function(){

                                }
                            });
                            Ext.get(row).highlight("dfe8f6", {
                                attr: "background-color",
                                easing: 'easeIn',
                                duration: 1
                            });

                        }
                    }

                    // If clicked row edit button
                    if(target.className && target.className == 'row-re-order-edit'){
                        var record = grid.getStore().getAt(rowIndex);
                        var location,action,is_included;
                        if(record.get('action') != ''){

                			var matches = record.get('action').toString().match(/]*>(.*)<\/span>/i);
                        	if(matches[1])
                        	action = matches[1];
                        }
                        var editTrigger = new triggerAttr({
            		        location: record.get('location'),
            		        action: action,
            		        is_included: record.get('is_included')
                        });

                        win.show();
                        win.center();
                        form.isEdit=true;
                        form.record = record;
                        form.rowIndex = rowIndex;
                        form.getForm().loadRecord(editTrigger);

                    }

                    // If clicked row remove button
                    if(target.className && target.className == 'row-re-order-remove'){
                        var record = grid.getStore().getAt(rowIndex);
                        var row = grid.getView().getRow(rowIndex);
                        Ext.get(row).syncFx();
                        Ext.get(row).fadeOut({
                            duration: .5,
                            callback: function(){
                                grid.getStore().remove(record);
                                grid.getStore().commitChanges();
                            }
                        });
                    }
                },this);
			})
		})
	}
})
<|endoftext|>


<commit_before>module.exports = {

	//---------------------------------------------------------------------
	// Action Name
	//
	// This is the name of the action displayed in the editor.
	//---------------------------------------------------------------------

	name: "Sends Stats to DBL",

	//---------------------------------------------------------------------
	// Action Section
	//
	// This is the section the action will fall into.
	//---------------------------------------------------------------------

	section: "Other Stuff",

	//---------------------------------------------------------------------
	// Action Subtitle
	//
	// This function generates the subtitle displayed next to the name.
	//---------------------------------------------------------------------

	subtitle: function (data) {
		const info = ['Only Server Count', 'Shard & Server Count'];
		return `Send ${info[parseInt(data.info)]} to DBL!`;
	},

	//---------------------------------------------------------------------
	// DBM Mods Manager Variables (Optional but nice to have!)
	//
	// These are variables that DBM Mods Manager uses to show information
	// about the mods for people to see in the list.
	//---------------------------------------------------------------------

	// Who made the mod (If not set, defaults to "DBM Mods")
	author: "EGGSY",

	// The version of the mod (Defaults to 1.0.0)
	version: "1.8.9",

	// A short description to show on the mod line for this mod (Must be on a single line)
	short_description: "Send bot stats to Discord Bot List!",

	// If it depends on any other mods by name, ex: WrexMODS if the mod uses something from WrexMods

	//---------------------------------------------------------------------
	// Action Storage Function
	//
	// Stores the relevant variable info for the editor.
	//---------------------------------------------------------------------

	// NOTHING HERE, K, PLS LEAVE NOW.

	//---------------------------------------------------------------------
	// Action Fields
	//
	// These are the fields for the action. These fields are customized
	// by creating elements with corresponding IDs in the HTML. These
	// are also the names of the fields stored in the action's JSON data.
	//---------------------------------------------------------------------

	fields: ["dblToken", "info"],

	//---------------------------------------------------------------------
	// Command HTML
	//
	// This function returns a string containing the HTML used for
	// editting actions.
	//
	// The "isEvent" parameter will be true if this action is being used
	// for an event. Due to their nature, events lack certain information,
	// so edit the HTML to reflect this.
	//
	// The "data" parameter stores constants for select elements to use.
	// Each is an array: index 0 for commands, index 1 for events.
	// The names are: sendTargets, members, roles, channels,
	//                messages, servers, variables
	//---------------------------------------------------------------------

	html: function (isEvent, data) {
		return `

	   Mod Info:

	   Made by EGGSY!

	   Your DBL Token:

	   <input id="dblToken" class="round" type="text">

	   Info to Send:

	   <select id="info" class="round">
		<option value="0">Send Only Server Count</option>
		<option value="1">Send Shard & Server Count</option>
	</select>

		• Using this mod with events will be better. I suggest using this with Bot Join & Bot Leave Server event.

		• Do not send anything about shards if you don't shard your bot!

`
	},

	//---------------------------------------------------------------------
	// Action Editor Init Code
	//
	// When the HTML is first applied to the action editor, this code
	// is also run. This helps add modifications or setup reactionary
	// functions for the DOM elements.
	//---------------------------------------------------------------------

	init: function () {
	},

	//---------------------------------------------------------------------
	// Action Bot Function
	//
	// This is the function for the action within the Bot's Action class.
	// Keep in mind event calls won't have access to the "msg" parameter,
	// so be sure to provide checks for variable existance.
	//---------------------------------------------------------------------

	action: function (cache) {

		const data = cache.actions[cache.index];
		const token = this.evalMessage(data.dblToken, cache);
		const info = parseInt(data.info);
		var client = this.getDBM().Bot.bot;

		const WrexMODS = this.getWrexMods(); // still, as always <3
		const DBL = WrexMODS.require('dblapi.js'); // what a great module!
		const dbl = new DBL(token);

		if (info == 0) {
			dbl.postStats(client.guilds.size)
				.then(console.log("Successfully updated DBL stats! Thank you EGGSY!"))
				.catch(e => console.log(e))
		}
		else if (info == 1) {
			dbl.postStats(client.guilds.size, client.shards.Id, client.shards.total)
				.then(console.log("Successfully updated DBL stats! Thank you EGGSY!"))
				.catch(e => console.log(e))
		}
	},

	//---------------------------------------------------------------------
	// Action Bot Mod
	//
	// Upon initialization of the bot, this code is run. Using the bot's
	// DBM namespace, one can add/modify existing functions if necessary.
	// In order to reduce conflictions between mods, be sure to alias
	// functions you wish to overwrite.
	//---------------------------------------------------------------------

	mod: function (DBM) {
	}

}; // End of module
<commit_msg>Evetything must be fixed now (Send Stats to DBL)<commit_after>module.exports = {

	//---------------------------------------------------------------------
	// Action Name
	//
	// This is the name of the action displayed in the editor.
	//---------------------------------------------------------------------

	name: "Sends Stats to DBL",

	//---------------------------------------------------------------------
	// Action Section
	//
	// This is the section the action will fall into.
	//---------------------------------------------------------------------

	section: "Other Stuff",

	//---------------------------------------------------------------------
	// Action Subtitle
	//
	// This function generates the subtitle displayed next to the name.
	//---------------------------------------------------------------------

	subtitle: function (data) {
		const info = ['Only Server Count', 'Shard & Server Count'];
		return `Send ${info[parseInt(data.info)]} to DBL!`;
	},

	//---------------------------------------------------------------------
	// DBM Mods Manager Variables (Optional but nice to have!)
	//
	// These are variables that DBM Mods Manager uses to show information
	// about the mods for people to see in the list.
	//---------------------------------------------------------------------

	// Who made the mod (If not set, defaults to "DBM Mods")
	author: "EGGSY",

	// The version of the mod (Defaults to 1.0.0)
	version: "1.8.9",

	// A short description to show on the mod line for this mod (Must be on a single line)
	short_description: "Send bot stats to Discord Bot List!",

	// If it depends on any other mods by name, ex: WrexMODS if the mod uses something from WrexMods

	//---------------------------------------------------------------------
	// Action Storage Function
	//
	// Stores the relevant variable info for the editor.
	//---------------------------------------------------------------------

	// NOTHING HERE, K, PLS LEAVE NOW.

	//---------------------------------------------------------------------
	// Action Fields
	//
	// These are the fields for the action. These fields are customized
	// by creating elements with corresponding IDs in the HTML. These
	// are also the names of the fields stored in the action's JSON data.
	//---------------------------------------------------------------------

	fields: ["dblToken", "info"],

	//---------------------------------------------------------------------
	// Command HTML
	//
	// This function returns a string containing the HTML used for
	// editting actions.
	//
	// The "isEvent" parameter will be true if this action is being used
	// for an event. Due to their nature, events lack certain information,
	// so edit the HTML to reflect this.
	//
	// The "data" parameter stores constants for select elements to use.
	// Each is an array: index 0 for commands, index 1 for events.
	// The names are: sendTargets, members, roles, channels,
	//                messages, servers, variables
	//---------------------------------------------------------------------

	html: function (isEvent, data) {
		return `

	   Mod Info:

	   Made by EGGSY!

	   Your DBL Token:

	   <input id="dblToken" class="round" type="text">

	   Info to Send:

	   <select id="info" class="round">
		<option value="0">Send Only Server Count</option>
		<option value="1">Send Shard & Server Count</option>
	</select>

		• Using this mod with events will be better. I suggest using this with Bot Join & Bot Leave Server event.

		• Do not send anything about shards if you don't shard your bot!

`
	},

	//---------------------------------------------------------------------
	// Action Editor Init Code
	//
	// When the HTML is first applied to the action editor, this code
	// is also run. This helps add modifications or setup reactionary
	// functions for the DOM elements.
	//---------------------------------------------------------------------

	init: function () {
	},

	//---------------------------------------------------------------------
	// Action Bot Function
	//
	// This is the function for the action within the Bot's Action class.
	// Keep in mind event calls won't have access to the "msg" parameter,
	// so be sure to provide checks for variable existance.
	//---------------------------------------------------------------------

	action: function (cache) {

		const data = cache.actions[cache.index];
		const token = this.evalMessage(data.dblToken, cache);
		const info = parseInt(data.info);
		// Commented due errors => var client = this.getDBM().Bot.bot;

		const WrexMODS = this.getWrexMods(); // still, as always <3
		const DBL = WrexMODS.require('dblapi.js'); // what a great module!
		const dbl = new DBL(token);

		if (info == 0) {
			dbl.postStats(this.getDBM().Bot.bot.guilds.size)
				.then(console.log("Successfully updated DBL stats! Thank you EGGSY!"))
				.catch(e => console.log(e))
		}
		else if (info == 1) {
			dbl.postStats(this.getDBM().Bot.bot.guilds.size, this.getDBM().Bot.bot.shard.id, this.getDBM().Bot.bot.shards.total)
				.then(console.log("Successfully updated DBL stats! Thank you EGGSY!"))
				.catch(e => console.log(e))
		}
	},

	//---------------------------------------------------------------------
	// Action Bot Mod
	//
	// Upon initialization of the bot, this code is run. Using the bot's
	// DBM namespace, one can add/modify existing functions if necessary.
	// In order to reduce conflictions between mods, be sure to alias
	// functions you wish to overwrite.
	//---------------------------------------------------------------------

	mod: function (DBM) {
	}

}; // End of module
<|endoftext|>


<commit_before>/**
 * OpenEyes
 *
 * (C) OpenEyes Foundation, 2017
 * This file is part of OpenEyes.
 * OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * OpenEyes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package OpenEyes
 * @link http://www.openeyes.org.uk
 * @author OpenEyes <info@openeyes.org.uk>
 * @copyright Copyright (c) 2017, OpenEyes Foundation
 * @license http://www.gnu.org/licenses/agpl-3.0.html The GNU Affero General Public License V3.0
 */

var OpenEyes = OpenEyes || {};

OpenEyes.OphCiExamination = OpenEyes.OphCiExamination || {};

(function(exports) {
    function HistoryRisksCore()
    {
        this.elementTypeClass = OE_MODEL_PREFIX + 'HistoryRisks';
        this.controllerElSelector = '#' + OE_MODEL_PREFIX + 'HistoryRisks_element';
    }

    /**
     * Singleton function for any element to call when wanting to add a Risk
     *
     * @param risks [{id: riskId, comments: [comment, ...]}, ...]
     * @param sourceElementName
     */
    HistoryRisksCore.prototype.addRisksForSource = function(risks, sourceElementName)
    {
        this.callFunctionOnController('addRisks', [risks, sourceElementName]);
    };

    /**
     * Abstraction for calling function on the active history risks controller
     *
     * @param funcName
     * @param args
     */
    HistoryRisksCore.prototype.callFunctionOnController = function(funcName, args)
    {
        var core = this;
        function controllerFunction() {
            var controller = $(core.controllerElSelector).data('controller');
            controller[funcName].apply(controller, args);
        }

        if (!$.find(core.controllerElSelector).length) {
            var sidebar = $('aside.episodes-and-events').data('patient-sidebar');
            sidebar.addElementByTypeClass(core.elementTypeClass, undefined, controllerFunction);
        } else {
            controllerFunction();
        }
    };

    if (exports.HistoryRisks === undefined) {
        exports.HistoryRisks = new HistoryRisksCore();
    }

    function HistoryRisksController(options) {
        this.options = $.extend(true, {}, HistoryRisksController._defaultOptions, options);
        this.$element = this.options.element;
        this.$element.data('controller', this);
        // this.riskSelector = '.' + this.options.modelName + '_risk_id';
        this.riskSelector = '[name$="[risk_id]"]';
        this.hasRiskSelector = '[name$="[has_risk]"]';
        this.otherSelector = '.' + this.options.modelName + '_other_risk';
        this.otherWrapperSelector = '.' + this.options.modelName + '_other_wrapper';
        this.commentsSelector = '[name$="[comments]"]';

        this.$noRisksWrapper = this.$element.find('.' + this.options.modelName + '_no_risks_wrapper');
        this.$noRisksFld = this.$element.find('.' + this.options.modelName + '_no_risks');
        this.tableSelector = '.' + this.options.modelName + '_entry_table';
        this.$table = this.$element.find(this.tableSelector);
        this.templateText = this.$element.find('.' + this.options.modelName + '_entry_template').text();
        this.riskIdMap = undefined;
        this.riskLabelMap = undefined;
        this.initialiseTriggers();
        this.dedupeRiskSelectors();
    }

    HistoryRisksController._defaultOptions = {
      modelName: 'OEModule_OphCiExamination_models_HistoryRisks',
      element: undefined
    };

    HistoryRisksController.prototype.initialiseTriggers = function()
    {
        var controller = this;
        controller.$element.on('change', controller.riskSelector, function(e) {
            var $selected = $(this).find('option:selected');
            var $container = $(this).parents('td');
            if ($selected.data('other')) {
                $container.find(controller.otherWrapperSelector).show();
            }
            else {
                $container.find(controller.otherWrapperSelector).hide();
                $container.find(controller.otherSelector).val('');
                controller.dedupeRiskSelectors();
            }
        });

        controller.$element.on('click', '.' + controller.options.modelName + '_add_entry', function(e) {
            e.preventDefault();
            controller.addEntry();
        });

      controller.$table.on('click', '.button.remove', function(e) {
            e.preventDefault();
            $(e.target).parents('tr').remove();
            controller.updateNoRisksState();
            controller.dedupeRiskSelectors();
        });

      controller.$noRisksFld.on('click', function() {
            if (controller.$noRisksFld.prop('checked')) {
                controller.$table.hide();
            }
            else {
                controller.$table.show();
            }
        })
    };

    /**
     * Show the no risks form section if there are no table entries
     */
    HistoryRisksController.prototype.updateNoRisksState = function()
    {
        if (this.$table.find('tbody tr').length === 0) {
            this.$noRisksWrapper.show();
        } else {
            this.$noRisksWrapper.hide();
            this.$noRisksFld.prop('checked', false);
        }
    };

    /**
     *
     * @param data
     * @returns {*}
     */
    HistoryRisksController.prototype.createRow = function(data)
    {
        if (data === undefined)
            data = {};

        data['row_count'] = OpenEyes.Util.getNextDataKey( this.tableSelector + ' tbody tr', 'key');
        return Mustache.render(
            this.templateText,
            data
        );
    };

    /**
     * Add a history risks row
     */
    HistoryRisksController.prototype.addEntry = function()
    {
        var row = this.createRow();
        this.$table.find('tbody').append(row);
        this.dedupeRiskSelectors();
        this.updateNoRisksState();
    };

    /**
     * Run through each Risk drop down and ensure selected options are not
     * available in other rows.
     */
    HistoryRisksController.prototype.dedupeRiskSelectors = function()
    {
        var self = this;
        var selectedRisks = [];
        self.$element.find(self.riskSelector).each(function() {
            var $selected = $(this).find('option:selected');
            if ($selected.val() && !$selected.data('other')) {
                selectedRisks.push($selected.val());
            }
        });

        self.$element.find(self.riskSelector).each(function() {
            $(this).find('option').each(function() {
                if (!$(this).is(':selected') && ($.inArray($(this).val(), selectedRisks) > -1)) {
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
        });
    }

    /**
     * Update the risks table with the given list of risks with comments
     */
    HistoryRisksController.prototype.addRisks = function(risks, sourceName)
    {
        for (var idx in risks) {
            if (risks.hasOwnProperty(idx)) {
                risk_id = risks[idx].id;
                // add to table if not present
                var rowEntry = this.getTableRowForRisk(risk_id);
                // set the risk and comment
                this.setHasRiskAndComments(rowEntry, risks[idx].comments);
            }

        }
    };

    /**
     * Find the table row for the given risk id if it exists.
     *
     * @param risk_id
     * @returns $('tr')|{undefined}
     */
    HistoryRisksController.prototype.findTableRowForRisk = function(risk_id)
    {
        var self = this;
        var row = undefined;
        self.$table.find('tbody tr').each(function() {
            if ($(this).find(self.riskSelector).val() == risk_id) {
                row = $(this);
                return false;
            }
        });
        return row;
    };

    /**
     * get or create a table row for the given risk
     */
    HistoryRisksController.prototype.getTableRowForRisk = function(risk_id)
    {
        var self = this;
        var row = self.findTableRowForRisk(risk_id);
        if (row === undefined) {
            self.addEntry();
            row = self.$table.find('tbody tr:last');
            row.find(self.riskSelector).val(risk_id);
        }
        return row;
    };

    /**
     *
     * @param row
     * @param comments
     */
    HistoryRisksController.prototype.setHasRiskAndComments = function(row, comments)
    {
        // select the appropriate radio option
        row.find(this.hasRiskSelector + '[value="1"]').prop('checked', 'checked').trigger('change');

        // now munge comments together with current content
        var current = row.find(this.commentsSelector).val();
        var finalList = [];
        if (current && current.replace(/\s/g, '').length) {
            finalList.push(current);
        }
        for (var i in comments) {
            var comment = comments[i];
            if (!current || current.indexOf(comment) === -1) {
                finalList.push(comment);
            }
        }
        row.find(this.commentsSelector).val(finalList.join(', '));
    };

    /**
     * Create an internal map of risk ids to names
     */
    HistoryRisksController.prototype.initialiseRiskIdMap = function()
    {
        var self = this;
        self.riskIdMap = {};
        var tmpRow = self.createRow({});
        $(tmpRow).find('td:first select option').each(function() {
            self.riskIdMap[$(this).val()] = $(this).text();
        });
        // map out those that are not in the dropdown list.
        self.$table.find('tr td:first').each(function() {
            var text = $(this).text();
            if (text.length) {
                self.riskIdMap[$(this).find(self.riskSelector).val()] = text;
            }
        })
    };

    /**
     * Find a risk id for given label (needs to partial match the risk name)
     * @param riskLabel
     * @returns {*}
     */
    HistoryRisksController.prototype.getRiskIdForLabel = function(riskLabel)
    {
        var self = this;

        if (self.riskIdMap === undefined) {
            self.initialiseRiskIdMap();
        }
        if (self.riskLabelMap === undefined) {
            self.riskLabelMap = {};
        }

        if (!self.riskLabelMap.hasOwnProperty(riskLabel)) {
            $.each(self.riskIdMap, function(id, name) {
                if (name.toLowerCase().indexOf(riskLabel.toLowerCase()) >= 0) {
                    self.riskLabelMap[riskLabel] = id;
                }
            });
        }
        return self.riskLabelMap[riskLabel];
    };

    /**
     *
     * @param riskLabel
     */
    HistoryRisksController.prototype.getRiskStatus = function(riskLabel)
    {
        var riskId = this.getRiskIdForLabel(riskLabel);
        var row = this.findTableRowForRisk(riskId);
        if (row === undefined)
            return undefined;

        var selected = row.find('input:checked');
        return selected ? selected.val() : undefined;
    };

    exports.HistoryRisksController = HistoryRisksController;
})(OpenEyes.OphCiExamination);

<commit_msg>minor bug tweak for history risks<commit_after>/**
 * OpenEyes
 *
 * (C) OpenEyes Foundation, 2017
 * This file is part of OpenEyes.
 * OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * OpenEyes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package OpenEyes
 * @link http://www.openeyes.org.uk
 * @author OpenEyes <info@openeyes.org.uk>
 * @copyright Copyright (c) 2017, OpenEyes Foundation
 * @license http://www.gnu.org/licenses/agpl-3.0.html The GNU Affero General Public License V3.0
 */

var OpenEyes = OpenEyes || {};

OpenEyes.OphCiExamination = OpenEyes.OphCiExamination || {};

(function(exports) {
    function HistoryRisksCore()
    {
        this.elementTypeClass = OE_MODEL_PREFIX + 'HistoryRisks';
        this.controllerElSelector = '#' + OE_MODEL_PREFIX + 'HistoryRisks_element';
    }

    /**
     * Singleton function for any element to call when wanting to add a Risk
     *
     * @param risks [{id: riskId, comments: [comment, ...]}, ...]
     * @param sourceElementName
     */
    HistoryRisksCore.prototype.addRisksForSource = function(risks, sourceElementName)
    {
        this.callFunctionOnController('addRisks', [risks, sourceElementName]);
    };

    /**
     * Abstraction for calling function on the active history risks controller
     *
     * @param funcName
     * @param args
     */
    HistoryRisksCore.prototype.callFunctionOnController = function(funcName, args)
    {
        var core = this;
        function controllerFunction() {
            var controller = $(core.controllerElSelector).data('controller');
            controller[funcName].apply(controller, args);
        }

        if (!$.find(core.controllerElSelector).length) {
            var sidebar = $('aside.episodes-and-events').data('patient-sidebar');
            sidebar.addElementByTypeClass(core.elementTypeClass, undefined, controllerFunction);
        } else {
            controllerFunction();
        }
    };

    if (exports.HistoryRisks === undefined) {
        exports.HistoryRisks = new HistoryRisksCore();
    }

    function HistoryRisksController(options) {
        this.options = $.extend(true, {}, HistoryRisksController._defaultOptions, options);
        this.$element = this.options.element;
        this.$element.data('controller', this);
        // this.riskSelector = '.' + this.options.modelName + '_risk_id';
        this.riskSelector = '[name$="[risk_id]"]';
        this.hasRiskSelector = '[name$="[has_risk]"]';
        this.otherSelector = '.' + this.options.modelName + '_other_risk';
        this.otherWrapperSelector = '.' + this.options.modelName + '_other_wrapper';
        this.commentsSelector = '[name$="[comments]"]';

        this.$noRisksWrapper = this.$element.find('.' + this.options.modelName + '_no_risks_wrapper');
        this.$noRisksFld = this.$element.find('.' + this.options.modelName + '_no_risks');
        this.tableSelector = '.' + this.options.modelName + '_entry_table';
        this.$table = this.$element.find(this.tableSelector);
        this.templateText = this.$element.find('.' + this.options.modelName + '_entry_template').text();
        this.riskIdMap = undefined;
        this.riskLabelMap = undefined;
        this.initialiseTriggers();
        this.dedupeRiskSelectors();
    }

    HistoryRisksController._defaultOptions = {
      modelName: 'OEModule_OphCiExamination_models_HistoryRisks',
      element: undefined
    };

    HistoryRisksController.prototype.initialiseTriggers = function()
    {
        var controller = this;
        controller.$element.on('change', controller.riskSelector, function(e) {
            var $selected = $(this).find('option:selected');
            var $container = $(this).parents('td');
            if ($selected.data('other')) {
                $container.find(controller.otherWrapperSelector).show();
            }
            else {
                $container.find(controller.otherWrapperSelector).hide();
                $container.find(controller.otherSelector).val('');
            }
            controller.dedupeRiskSelectors();
        });

        controller.$element.on('click', '.' + controller.options.modelName + '_add_entry', function(e) {
            e.preventDefault();
            controller.addEntry();
        });

      controller.$table.on('click', '.button.remove', function(e) {
            e.preventDefault();
            $(e.target).parents('tr').remove();
            controller.updateNoRisksState();
            controller.dedupeRiskSelectors();
        });

      controller.$noRisksFld.on('click', function() {
            if (controller.$noRisksFld.prop('checked')) {
                controller.$table.hide();
            }
            else {
                controller.$table.show();
            }
        })
    };

    /**
     * Show the no risks form section if there are no table entries
     */
    HistoryRisksController.prototype.updateNoRisksState = function()
    {
        if (this.$table.find('tbody tr').length === 0) {
            this.$noRisksWrapper.show();
        } else {
            this.$noRisksWrapper.hide();
            this.$noRisksFld.prop('checked', false);
        }
    };

    /**
     *
     * @param data
     * @returns {*}
     */
    HistoryRisksController.prototype.createRow = function(data)
    {
        if (data === undefined)
            data = {};

        data['row_count'] = OpenEyes.Util.getNextDataKey( this.tableSelector + ' tbody tr', 'key');
        return Mustache.render(
            this.templateText,
            data
        );
    };

    /**
     * Add a history risks row
     */
    HistoryRisksController.prototype.addEntry = function()
    {
        var row = this.createRow();
        this.$table.find('tbody').append(row);
        this.dedupeRiskSelectors();
        this.updateNoRisksState();
    };

    /**
     * Run through each Risk drop down and ensure selected options are not
     * available in other rows.
     */
    HistoryRisksController.prototype.dedupeRiskSelectors = function()
    {
        var self = this;
        var selectedRisks = [];
        self.$element.find(self.riskSelector).each(function() {
            var $selected = $(this).find('option:selected');
            if ($selected.val() && !$selected.data('other')) {
                selectedRisks.push($selected.val());
            }
        });

        self.$element.find(self.riskSelector).each(function() {
            $(this).find('option').each(function() {
                if (!$(this).is(':selected') && ($.inArray($(this).val(), selectedRisks) > -1)) {
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
        });
    }

    /**
     * Update the risks table with the given list of risks with comments
     */
    HistoryRisksController.prototype.addRisks = function(risks, sourceName)
    {
        for (var idx in risks) {
            if (risks.hasOwnProperty(idx)) {
                risk_id = risks[idx].id;
                // add to table if not present
                var rowEntry = this.getTableRowForRisk(risk_id);
                // set the risk and comment
                this.setHasRiskAndComments(rowEntry, risks[idx].comments);
            }

        }
    };

    /**
     * Find the table row for the given risk id if it exists.
     *
     * @param risk_id
     * @returns $('tr')|{undefined}
     */
    HistoryRisksController.prototype.findTableRowForRisk = function(risk_id)
    {
        var self = this;
        var row = undefined;
        self.$table.find('tbody tr').each(function() {
            if ($(this).find(self.riskSelector).val() == risk_id) {
                row = $(this);
                return false;
            }
        });
        return row;
    };

    /**
     * get or create a table row for the given risk
     */
    HistoryRisksController.prototype.getTableRowForRisk = function(risk_id)
    {
        var self = this;
        var row = self.findTableRowForRisk(risk_id);
        if (row === undefined) {
            self.addEntry();
            row = self.$table.find('tbody tr:last');
            row.find(self.riskSelector).val(risk_id);
        }
        return row;
    };

    /**
     *
     * @param row
     * @param comments
     */
    HistoryRisksController.prototype.setHasRiskAndComments = function(row, comments)
    {
        // select the appropriate radio option
        row.find(this.hasRiskSelector + '[value="1"]').prop('checked', 'checked').trigger('change');

        // now munge comments together with current content
        var current = row.find(this.commentsSelector).val();
        var finalList = [];
        if (current && current.replace(/\s/g, '').length) {
            finalList.push(current);
        }
        for (var i in comments) {
            var comment = comments[i];
            if (!current || current.indexOf(comment) === -1) {
                finalList.push(comment);
            }
        }
        row.find(this.commentsSelector).val(finalList.join(', '));
    };

    /**
     * Create an internal map of risk ids to names
     */
    HistoryRisksController.prototype.initialiseRiskIdMap = function()
    {
        var self = this;
        self.riskIdMap = {};
        var tmpRow = self.createRow({});
        $(tmpRow).find('td:first select option').each(function() {
            self.riskIdMap[$(this).val()] = $(this).text();
        });
        // map out those that are not in the dropdown list.
        self.$table.find('tr td:first').each(function() {
            var text = $(this).text();
            if (text.length) {
                self.riskIdMap[$(this).find(self.riskSelector).val()] = text;
            }
        })
    };

    /**
     * Find a risk id for given label (needs to partial match the risk name)
     * @param riskLabel
     * @returns {*}
     */
    HistoryRisksController.prototype.getRiskIdForLabel = function(riskLabel)
    {
        var self = this;

        if (self.riskIdMap === undefined) {
            self.initialiseRiskIdMap();
        }
        if (self.riskLabelMap === undefined) {
            self.riskLabelMap = {};
        }

        if (!self.riskLabelMap.hasOwnProperty(riskLabel)) {
            $.each(self.riskIdMap, function(id, name) {
                if (name.toLowerCase().indexOf(riskLabel.toLowerCase()) >= 0) {
                    self.riskLabelMap[riskLabel] = id;
                }
            });
        }
        return self.riskLabelMap[riskLabel];
    };

    /**
     *
     * @param riskLabel
     */
    HistoryRisksController.prototype.getRiskStatus = function(riskLabel)
    {
        var riskId = this.getRiskIdForLabel(riskLabel);
        var row = this.findTableRowForRisk(riskId);
        if (row === undefined)
            return undefined;

        var selected = row.find('input:checked');
        return selected ? selected.val() : undefined;
    };

    exports.HistoryRisksController = HistoryRisksController;
})(OpenEyes.OphCiExamination);

<|endoftext|>


<commit_before>/**
 * pad with zeros
 * @author sarkiroka on 2017.01.13.
 */
var padInteger=require('./pad-integer');
var padFloat=require('./pad-float');
module.exports = function (a, b) {
	var dotPositionA = a.indexOf('.');
	var dotPositionB = a.indexOf('.');
	var numbers,resultA,resultB,retValue;
	if(dotPositionA==-1 && dotPositionB==-1){ // all integer
		numbers=Math.max(a.length, b.length);
		resultA=padInteger(a, numbers);
		resultB=padInteger(b, numbers);
		retValue={
			length: numbers,
			a: resultA,
			b: resultB
		};
	} else if(dotPositionA>-1 && dotPositionB>-1){ // all float
		numbers=Math.max(a.length, b.length);
		resultA=padFloat(a,numbers);
		resultB=padFloat(b,numbers);
		retValue={
			length:numbers,
			a:resultA,
			b:resultB
		}
	}else{
		if(dotPositionA==-1){
			a+='.0';
		}
		if(dotPositionB==-1){
			b+='.0';
		}
		dotPositionA = a.indexOf('.');
		dotPositionB = a.indexOf('.');
		numbers=Math.max(dotPositionA,dotPositionB);
		resultA=padInteger(a,numbers);
		resultB=padInteger(b,numbers);
		numbers=Math.max(resultA.length,resultB.length);
		resultA=padFloat(a,numbers);
		resultB=padFloat(b,numbers);
		retValue={
			length:numbers,
			a:resultA,
			b:resultB
		}
	}
	return retValue;
};
<commit_msg>fractions<commit_after>/**
 * pad with zeros
 * @author sarkiroka on 2017.01.13.
 */
var padInteger=require('./pad-integer');
var padFloat=require('./pad-float');
module.exports = function (a, b) {
	var dotPositionA = a.indexOf('.');
	var dotPositionB = a.indexOf('.');
	var numbers,resultA,resultB,retValue;
	if(dotPositionA==-1 && dotPositionB==-1){ // all integer
		numbers=Math.max(a.length, b.length);
		resultA=padInteger(a, numbers);
		resultB=padInteger(b, numbers);
		retValue={
			length: numbers,
			a: resultA,
			b: resultB
		};
	} else if(dotPositionA>-1 && dotPositionB>-1){ // all float
		numbers=Math.max(a.length, b.length);
		resultA=padFloat(a,numbers);
		resultB=padFloat(b,numbers);
		retValue={
			length:numbers,
			a:resultA,
			b:resultB
		}
	}else{
		if(dotPositionA==-1){
			a+='.0';
		}
		if(dotPositionB==-1){
			b+='.0';
		}
		dotPositionA = a.indexOf('.');
		dotPositionB = a.indexOf('.');
		numbers=Math.max(dotPositionA,dotPositionB);
		resultA=padInteger(a,numbers);
		resultB=padInteger(b,numbers);
		numbers=Math.max(resultA.length,resultB.length);
		resultA=padFloat(resultA,numbers);
		resultB=padFloat(resultB,numbers);
		retValue={
			length:numbers,
			a:resultA,
			b:resultB
		}
	}
	return retValue;
};
<|endoftext|>


<commit_before>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

 defaultDuration = 5000

var AutoReloader = function autoReloader (options) {
  var returning = {}
  // validating functions
  var checkBool = function checkBool (args) {
    // check if passed args are 'true' or 'false' type
    for (var a in args) {
      if (args[a] !== 'true' && args[a] !== 'false') return false
    }
    return true
  }
  var checkType = function checkType (type, args) {
    // checking the type of each variable in the passed array
    for (var a in args) {
      if (typeof args[a] !== type) return false
    }
    return true
  }

  // main class, contains all
  if (typeof options !== 'object') options = {}
  returning.options = { // inserted options, with defaults
    identifier: options.identifier || '.autoreloader', // class or id to identify the autoloading element with
    duration: options.duration * 1000 || defaultDuration, // duration number in seconds, in-which each reload is due
    add_classes: options.add_classes || ['btn-danger'], // css classes to add or remove with start or stop
    add_classes_span: options.add_classes_span || ['fa-spin'], // to add classes to span inside button
    add_style: options.add_style || ';font-size: 200%; color: green;', // css style to add or remove with start or stop
    remember_position: options.remember_position || 'true', // to remember the screen position after reload
    fix_rotation: options.screen_rotation || 'true', // to fix screen size rotation with reload
    auto_start: options.auto_start || 'false' // to start auto reloading without element click
  }

  returning.defaults = {
    sleeps: []  // to store timeouts
  }

  returning.__init__ = function __init__ () {
  // Validation
    // Type validation
    if (!checkType('string', [
      returning.options.add_classes]) && !(
        returning.options.add_classes instanceof Array)
      ) throw new TypeError('auto_reloader(options) add_classes requires array of strings')
    if (!checkType('string', [
      returning.options.add_classes_span]) && !(
        returning.options.add_classes_span instanceof Array)
      ) throw new TypeError('auto_reloader(options) add_classes_span requires array of strings')
    if (!checkType('string', [
      returning.options.identifier,
      returning.options.add_style
    ])) throw new TypeError('auto_reloader(options) identifier, add_style require strings')
    if (!checkBool([
      returning.options.remember_position,
      returning.options.fix_rotation
    ])) throw new TypeError('auto_reloader(options) remember_position, fix_rotation require "true" or "false"')
    if (typeof returning.options.duration !== 'number' || returning.options.duration < 0) throw new TypeError('auto_reloader(options) duration requires valid number')
    // Value validation
    if (!(returning.options.identifier.startsWith('.')) && !(returning.options.identifier.startsWith('#'))) throw new Error('auto_reloader(options) identifier should start with # or .')
    if ($(returning.options.identifier).length <= 0 && returning.options.auto_start === 'false') throw new Error('auto_reloader(options) can not find any elements with identifier')
  // Setup directions
    $(returning.options.identifier).click(function (event) {
      if (sessionStorage.active === undefined) start(); else stop() // start or stop if clicked
    })
    if (sessionStorage.active !== undefined || returning.options.auto_start === 'true') start() // start if not first time
  }

// Starter and Stopper

  // global name to access from events
  var start = function start () {
    // starting the auto reload, changing style
    if (sessionStorage.active !== undefined) {
      returning.set_style(false)
      if (returning.options.remember_position) $(window).scrollTop(sessionStorage.position) // to remember position
      if (returning.options.fix_rotation) returning.check_screen() // to watch out for screen size change
      returning.reload() // timeout to reload
    } else {
      returning.set_style()
      returning.reload(0)
    }
  }
  // global name to access from events
  var stop = function stop () {
    // stopping the auto reload clearing timeouts restoring style
    returning.restore_style()
    if (returning.defaults.sleeps.length > 0) {
      $.each(returning.defaults.sleeps, function (i, value) {
        clearTimeout(value)
      })
    }
    // clearing up the storage
    sessionStorage.clear()
  }

// When Started

  returning.reload = function reload (duration) {
    duration = duration || sessionStorage.duration || returning.options.duration
    // setting timeout to reload
    // clearing timeouts before loading
    returning.defaults.sleeps.push(
      setTimeout(function () {
        sessionStorage.position = $(window).scrollTop() // getting screen position
        sessionStorage.active = 'true' // to indeicate not a first time
        location.reload()
      }, duration)
    )
  }
  returning.check_screen = function checkScreen (
    // setting event watch for screen resize or rotation and reload if so
    height, width) {

    height = height || $(window).height()
    width = width || $(window).width()

    jQuery(function ($) {
      $(window).resize(function () {
        if (height !== $(window).height() || width !== $(window).width()) {
          location.reload()
        }
      })
    })
  }
  returning.set_style = function setStyle (notactive) {
    notactive = notactive || true

    // setting the button style with style and class
    for (var i = 0; returning.options.add_classes.length > i; i += 1) {
      $(returning.options.identifier).addClass(returning.options.add_classes[i])
    }
    for (var i = 0; returning.options.add_classes_span.length > i; i += 1) {
      $(returning.options.identifier + '> span').addClass(returning.options.add_classes_span[i])
    }
    if ($(returning.options.identifier).attr('style') !== undefined && notactive) {
      sessionStorage.style = $(returning.options.identifier).attr('style') // storing style
      $(returning.options.identifier).attr(
        'style', sessionStorage.style + ';' + returning.options.add_style
      ) // adding style to existing one
    } else {
      if (sessionStorage.style !== undefined) $(returning.options.identifier).attr('style', sessionStorage.style + ';' + returning.options.add_style)
      else $(returning.options.identifier).attr('style', returning.options.add_style)
    }
  }

// When Stopped

  returning.restore_style = function restoreStyle () {
    // restoring the button previous style
    for (var i = 0; returning.options.add_classes.length > i; i += 1) {
      if ($(returning.options.identifier).hasClass(returning.options.add_classes[i])) {
        $(returning.options.identifier).removeClass(returning.options.add_classes[i])
      }
    }
    for (var i = 0; returning.options.add_classes_span.length > i; i += 1) {
      if ($(returning.options.identifier + ' > span').hasClass(returning.options.add_classes_span[i])) {
        $(returning.options.identifier + ' > span').removeClass(returning.options.add_classes_span[i])
      }
    }
    if (sessionStorage.style !== undefined) {
      $(returning.options.identifier).attr('style', sessionStorage.style)
      sessionStorage.style = false
    } else { // if style not stored and equal to iserted style, will be emptied
      if ($(returning.options.identifier).attr('style') === returning.options.add_style) {
        $(returning.options.identifier).attr('style', '')
      }
    }
  }

// Initiate and return the class

  returning.__init__()
  return returning
}

var AskReloader = function ask (msg) {
  msg = msg || "Enter new auto-reload duration in seconds : "
  // to prompt user to set new duration
  var newDuration = window.prompt(
    msg,
    sessionStorage.duration / 1000 || defaultDuration / 1000
  )
  sessionStorage.duration = newDuration > 0 ? newDuration * 1000 : sessionStorage.duration ? sessionStorage.duration : defaultDuration
}<commit_msg>Replace sessionStorage with localStorage, Resolves #237<commit_after>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

 defaultDuration = 5000

var AutoReloader = function autoReloader (options) {
  var returning = {}
  // validating functions
  var checkBool = function checkBool (args) {
    // check if passed args are 'true' or 'false' type
    for (var a in args) {
      if (args[a] !== 'true' && args[a] !== 'false') return false
    }
    return true
  }
  var checkType = function checkType (type, args) {
    // checking the type of each variable in the passed array
    for (var a in args) {
      if (typeof args[a] !== type) return false
    }
    return true
  }

  // main class, contains all
  if (typeof options !== 'object') options = {}
  returning.options = { // inserted options, with defaults
    identifier: options.identifier || '.autoreloader', // class or id to identify the autoloading element with
    duration: options.duration * 1000 || defaultDuration, // duration number in seconds, in-which each reload is due
    add_classes: options.add_classes || ['btn-danger'], // css classes to add or remove with start or stop
    add_classes_span: options.add_classes_span || ['fa-spin'], // to add classes to span inside button
    add_style: options.add_style || ';font-size: 200%; color: green;', // css style to add or remove with start or stop
    remember_position: options.remember_position || 'true', // to remember the screen position after reload
    fix_rotation: options.screen_rotation || 'true', // to fix screen size rotation with reload
    auto_start: options.auto_start || 'false' // to start auto reloading without element click
  }

  returning.defaults = {
    sleeps: []  // to store timeouts
  }

  returning.__init__ = function __init__ () {
  // Validation
    // Type validation
    if (!checkType('string', [
      returning.options.add_classes]) && !(
        returning.options.add_classes instanceof Array)
      ) throw new TypeError('auto_reloader(options) add_classes requires array of strings')
    if (!checkType('string', [
      returning.options.add_classes_span]) && !(
        returning.options.add_classes_span instanceof Array)
      ) throw new TypeError('auto_reloader(options) add_classes_span requires array of strings')
    if (!checkType('string', [
      returning.options.identifier,
      returning.options.add_style
    ])) throw new TypeError('auto_reloader(options) identifier, add_style require strings')
    if (!checkBool([
      returning.options.remember_position,
      returning.options.fix_rotation
    ])) throw new TypeError('auto_reloader(options) remember_position, fix_rotation require "true" or "false"')
    if (typeof returning.options.duration !== 'number' || returning.options.duration < 0) throw new TypeError('auto_reloader(options) duration requires valid number')
    // Value validation
    if (!(returning.options.identifier.startsWith('.')) && !(returning.options.identifier.startsWith('#'))) throw new Error('auto_reloader(options) identifier should start with # or .')
    if ($(returning.options.identifier).length <= 0 && returning.options.auto_start === 'false') throw new Error('auto_reloader(options) can not find any elements with identifier')
  // Setup directions
    $(returning.options.identifier).click(function (event) {
      if (localStorage.active === undefined) start(); else stop() // start or stop if clicked
    })
    if (localStorage.active !== undefined || returning.options.auto_start === 'true') start() // start if not first time
  }

// Starter and Stopper

  // global name to access from events
  var start = function start () {
    // starting the auto reload, changing style
    if (localStorage.active !== undefined) {
      returning.set_style(false)
      if (returning.options.remember_position) $(window).scrollTop(localStorage.position) // to remember position
      if (returning.options.fix_rotation) returning.check_screen() // to watch out for screen size change
      returning.reload() // timeout to reload
    } else {
      returning.set_style()
      returning.reload(0)
    }
  }
  // global name to access from events
  var stop = function stop () {
    // stopping the auto reload clearing timeouts restoring style
    returning.restore_style()
    if (returning.defaults.sleeps.length > 0) {
      $.each(returning.defaults.sleeps, function (i, value) {
        clearTimeout(value)
      })
    }
    // clearing up the storage
    localStorage.clear()
  }

// When Started

  returning.reload = function reload (duration) {
    duration = duration || localStorage.duration || returning.options.duration
    // setting timeout to reload
    // clearing timeouts before loading
    returning.defaults.sleeps.push(
      setTimeout(function () {
        localStorage.position = $(window).scrollTop() // getting screen position
        localStorage.active = 'true' // to indeicate not a first time
        location.reload()
      }, duration)
    )
  }
  returning.check_screen = function checkScreen (
    // setting event watch for screen resize or rotation and reload if so
    height, width) {

    height = height || $(window).height()
    width = width || $(window).width()

    jQuery(function ($) {
      $(window).resize(function () {
        if (height !== $(window).height() || width !== $(window).width()) {
          location.reload()
        }
      })
    })
  }
  returning.set_style = function setStyle (notactive) {
    notactive = notactive || true

    // setting the button style with style and class
    for (var i = 0; returning.options.add_classes.length > i; i += 1) {
      $(returning.options.identifier).addClass(returning.options.add_classes[i])
    }
    for (var i = 0; returning.options.add_classes_span.length > i; i += 1) {
      $(returning.options.identifier + '> span').addClass(returning.options.add_classes_span[i])
    }
    if ($(returning.options.identifier).attr('style') !== undefined && notactive) {
      localStorage.style = $(returning.options.identifier).attr('style') // storing style
      $(returning.options.identifier).attr(
        'style', localStorage.style + ';' + returning.options.add_style
      ) // adding style to existing one
    } else {
      if (localStorage.style !== undefined) $(returning.options.identifier).attr('style', localStorage.style + ';' + returning.options.add_style)
      else $(returning.options.identifier).attr('style', returning.options.add_style)
    }
  }

// When Stopped

  returning.restore_style = function restoreStyle () {
    // restoring the button previous style
    for (var i = 0; returning.options.add_classes.length > i; i += 1) {
      if ($(returning.options.identifier).hasClass(returning.options.add_classes[i])) {
        $(returning.options.identifier).removeClass(returning.options.add_classes[i])
      }
    }
    for (var i = 0; returning.options.add_classes_span.length > i; i += 1) {
      if ($(returning.options.identifier + ' > span').hasClass(returning.options.add_classes_span[i])) {
        $(returning.options.identifier + ' > span').removeClass(returning.options.add_classes_span[i])
      }
    }
    if (localStorage.style !== undefined) {
      $(returning.options.identifier).attr('style', localStorage.style)
      localStorage.style = false
    } else { // if style not stored and equal to iserted style, will be emptied
      if ($(returning.options.identifier).attr('style') === returning.options.add_style) {
        $(returning.options.identifier).attr('style', '')
      }
    }
  }

// Initiate and return the class

  returning.__init__()
  return returning
}

var AskReloader = function ask (msg) {
  msg = msg || "Enter new auto-reload duration in seconds : "
  // to prompt user to set new duration
  var newDuration = window.prompt(
    msg,
    localStorage.duration / 1000 || defaultDuration / 1000
  )
  localStorage.duration = newDuration > 0 ? newDuration * 1000 : localStorage.duration ? localStorage.duration : defaultDuration
}<|endoftext|>


<commit_before>var portfolioElements = {};

portfolioElements.all = [];

function Portfolios (opts) {
  this.title = opts.title;
  this.repoUrl = opts.repoUrl;
  this.deployUrl = opts.deployUrl;
  this.finishedOn = opts.finishedOn;
  this.snippet = opts.snippet;
};

Portfolios.prototype.toHtml = function() {
  var portfolioItem = Handlebars.compile($('#porfolio-template').text());
  this.daysAgo = parseInt((new Date() - new Date (this.finishedOn))/60/60/24/1000);
  this.publishedRef = ' ' + this.daysAgo + ' days ago.';
  return portfolioItem(this);
};

var portfolioPieces = [];

portfolioPieces.getAll = function (){
  $.getJSON('data/portfolioPieces.json', function(data, message, xhr){
    localStorage.setItem('portfolioArticles' , JSON.stringify(data));
    portfolioPieces.loadAll(JSON.parse(localStorage.portfolioArticles));
    portfolioElements.initHomePage();
  });
};

portfolioPieces.loadAll = function (portfolioPieces){
  portfolioPieces.sort(function(a,b) {
    return (new Date(b.finishedOn)) - (new Date(a.finishedOn));
  });

  portfolioPieces.forEach(function(ele){
    portfolioElements.all.push(new Portfolios(ele));
  });
};

portfolioElements.initHomePage = function() {
  portfolioElements.all.forEach(function(a){
    $('#portfolio-pieces').append(a.toHtml());
  });
};
<commit_msg>cleaned up some extra lines of code<commit_after>var portfolioElements = {};

portfolioElements.all = [];

function Portfolios (opts) {
  this.title = opts.title;
  this.repoUrl = opts.repoUrl;
  this.deployUrl = opts.deployUrl;
  this.finishedOn = opts.finishedOn;
  this.snippet = opts.snippet;
};

Portfolios.prototype.toHtml = function() {
  var portfolioItem = Handlebars.compile($('#porfolio-template').text());
  this.daysAgo = parseInt((new Date() - new Date (this.finishedOn))/60/60/24/1000);
  this.publishedRef = ' ' + this.daysAgo + ' days ago.';
  return portfolioItem(this);
};

var portfolioPieces = [];

portfolioPieces.getAll = function (){
  $.getJSON('data/portfolioPieces.json', function(data, message, xhr){
    localStorage.setItem('portfolioArticles' , JSON.stringify(data));
    portfolioPieces.loadAll(JSON.parse(localStorage.portfolioArticles));
    portfolioElements.initHomePage();
  });
};

portfolioPieces.loadAll = function (portfolioPieces){
  portfolioPieces.sort(function(a,b) {
    return (new Date(b.finishedOn)) - (new Date(a.finishedOn));
  });

  portfolioPieces.forEach(function(ele){
    portfolioElements.all.push(new Portfolios(ele));
  });
};

portfolioElements.initHomePage = function() {
  portfolioElements.all.forEach(function(a){
    $('#portfolio-pieces').append(a.toHtml());
  });
};
<|endoftext|>


<commit_before>angular.module('os.administrative.container.addedit', ['os.administrative.models'])
  .controller('ContainerAddEditCtrl', function(
    $scope, $state, $stateParams, $q, container,
    Site, Container, CollectionProtocol, PvManager, Util) {

    var allSpecimenTypes = undefined;
    var allowedCps = undefined;
    var parentContainerName = undefined;

    function init() {
      $scope.container = container;
      parentContainerName = container.parentContainerName;

      /**
       * Some how the ui-select's multiple option is removing pre-selected items
       * when cp list is being loaded or not yet loaded...
       * Therefore we copy pre-selected cps and then use it when all CPs are loaded
       */
      allowedCps = angular.copy(container.allowedCollectionProtocols);

      $scope.cps = [];
      $scope.specimenTypes = [];
      loadPvs();

      $scope.specimenTypeSelectorOpts = {
        items: $scope.specimenTypes,
        selectedCategories: container.allowedSpecimenClasses,
        selectedCategoryItems: container.allowedSpecimenTypes,
        categoryAttr: 'parent',
        valueAttr: 'value',
        allowAll: undefined
      };

      if ($stateParams.parentContainerName && $stateParams.parentContainerId &&
          $stateParams.posOne && $stateParams.posTwo) {
        //
        // This happens when user adds container from container map
        //

        $scope.locationSelected = true;
        container.position = {posOne: $stateParams.posOne, posTwo: $stateParams.posTwo};
        container.parentContainerName = $stateParams.parentContainerName;
        restrictCpsAndSpecimenTypes();
      }

      watchParentContainer();
    };

    function watchParentContainer() {
      $scope.$watch('container.parentContainerName', function(newVal, oldVal) {
        if (newVal == oldVal) {
          return;
        }

        if (!newVal) {
          loadAllCpsAndSpecimenTypes();
        } else {
          restrictCpsAndSpecimenTypes();
        }
      });
    };

    function loadPvs() {
      $scope.positionLabelingSchemes = PvManager.getPvs('container-position-labeling-schemes');

      var op = !!$scope.container.id ? 'Update' : 'Create';
      $scope.sites = [];
      Site.listForContainers(op).then(function(sites) {
        $scope.sites = sites;
      });

      if ($scope.container.parentContainerName) {
        restrictCpsAndSpecimenTypes();
      } else {
        loadAllCpsAndSpecimenTypes();
      }

      if (!!$scope.container.siteName) {
        $scope.loadContainers($scope.container.siteName);
      }

    };

    function restrictCpsAndSpecimenTypes() {
      var parentName = $scope.container.parentContainerName;
      Container.getByName(parentName).then(
        function(parentContainer) {
          restrictCps(parentContainer);
          restrictSpecimenTypes(parentContainer);
        }
      );
    };

    function loadAllCpsAndSpecimenTypes() {
      loadAllCps();
      loadAllSpecimenTypes();
    };

    function restrictCps(parentContainer) {
      var parentCps = parentContainer.calcAllowedCollectionProtocols;
      if (parentCps.length > 0) {
        $scope.cps = parentCps;
      } else {
        loadAllCps(parentContainer.siteName);
      }

      $scope.container.allowedCollectionProtocols = allowedCps;
    };

    function loadAllCps(siteName) {
      siteName = !siteName ? $scope.container.siteName : siteName;

      CollectionProtocol.query({repositoryName: siteName}).then(
        function(cps) {
          $scope.cps = cps.map(function(cp) { return cp.shortTitle; });

          // fix - pre-selected cps were getting cleared
          $scope.container.allowedCollectionProtocols = allowedCps;
        }
      );
    };

    function restrictSpecimenTypes(parentContainer) {
      if (allSpecimenTypes) {
        filterSpecimenTypes(parentContainer);
      } else {
        loadAllSpecimenTypes().then(
          function() {
            filterSpecimenTypes(parentContainer);
          }
        );
      }
    };

    function filterSpecimenTypes(parentContainer) {
      var allowedClasses = parentContainer.calcAllowedSpecimenClasses;
      var allowedTypes = parentContainer.calcAllowedSpecimenTypes;
      $scope.specimenTypeSelectorOpts.allowAll = allowedClasses;

      var filtered = allSpecimenTypes.filter(
        function(specimenType) {
          return allowedClasses.indexOf(specimenType.parent) >= 0 ||
                   allowedTypes.indexOf(specimenType.value) >= 0;
        }
      );
      Util.assign($scope.specimenTypes, filtered);
    };

    function loadAllSpecimenTypes() {
      if (allSpecimenTypes) {
        var d = $q.defer();
        d.resolve(allSpecimenTypes);
        return d.promise;
      }

      return PvManager.loadPvsByParent('specimen-class', undefined, true).then(
        function(specimenTypes) {
          allSpecimenTypes = specimenTypes;
          Util.assign($scope.specimenTypes, specimenTypes);
          return allSpecimenTypes;
        }
      );
    };

    //
    // invoked when a site is selected on UI
    //
    $scope.loadContainers = function(siteName) {
      Container.listForSite(siteName, true, true).then(
        function(result) {
          $scope.containers = [];
          angular.forEach(result, function(container) {
            $scope.containers.push(container.name);
          });
        }
      );

      loadAllCps(siteName);
    };

    $scope.save = function() {
      var container = angular.copy($scope.container);
      if (container.id && container.parentContainerName != parentContainerName) {
        //
        // if parent container is changed, we need to invalidate
        // existing container position
        //
        //
        container.position = undefined;
      }

      container.$saveOrUpdate().then(
        function(result) {
          if (!$scope.locationSelected) {
            $state.go('container-detail.overview', {containerId: result.id});
          } else {
            $state.go('container-detail.locations', {containerId: $stateParams.parentContainerId});
          }
        }
      );
    };

    init();
  });
<commit_msg>OPSMN-2198:<commit_after>angular.module('os.administrative.container.addedit', ['os.administrative.models'])
  .controller('ContainerAddEditCtrl', function(
    $scope, $state, $stateParams, $q, container,
    Site, Container, CollectionProtocol, PvManager, Util) {

    var allSpecimenTypes = undefined;
    var allowedCps = undefined;
    var parentContainerName = undefined;

    function init() {
      container.parentContainerId = undefined;
      $scope.container = container;
      parentContainerName = container.parentContainerName;

      /**
       * Some how the ui-select's multiple option is removing pre-selected items
       * when cp list is being loaded or not yet loaded...
       * Therefore we copy pre-selected cps and then use it when all CPs are loaded
       */
      allowedCps = angular.copy(container.allowedCollectionProtocols);

      $scope.cps = [];
      $scope.specimenTypes = [];
      loadPvs();

      $scope.specimenTypeSelectorOpts = {
        items: $scope.specimenTypes,
        selectedCategories: container.allowedSpecimenClasses,
        selectedCategoryItems: container.allowedSpecimenTypes,
        categoryAttr: 'parent',
        valueAttr: 'value',
        allowAll: undefined
      };

      if ($stateParams.parentContainerName && $stateParams.parentContainerId &&
          $stateParams.posOne && $stateParams.posTwo) {
        //
        // This happens when user adds container from container map
        //

        $scope.locationSelected = true;
        container.position = {posOne: $stateParams.posOne, posTwo: $stateParams.posTwo};
        container.parentContainerName = $stateParams.parentContainerName;
        restrictCpsAndSpecimenTypes();
      }

      watchParentContainer();
    };

    function watchParentContainer() {
      $scope.$watch('container.parentContainerName', function(newVal, oldVal) {
        if (newVal == oldVal) {
          return;
        }

        if (!newVal) {
          loadAllCpsAndSpecimenTypes();
        } else {
          restrictCpsAndSpecimenTypes();
        }
      });
    };

    function loadPvs() {
      $scope.positionLabelingSchemes = PvManager.getPvs('container-position-labeling-schemes');

      var op = !!$scope.container.id ? 'Update' : 'Create';
      $scope.sites = [];
      Site.listForContainers(op).then(function(sites) {
        $scope.sites = sites;
      });

      if ($scope.container.parentContainerName) {
        restrictCpsAndSpecimenTypes();
      } else {
        loadAllCpsAndSpecimenTypes();
      }

      if (!!$scope.container.siteName) {
        $scope.loadContainers($scope.container.siteName);
      }

    };

    function restrictCpsAndSpecimenTypes() {
      var parentName = $scope.container.parentContainerName;
      Container.getByName(parentName).then(
        function(parentContainer) {
          restrictCps(parentContainer);
          restrictSpecimenTypes(parentContainer);
        }
      );
    };

    function loadAllCpsAndSpecimenTypes() {
      loadAllCps();
      loadAllSpecimenTypes();
    };

    function restrictCps(parentContainer) {
      var parentCps = parentContainer.calcAllowedCollectionProtocols;
      if (parentCps.length > 0) {
        $scope.cps = parentCps;
      } else {
        loadAllCps(parentContainer.siteName);
      }

      $scope.container.allowedCollectionProtocols = allowedCps;
    };

    function loadAllCps(siteName) {
      siteName = !siteName ? $scope.container.siteName : siteName;

      CollectionProtocol.query({repositoryName: siteName}).then(
        function(cps) {
          $scope.cps = cps.map(function(cp) { return cp.shortTitle; });

          // fix - pre-selected cps were getting cleared
          $scope.container.allowedCollectionProtocols = allowedCps;
        }
      );
    };

    function restrictSpecimenTypes(parentContainer) {
      if (allSpecimenTypes) {
        filterSpecimenTypes(parentContainer);
      } else {
        loadAllSpecimenTypes().then(
          function() {
            filterSpecimenTypes(parentContainer);
          }
        );
      }
    };

    function filterSpecimenTypes(parentContainer) {
      var allowedClasses = parentContainer.calcAllowedSpecimenClasses;
      var allowedTypes = parentContainer.calcAllowedSpecimenTypes;
      $scope.specimenTypeSelectorOpts.allowAll = allowedClasses;

      var filtered = allSpecimenTypes.filter(
        function(specimenType) {
          return allowedClasses.indexOf(specimenType.parent) >= 0 ||
                   allowedTypes.indexOf(specimenType.value) >= 0;
        }
      );
      Util.assign($scope.specimenTypes, filtered);
    };

    function loadAllSpecimenTypes() {
      if (allSpecimenTypes) {
        var d = $q.defer();
        d.resolve(allSpecimenTypes);
        return d.promise;
      }

      return PvManager.loadPvsByParent('specimen-class', undefined, true).then(
        function(specimenTypes) {
          allSpecimenTypes = specimenTypes;
          Util.assign($scope.specimenTypes, specimenTypes);
          return allSpecimenTypes;
        }
      );
    };

    //
    // invoked when a site is selected on UI
    //
    $scope.loadContainers = function(siteName) {
      Container.listForSite(siteName, true, true).then(
        function(result) {
          $scope.containers = [];
          angular.forEach(result, function(container) {
            $scope.containers.push(container.name);
          });
        }
      );

      loadAllCps(siteName);
    };

    $scope.save = function() {
      var container = angular.copy($scope.container);
      if (container.id && container.parentContainerName != parentContainerName) {
        //
        // if parent container is changed, we need to invalidate
        // existing container position
        //
        //
        container.position = undefined;
      }

      container.$saveOrUpdate().then(
        function(result) {
          if (!$scope.locationSelected) {
            $state.go('container-detail.overview', {containerId: result.id});
          } else {
            $state.go('container-detail.locations', {containerId: $stateParams.parentContainerId});
          }
        }
      );
    };

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