<commit_before>var fs     = require('fs'),
    interp = require('../lib/interpolate'),
    glob   = require('glob'),
    async  = require('async'),
    utils  = require('amd-utils')
;

var task = {
    id      : 'scaffolding-close',
    author  : 'Indigo United',
    name    : 'Scaffolding: close placeholder',
    options : {
        file: {
            description: 'The file(s) to apply the close (supports minimatch patterns)'
        },
        placeholders: {
            description: 'Which placeholder(s) to close'
        },
        cleanup: {
            description: 'Cleans leading or trailing spaces',
            'default': true
        }
    },
    tasks   :
    [
        {
            task : function (opt, next) {
                var files = !utils.lang.isArray(opt.file) ? [opt.file] : opt.file;
                var data = {};

                opt.placeholders.forEach(function (placeholder) {
                    data[placeholder] = '';
                });

                // data is done at this time
                // For each item in the files array, perform a glob
                async.forEach(files, function (file, next) {
                    glob(file, function (err, files) {
                        if (err) {
                            return next(err);
                        }

                        // For each file in the glob result,
                        // close the placeholders
                        async.forEach(files, function (file, next) {
                            // Only apply to files
                            fs.stat(file, function (err, stat) {
                                if (err) {
                                    return next(err);
                                }

                                if (!stat.isFile()) {
                                    return next();
                                }

                                fs.readFile(file, function (err, contents) {
                                    if (err) {
                                        return next(err);
                                    }

                                    contents = interp(contents.toString(), data, opt.cleanup);
                                    fs.writeFile(file, contents, next);
                                });
                            });
                        }, next);
                    });
                }, next);
            }
        }
    ]
};

module.exports = task;<commit_msg>Forgot tho change scaffolding-close task.<commit_after>var fs     = require('fs'),
    interp = require('../lib/interpolate'),
    glob   = require('glob'),
    async  = require('async'),
    utils  = require('amd-utils')
;

var task = {
    id      : 'scaffolding-close',
    author  : 'Indigo United',
    name    : 'Scaffolding: close placeholder',
    options : {
        file: {
            description: 'The file(s) to apply the close (supports minimatch patterns)'
        },
        placeholders: {
            description: 'Which placeholder(s) to close'
        },
        trim: {
            description: 'Trim leading or trailing spaces',
            'default': true
        }
    },
    tasks   :
    [
        {
            task : function (opt, next) {
                var files = !utils.lang.isArray(opt.file) ? [opt.file] : opt.file;
                var data = {};

                opt.placeholders.forEach(function (placeholder) {
                    data[placeholder] = '';
                });

                // data is done at this time
                // For each item in the files array, perform a glob
                async.forEach(files, function (file, next) {
                    glob(file, function (err, files) {
                        if (err) {
                            return next(err);
                        }

                        // For each file in the glob result,
                        // close the placeholders
                        async.forEach(files, function (file, next) {
                            // Only apply to files
                            fs.stat(file, function (err, stat) {
                                if (err) {
                                    return next(err);
                                }

                                if (!stat.isFile()) {
                                    return next();
                                }

                                fs.readFile(file, function (err, contents) {
                                    if (err) {
                                        return next(err);
                                    }

                                    contents = interp(contents.toString(), data, opt.trim);
                                    fs.writeFile(file, contents, next);
                                });
                            });
                        }, next);
                    });
                }, next);
            }
        }
    ]
};

module.exports = task;<|endoftext|>


<commit_before>
//var dirSounds = "Sounds/";
var dirScreenShots = "res/screenshots/";
var dirImages = "res/images/";
var dirFonts = "res/fonts/";
var dirSpriteSheets = "res/spritesheets/";

/*

var s_bgMusic = dirSounds + "background-music.mp3";
var s_bgMusicOgg = dirSounds + "background-music.ogg";
var s_bgMusicCaf = dirSounds + "background-music.caf";

var s_shootEffect = dirSounds + "pew-pew-lei.mp3";
var s_shootEffectOgg = dirSounds + "pew-pew-lei.ogg";
var s_shootEffectWav = dirSounds + "pew-pew-lei.wav";
*/
var sJoystixFont = dirFonts + "Joystix.ttf";

var sSplashTeam = dirScreenShots + "splashTeam_800-480.png";
var sSplashGame = dirScreenShots + "splashGame_800-480.png";
var sMenuTitle = dirImages + "menuTitle_595-135.png";
var ssGame = dirSpriteSheets + "GameSpriteSheet.png";
var ssGameList = dirSpriteSheets + "GameSpriteSheet.plist";
var sPacLife = dirImages + "pac_left_14-16.png";
var sGameOver = dirImages + "game_over_217-32.png";

var resource = [
    /*

    {type:"sound", src:s_bgMusic},
    {type:"sound", src:s_bgMusicOgg},
    {type:"sound", src:s_bgMusicCaf},

    {type:"sound", src:s_shootEffect},
    {type:"sound", src:s_shootEffectOgg},
    {type:"sound", src:s_shootEffectWav},
    */
    {fontName: "fontName", src: [{src: sJoystixFont, type: "truetype"}]},

    {type: "image", src: sSplashTeam},
	{type: "image", src: sSplashGame},
	{type: "image", src: sMenuTitle},

	{type: "image", src: ssGame},
    {type: "plist", src: ssGameList},

	{type: "image", src: sPacLife},
	{type: "image", src: sGameOver}

];<commit_msg>[pacman1][Cocos2D] Correct life image<commit_after>
//var dirSounds = "Sounds/";
var dirScreenShots = "res/screenshots/";
var dirImages = "res/images/";
var dirFonts = "res/fonts/";
var dirSpriteSheets = "res/spritesheets/";

/*

var s_bgMusic = dirSounds + "background-music.mp3";
var s_bgMusicOgg = dirSounds + "background-music.ogg";
var s_bgMusicCaf = dirSounds + "background-music.caf";

var s_shootEffect = dirSounds + "pew-pew-lei.mp3";
var s_shootEffectOgg = dirSounds + "pew-pew-lei.ogg";
var s_shootEffectWav = dirSounds + "pew-pew-lei.wav";
*/
var sJoystixFont = dirFonts + "Joystix.ttf";

var sSplashTeam = dirScreenShots + "splashTeam_800-480.png";
var sSplashGame = dirScreenShots + "splashGame_800-480.png";
var sMenuTitle = dirImages + "menuTitle_595-135.png";
var ssGame = dirSpriteSheets + "GameSpriteSheet.png";
var ssGameList = dirSpriteSheets + "GameSpriteSheet.plist";
var sPacLife = dirImages + "pac_left_middle_16-16.png";
var sGameOver = dirImages + "game_over_217-32.png";

var resource = [
    /*

    {type:"sound", src:s_bgMusic},
    {type:"sound", src:s_bgMusicOgg},
    {type:"sound", src:s_bgMusicCaf},

    {type:"sound", src:s_shootEffect},
    {type:"sound", src:s_shootEffectOgg},
    {type:"sound", src:s_shootEffectWav},
    */
    {fontName: "fontName", src: [{src: sJoystixFont, type: "truetype"}]},

    {type: "image", src: sSplashTeam},
	{type: "image", src: sSplashGame},
	{type: "image", src: sMenuTitle},

	{type: "image", src: ssGame},
    {type: "plist", src: ssGameList},

	{type: "image", src: sPacLife},
	{type: "image", src: sGameOver}

];<|endoftext|>


<commit_before>'use strict';

const ChildProcessError = require('../../error/ChildProcessError');

class SortWrapper
{
	/**
	 * @param {SortOptions} options
	 */
	constructor(options)
	{
		var sortCmd = options.path || 'sort';

		var argsHash = {
			'-u': !!options.unique,
			'-n': !!options.numeric,
			'-r': !!options.reverse,
			'-s': !!options.stable,
			'-m': !!options.merge,
			'-i': !!options.ignoreCase,
			'-R': !!options.sortByHash,
			'-T': options.tmpDir,
			'-S': options.bufferSize ? options.bufferSize + 'b' : null,
			'-t': options.separator,
			'--parallel': options.threads,
	//		'--compress-program': options.compress
		};

		const args = [];

		for (const opt in argsHash) {
			const optval = argsHash[opt];

			if (optval === null || optval === undefined || optval === false) {
				continue;
			}

			if (optval === true) {
				args.push(opt);
			} else {
				args.push(opt);
				args.push(optval.toString());
			}
		}

		for (const keydef of options.keys) {
			args.push('-k');
			args.push(keydef);
		}

		const p = this._runSimple(
			sortCmd,
			args
		);

		p.on('close', function(code, signal) {
			if (code !== 0) {
				throw new ChildProcessError(sortCmd, args, code, signal);
			}
		});

		this.process = p;
		this.stdin = p.stdin;
		this.stdout = p.stdout;
	}

	_runSimple(cmd, args)
	{
		const options = {
			stdio: [
				'pipe',
				'pipe',
				process.stderr
			],
			env: {
				LC_ALL: 'C'
			}
		};

		var p = require('child_process').spawn(
			cmd,
			args,
			options
		);

		return p;
	}
}

module.exports = SortWrapper;
<commit_msg>Make options.keys optional (sort whole line by default)<commit_after>'use strict';

const ChildProcessError = require('../../error/ChildProcessError');

class SortWrapper
{
	/**
	 * @param {SortOptions} options
	 */
	constructor(options)
	{
		var sortCmd = options.path || 'sort';

		var argsHash = {
			'-u': !!options.unique,
			'-n': !!options.numeric,
			'-r': !!options.reverse,
			'-s': !!options.stable,
			'-m': !!options.merge,
			'-i': !!options.ignoreCase,
			'-R': !!options.sortByHash,
			'-T': options.tmpDir,
			'-S': options.bufferSize ? options.bufferSize + 'b' : null,
			'-t': options.separator,
			'--parallel': options.threads,
	//		'--compress-program': options.compress
		};

		const args = [];

		for (const opt in argsHash) {
			const optval = argsHash[opt];

			if (optval === null || optval === undefined || optval === false) {
				continue;
			}

			if (optval === true) {
				args.push(opt);
			} else {
				args.push(opt);
				args.push(optval.toString());
			}
		}

		if (options.keys) {
			for (const keydef of options.keys) {
				args.push('-k');
				args.push(keydef);
			}
		}

		const p = this._runSimple(
			sortCmd,
			args
		);

		p.on('close', function(code, signal) {
			if (code !== 0) {
				throw new ChildProcessError(sortCmd, args, code, signal);
			}
		});

		this.process = p;
		this.stdin = p.stdin;
		this.stdout = p.stdout;
	}

	_runSimple(cmd, args)
	{
		const options = {
			stdio: [
				'pipe',
				'pipe',
				process.stderr
			],
			env: {
				LC_ALL: 'C'
			}
		};

		var p = require('child_process').spawn(
			cmd,
			args,
			options
		);

		return p;
	}
}

module.exports = SortWrapper;
<|endoftext|>


<commit_before>zk.$package("ganttz.resourceload");

ganttz.resourceload.ResourceLoadList = zk.$extends(zk.Widget,{});<commit_msg>Added class-methods setInstance and getIntance<commit_after>zk.$package("ganttz.resourceload");

ganttz.resourceload.ResourceLoadList = zk.$extends(zk.Widget,{
    $init : function(){
        this.$super('init');
        this.$class.setInstance(this);
    }
},{ //Class stuff
    setInstance : function(instance){
        this._instance = instance;
    },
    getInstance : function(){
        return this._instance;
    }
});<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.box',
  name: 'SessionReplyBox',
  extends: 'foam.box.ProxyBox',

  imports: [
    // 'requestLogin'
  ],

  methods: [
    {
      name: 'send',
      code: function send(msg) {
        // TODO: if I get an AuthException the call the requestLogin
        // handler then retry once it finishes.
        console.log('***** REPLY: ', foam.json.stringify(msg));
        this.delegate.send(msg);
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.box',
  name: 'SessionClientBox',
  extends: 'foam.box.ProxyBox',

  implements: [ 'foam.box.Box' ],

  requires: [ 'foam.box.SessionReplyBox' ],

  imports: [
    // 'requestLogin'
  ],

  constants: {
    SESSION_KEY: 'sessionId'
  },

  properties: [
    {
      class: 'String',
      name: 'sessionName',
      value: 'defaultSession'
    },
    {
      class: 'String',
      name: 'sessionID',
      factory: function() {
        return localStorage[this.sessionName] ||
            ( localStorage[this.sessionName] = foam.uuid.randomGUID() );
      }
    }
  ],

  methods: [
    {
      name: 'send',
      code: function send(msg) {
        msg.attributes[this.SESSION_KEY] = this.sessionID;

        console.log('***** SEND: ', foam.json.stringify(msg));

        msg.attributes.replyBox = this.SessionReplyBox.create({
          delegate: msg.attributes.replyBox
        });

        this.delegate.send(msg);
      }
    }
  ]
});
<commit_msg>Updates to SessionClientBox.<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.box',
  name: 'SessionReplyBox',
  extends: 'foam.box.ProxyBox',

  imports: [
    // 'requestLogin'
  ],

  properties: [
    'msg',
    'clientBox'
  ],

  methods: [
    {
      name: 'send',
      code: function send(msg) {
        // TODO: if I get an AuthException the call the requestLogin
        // handler then retry once it finishes.
        console.log('***** REPLY: ', foam.json.stringify(msg));
        this.delegate.send(msg);
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.box',
  name: 'SessionClientBox',
  extends: 'foam.box.ProxyBox',

  implements: [ 'foam.box.Box' ],

  requires: [ 'foam.box.SessionReplyBox' ],

  imports: [
    // 'requestLogin'
  ],

  constants: {
    SESSION_KEY: 'sessionId'
  },

  properties: [
    {
      class: 'String',
      name: 'sessionName',
      value: 'defaultSession'
    },
    {
      class: 'String',
      name: 'sessionID',
      factory: function() {
        return localStorage[this.sessionName] ||
            ( localStorage[this.sessionName] = foam.uuid.randomGUID() );
      }
    }
  ],

  methods: [
    {
      name: 'send',
      code: function send(msg) {
        msg.attributes[this.SESSION_KEY] = this.sessionID;

        console.log('***** SEND: ', foam.json.stringify(msg));

        msg.attributes.replyBox = this.SessionReplyBox.create({
          msg: msg,
          clientBox: this,
          delegate: msg.attributes.replyBox
        });

        this.delegate.send(msg);
      }
    }
  ]
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.graphics',
  name: 'ScrollCView',
  extends: 'foam.graphics.CView',

  properties: [
    {
      class: 'Float',
      name: 'width',
      value: 20
    },
    {
      class: 'Float',
      name: 'height',
      value: 100
    },
    {
      class: 'Boolean',
      name: 'vertical',
      value: true
    },
    {
      class: 'Int',
      name: 'value',
//      help: 'The first element being shown, starting at zero.',
      preSet: function(_, value) {
        return Math.max(0, Math.min(this.size-this.extent, value));
      },
      postSet: function(old, nu) {
        if ( old !== nu ) this.invalidated.pub();
      }
    },
    {
      class: 'Int',
      name: 'extent',
//      help: 'Number of elements shown.',
//      minValue: 1, // TODO: add back when minValue supported
      value: 10,
      postSet: function(old, nu) {
        if ( old !== nu ) this.invalidated.pub();
      }
    },
    {
      class: 'Int',
      name: 'size',
//      help: 'Total number of elements being scrolled through.',
      value: 0,
      postSet: function(old, size) {
        if ( old !== size ) this.invalidated.pub();
        // Trigger the preSet for value, so it stays within range.
        this.value = this.value;
      }
    },
    {
      class: 'Int',
      name: 'minHandleSize',
//      help: 'Minimum size to make the drag handle.'
      value: 10
    },
    {
      class: 'Float',
      name: 'handleSize',
      expression: function(minHandleSize, size, extent, height, innerBorder) {
        var h  = height - 2 * innerBorder;
        var hs = size > 0 ? extent * h / size : 0;

        return hs < minHandleSize ? minHandleSize : hs;
      }
    },
    {
      class: 'Int',
      name: 'innerBorder',
      value: 2
    },
    {
      class: 'String',
      name: 'handleColor',
      value: 'rgb(107,136,173)'
    },
    {
      class: 'String',
      name: 'borderColor',
      value: '#999'
    },
    {
      name: 'yMax',
      expression: function(height, innerBorder, handleSize)  {
        return height - innerBorder - handleSize;
      }
    },
    {
      name: 'rate',
      expression: function(size, extent, yMax, innerBorder) {
        return size ? ( yMax - innerBorder ) / (size - extent) : 0;
      }
    },
    'mouseEvent'
  ],

  methods: [
    function initCView() {
      this.onDetach(this.canvas.pointer.touch.sub(this.onTouch));

      var self = this;
      var mouseInput = this.canvas.pointer.mouseInput;
      this.onDetach(mouseInput.down.sub(function() {
        var moveSub = mouseInput.move.sub(function() {
          self.value = self.yToValue(mouseInput.y);
        });
        mouseInput.up.sub(function(s) {
          moveSub.detach();
          s.detach();
        });
      }));
    },

    function yToValue(y) {
      return ( y - this.innerBorder ) / this.rate;
    },

    function valueToY(value) {
      return value * this.rate + this.innerBorder;
    },

    function paintSelf(c) {
      if ( ! this.size ) return;

      if ( ! c ) return;

      if ( this.extent >= this.size ) return;

      c.strokeStyle = this.borderColor;
      c.lineWidth = 0.4;
      c.strokeRect(0, 0, this.width-7, this.height);

      c.fillStyle = this.handleColor;

      c.fillRect(
        2,
        this.valueToY(this.value),
        this.width - 11,
        this.handleSize);
    }
  ],

  listeners: [
    {
      name: 'onTouch',
      code: function(_, __, touch) {
        this.value = this.yToValue(touch.y);
        // prevents highlighting of other elements while scrolling
        touch.claimed = true;
      }
    },
    {
      name: 'updateScrollFromEvent',
      code: function(mouseEvent) {
        debugger;
        if ( ! mouseEvent || ! mouseEvent.src || ! mouseEvent.src.oldValue ) return;

        var p     = foam.graphics.Point.create();
        var event = mouseEvent.src.oldValue;

        p.x = event.clientX;
        p.y = event.clientY - this.canvas.el().getBoundingClientRect().top - (this.handleSize/2);
        p.w = 1;

        this.globalToLocalCoordinates(p);
        this.value = this.yToValue(p.y);
      }
    }
  ]
});
<commit_msg>Remove the mouseEvent property from ScrollCView.<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.graphics',
  name: 'ScrollCView',
  extends: 'foam.graphics.CView',

  properties: [
    {
      class: 'Float',
      name: 'width',
      value: 20
    },
    {
      class: 'Float',
      name: 'height',
      value: 100
    },
    {
      class: 'Boolean',
      name: 'vertical',
      value: true
    },
    {
      class: 'Int',
      name: 'value',
//      help: 'The first element being shown, starting at zero.',
      preSet: function(_, value) {
        return Math.max(0, Math.min(this.size-this.extent, value));
      },
      postSet: function(old, nu) {
        if ( old !== nu ) this.invalidated.pub();
      }
    },
    {
      class: 'Int',
      name: 'extent',
//      help: 'Number of elements shown.',
//      minValue: 1, // TODO: add back when minValue supported
      value: 10,
      postSet: function(old, nu) {
        if ( old !== nu ) this.invalidated.pub();
      }
    },
    {
      class: 'Int',
      name: 'size',
//      help: 'Total number of elements being scrolled through.',
      value: 0,
      postSet: function(old, size) {
        if ( old !== size ) this.invalidated.pub();
        // Trigger the preSet for value, so it stays within range.
        this.value = this.value;
      }
    },
    {
      class: 'Int',
      name: 'minHandleSize',
//      help: 'Minimum size to make the drag handle.'
      value: 10
    },
    {
      class: 'Float',
      name: 'handleSize',
      expression: function(minHandleSize, size, extent, height, innerBorder) {
        var h  = height - 2 * innerBorder;
        var hs = size > 0 ? extent * h / size : 0;

        return hs < minHandleSize ? minHandleSize : hs;
      }
    },
    {
      class: 'Int',
      name: 'innerBorder',
      value: 2
    },
    {
      class: 'String',
      name: 'handleColor',
      value: 'rgb(107,136,173)'
    },
    {
      class: 'String',
      name: 'borderColor',
      value: '#999'
    },
    {
      name: 'yMax',
      expression: function(height, innerBorder, handleSize)  {
        return height - innerBorder - handleSize;
      }
    },
    {
      name: 'rate',
      expression: function(size, extent, yMax, innerBorder) {
        return size ? ( yMax - innerBorder ) / (size - extent) : 0;
      }
    },
  ],

  methods: [
    function initCView() {
      this.onDetach(this.canvas.pointer.touch.sub(this.onTouch));

      var self = this;
      var mouseInput = this.canvas.pointer.mouseInput;
      this.onDetach(mouseInput.down.sub(function() {
        var moveSub = mouseInput.move.sub(function() {
          self.value = self.yToValue(mouseInput.y);
        });
        mouseInput.up.sub(function(s) {
          moveSub.detach();
          s.detach();
        });
      }));
    },

    function yToValue(y) {
      return ( y - this.innerBorder ) / this.rate;
    },

    function valueToY(value) {
      return value * this.rate + this.innerBorder;
    },

    function paintSelf(c) {
      if ( ! this.size ) return;

      if ( ! c ) return;

      if ( this.extent >= this.size ) return;

      c.strokeStyle = this.borderColor;
      c.lineWidth = 0.4;
      c.strokeRect(0, 0, this.width-7, this.height);

      c.fillStyle = this.handleColor;

      c.fillRect(
        2,
        this.valueToY(this.value),
        this.width - 11,
        this.handleSize);
    }
  ],

  listeners: [
    {
      name: 'onTouch',
      code: function(_, __, touch) {
        this.value = this.yToValue(touch.y);

        // prevents highlighting of other elements while scrolling
        touch.claimed = true;
      }
    },
  ]
});
<|endoftext|>


<commit_before>/*
Description:
Wide support, cutting edge where possible
*/

/*
Author:
Adam Silver
*/

var some;

if (Array.prototype.some) {
        some = function(arr, iterator, context) {
                return arr.some(iterator, context);
        };
} else {
        some = function(arr, iterator, context) {
                var i = 0, l = arr.length;

                context = context || arr;

                for( ; i < l; i++ ) {
                        if (iterator.call(context, arr[ i ], i, arr)) {
                                return true;
                        }
                }

                return false;
        };
}
<commit_msg>Inconsistency with - this - object<commit_after>/*
Description:
Wide support, cutting edge where possible
*/

/*
Author:
Adam Silver
*/

var some;

if (Array.prototype.some) {
        some = function(arr, iterator, context) {
                return arr.some(iterator, context);
        };
} else {
        some = function(arr, iterator, context) {
                var i = 0, l = arr.length;

                for( ; i < l; i++ ) {
                        if (iterator.call(context, arr[ i ], i, arr)) {
                                return true;
                        }
                }

                return false;
        };
}
<|endoftext|>


<commit_before>import * as THREE from 'three';
import gfxutils from '../gfxutils';

class TransformGroup extends THREE.Object3D {
  static _inverseMatrix = new THREE.Matrix4();

  static _ray = new THREE.Ray();

  constructor(geometry, geoParams, material, transforms) {
    super();
    this._geometry = geometry;
    this._geoParams = geoParams;
    const mat = material.createInstance();
    geoParams.initMaterial(mat);
    this._material = mat;
    this._transforms = transforms.length > 0 ? transforms : [new THREE.Matrix4()];
    const meshes = this._createMeshes(geometry);
    for (let i = 0, n = meshes.length; i < n; ++i) {
      this.add(meshes[i]);
    }
  }

  raycast(raycaster, intersects) {
    const ray = TransformGroup._ray;
    const inverseMatrix = TransformGroup._inverseMatrix;
    const { children } = this;
    ray.copy(raycaster.ray);
    for (let i = 0, n = children.length; i < n; ++i) {
      const child = children[i];

      if (!gfxutils.belongToSelectLayers(child)) {
        continue;
      }

      child.updateMatrixWorld();
      const mtx = child.matrixWorld;
      // TODO check near / far?
      inverseMatrix.getInverse(mtx);
      raycaster.ray.copy(ray).applyMatrix4(inverseMatrix);
      const childIntersects = [];
      this._geometry.raycast(raycaster, childIntersects);

      for (let j = 0, ciCount = childIntersects.length; j < ciCount; ++j) {
        const inters = childIntersects[j];
        if (inters.point) {
          inters.point.applyMatrix4(mtx);
          inters.distance = ray.origin.distanceTo(inters.point);
        }
        inters.object = child;
        // TODO: check raycaster near/far?
        intersects[intersects.length] = inters;
      }
    }
    raycaster.ray.copy(ray);
  }

  getSubset(chunkIndices) {
    const geos = this._geometry.getSubset(chunkIndices);
    const subset = [];
    let subIdx = 0;

    for (let i = 0, n = geos.length; i < n; ++i) {
      const meshes = this._createMeshes(geos[i]);
      for (let j = 0, meshCnt = meshes.length; j < meshCnt; ++j) {
        subset[subIdx++] = meshes[j];
      }
    }

    return subset;
  }

  _createMeshes(geometry) {
    const transforms = this._transforms;
    const Mesh = this._geoParams.Object;
    const material = this._material;
    const meshes = [];
    for (let i = 0, n = transforms.length; i < n; ++i) {
      const mesh = new Mesh(geometry, material);
      mesh.applyMatrix(transforms[i]);

      meshes[i] = mesh;
    }

    return meshes;
  }
}

export default TransformGroup;
<commit_msg>Remove outdated TODO - check is already done<commit_after>import * as THREE from 'three';
import gfxutils from '../gfxutils';

class TransformGroup extends THREE.Object3D {
  static _inverseMatrix = new THREE.Matrix4();

  static _ray = new THREE.Ray();

  constructor(geometry, geoParams, material, transforms) {
    super();
    this._geometry = geometry;
    this._geoParams = geoParams;
    const mat = material.createInstance();
    geoParams.initMaterial(mat);
    this._material = mat;
    this._transforms = transforms.length > 0 ? transforms : [new THREE.Matrix4()];
    const meshes = this._createMeshes(geometry);
    for (let i = 0, n = meshes.length; i < n; ++i) {
      this.add(meshes[i]);
    }
  }

  raycast(raycaster, intersects) {
    const ray = TransformGroup._ray;
    const inverseMatrix = TransformGroup._inverseMatrix;
    const { children } = this;
    ray.copy(raycaster.ray);
    for (let i = 0, n = children.length; i < n; ++i) {
      const child = children[i];

      if (!gfxutils.belongToSelectLayers(child)) {
        continue;
      }

      child.updateMatrixWorld();
      const mtx = child.matrixWorld;
      inverseMatrix.getInverse(mtx);
      raycaster.ray.copy(ray).applyMatrix4(inverseMatrix);
      const childIntersects = [];
      this._geometry.raycast(raycaster, childIntersects);

      for (let j = 0, ciCount = childIntersects.length; j < ciCount; ++j) {
        const inters = childIntersects[j];
        if (inters.point) {
          inters.point.applyMatrix4(mtx);
          inters.distance = ray.origin.distanceTo(inters.point);
        }
        inters.object = child;
        intersects[intersects.length] = inters;
      }
    }
    raycaster.ray.copy(ray);
  }

  getSubset(chunkIndices) {
    const geos = this._geometry.getSubset(chunkIndices);
    const subset = [];
    let subIdx = 0;

    for (let i = 0, n = geos.length; i < n; ++i) {
      const meshes = this._createMeshes(geos[i]);
      for (let j = 0, meshCnt = meshes.length; j < meshCnt; ++j) {
        subset[subIdx++] = meshes[j];
      }
    }

    return subset;
  }

  _createMeshes(geometry) {
    const transforms = this._transforms;
    const Mesh = this._geoParams.Object;
    const material = this._material;
    const meshes = [];
    for (let i = 0, n = transforms.length; i < n; ++i) {
      const mesh = new Mesh(geometry, material);
      mesh.applyMatrix(transforms[i]);

      meshes[i] = mesh;
    }

    return meshes;
  }
}

export default TransformGroup;
<|endoftext|>


<commit_before>$(function() {
	FastClick.attach(document.body);

	Phonepad.getInstance();
});
<commit_msg>withdaw fastclick from main.js<commit_after>$(function() {
	Phonepad.getInstance();
});
<|endoftext|>


<commit_before>'use strict';

var db                  = require('../db')
  , assign              = require('es5-ext/object/assign')
  , copy                = require('es5-ext/object/copy')
  , _                   = require('mano').i18n.bind('View: Statistics')
  , memoize             = require('memoizee')
  , location            = require('mano/lib/client/location')
  , setupQueryHandler   = require('../utils/setup-client-query-handler')
  , resolveFullStepPath = require('../utils/resolve-processing-step-full-path')
  , capitalize          = require('es5-ext/string/#/capitalize')
  , uncapitalize        = require('es5-ext/string/#/uncapitalize')
  , Duration            = require('duration')
  , getData             = require('mano/lib/client/xhr-driver').get
  , getQueryHandlerConf = require('../routes/utils/get-statistics-time-query-handler-conf')
  , ObjservableValue    = require('observable-value')
  , nextTick            = require('next-tick')
  , observableResult    = new ObjservableValue();

exports._servicesColors  = ["#673AB7", "#FFC107", "#FF4B4B", "#3366CC"];
exports._stepsColors     = ["#673AB7", "#FFC107", "#FF4B4B", "#3366CC"];
exports._customChartsDOM     = Function.prototype;
exports._customChartsGetData = Function.prototype;

exports._commonOptions = {
	colors: exports._servicesColors, // by default colors of the services
	animation: {
		startup: true,
		duration: 1200,
		easing: "in"
	},
	legend: { position: "bottom", maxLines: 3 },
	chartArea: { width: "100%", height: "75%" },
	height: 300,
	is3D: true,
	isStacked: true,
	titlePosition: "out",
	axisTitlesPosition: "in",
	vAxis: {
		textPosition: "in",
		viewWindow: { min: 0 },
		minValue: 0
	},
	width: "100%"
};

var queryServer = memoize(function (query) {
	return getData('/get-dashboard-data/', query);
}, {
	normalizer: function (args) { return JSON.stringify(args[0]); },
	max: 1000
});

var getServiceNames = function () {
	var services = {};

	db.BusinessProcess.extensions.forEach(function (BusinessProcessClass) {
		services[uncapitalize.call(BusinessProcessClass.__id__.slice('BusinessProcess'.length))] =
			{ label: BusinessProcessClass.prototype.label };
	});

	return services;
};

var dayRangeConfig = {
	31: 1,
	182: 7,
	365: 30,
	Infinity: 365
};

var getGroupByCount = function (dateFrom, dateTo) {
	var duration, groupBy;
	duration = new Duration(dateFrom, dateTo);

	Object.keys(dayRangeConfig).some(function (rangeKey) {
		if (duration.days <= rangeKey) {
			groupBy = dayRangeConfig[rangeKey];
			return true;
		}
	});

	return groupBy;
};

var getStepLabelByShortPath = function (processingStepsMeta) {
	return function (shortStepPath) {
		return db['BusinessProcess' +
			capitalize.call(processingStepsMeta[shortStepPath]._services[0])].prototype
			.processingSteps.map.getBySKeyPath(resolveFullStepPath(shortStepPath)).label;
	};
};

var getFilesCompletedPerDay = function (data) {
	var result = { handle: 'chart-files-completed-per-day' }, chart = {
		options: assign(copy(exports._commonOptions), {
			orientation: 'horizontal'
		}),
		data: [["Service"]]
	}, days = Object.keys(data.filesApprovedByDay),
		dateFrom, dateTo, dateFromStr, rowData, rangeKey, groupByCount,
		daysCount = 0, currentRange,
		setupRange, addAmountToRange, setupRowData;

	if (!days || !days.length) {
		result.data = null;
		return result;
	}
	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		chart.data[0].push(services[serviceName].label);
	});
	dateFrom = new Date(Date.parse(data.filesApprovedByDay.dateFrom));
	dateTo   = new Date(Date.parse(data.filesApprovedByDay.dateTo));
	groupByCount = getGroupByCount(dateFrom, dateTo);

	setupRange = function (currentRange) {
		Object.keys(services).forEach(function (serviceName) {
			currentRange.services[serviceName] = 0;
		});
	};

	addAmountToRange = function (currentRange, dateFromStr) {
		Object.keys(services).forEach(function (serviceName) {
			var amount;
			amount = data.filesApprovedByDay[dateFromStr][serviceName] || 0;
			currentRange.services[serviceName] += amount;
		});
	};

	setupRowData = function (currentRange, rowData) {
		Object.keys(currentRange.services).forEach(function (service) {
			rowData.push(currentRange.services[service] || 0);
		});
	};
	while (dateFrom <= dateTo) {
		daysCount++;
		dateFromStr = dateFrom.toISOString().slice(0, 10);
		if (!currentRange) {
			currentRange = { name: dateFrom.toLocaleDateString(db.locale), services: {} };
			setupRange(currentRange);
		}
		if (data.filesApprovedByDay[dateFromStr]) {
			addAmountToRange(currentRange, dateFromStr);
		}
		if ((daysCount % groupByCount === 0) || dateFrom.getTime() === dateTo.getTime()) {
			rangeKey = groupByCount === 1 ? currentRange.name : currentRange.name + ' - ' +
				dateFrom.toLocaleDateString(db.locale);
			rowData = [rangeKey];
			setupRowData(currentRange, rowData);
			chart.data.push(rowData);
			currentRange = null;
		}
		dateFrom.setUTCDate(dateFrom.getUTCDate() + 1);
	}

	return assign(result, chart);
};

var getFilesCompletedByStep = function (data) {
	var result = { handle: 'chart-files-completed-by-service' }, chart = {
		options: exports._commonOptions,
		data: [["Service"]]
	};
	if (!Object.keys(data.byStepAndService).length) {
		return result;
	}

	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		chart.data[0].push(services[serviceName].label);
	});
	Object.keys(data.byStepAndService).forEach(function (shortPath) {
		var stepData = [getStepLabelByShortPath(shortPath)];
		Object.keys(services).forEach(function (serviceName) {
			if (!data.byStepAndService[shortPath][serviceName]) {
				stepData.push(0);
				return;
			}
			stepData.push(data.byStepAndService[shortPath][serviceName].processed);
		});
		chart.data.push(stepData);
	});

	return assign(result, chart);
};

var getPendingFiles = function (data) {
	var result = { handle: 'chart-pending-files' }, chart = {
		options: assign(copy(exports._commonOptions), {
			colors: exports._stepsColors
		}),
		drawMethod: 'PieChart',
		data: [["Role", "Count"]]
	};

	if (!data.pendingFiles || !Object.keys(data.pendingFiles).length) {
		return result;
	}

	Object.keys(data.pendingFiles).forEach(function (shortPath) {
		chart.data.push([getStepLabelByShortPath(shortPath), data.pendingFiles[shortPath] || 0]);
	});

	return assign(result, chart);
};

var getAverageTime = function (data) {
	var result = { handle: 'chart-by-step-and-service' }, chart = {
		options: assign(copy(exports._commonOptions), {
			isStacked: false
		}),
		data: [["Role"]]
	};

	if (!data.byStepAndService || !Object.keys(data.byStepAndService).length) {
		return result;
	}
	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		chart.data[0].push(services[serviceName].label);
	});
	Object.keys(data.byStepAndService).forEach(function (shortPath) {
		if (shortPath === 'frontDesk') return;
		var stepData = [getStepLabelByShortPath(shortPath)];
		Object.keys(services).forEach(function (serviceName) {
			if (!data.byStepAndService[shortPath][serviceName]) {
				stepData.push(0);
				return;
			}
			stepData.push(
				Math.round(data.byStepAndService[shortPath][serviceName].avgTime / 1000 / 60 / 60 / 24)
			);
		});
		chart.data.push(stepData);
	});

	return assign(result, chart);
};

var getAverageTimeByService = function (data) {
	var result = { handle: 'chart-by-service' }, chart = {
		options: assign(copy(exports._commonOptions), {
			legend: null
		}),
		data: [["Service", "Data", { role: "style" }]]
	};

	if (!data.byService || !Object.keys(data.byService).length) {
		return result;
	}

	var services = getServiceNames(), i = 0;

	Object.keys(services).forEach(function (serviceName) {
		var row = [];
		row.push(services[serviceName].label);
		row.push(Math.round(
			(data.byService[serviceName] ? data.byService[serviceName].avgTime : 0) / 1000 / 60 / 60 / 24
		));
		row.push(chart.options.colors[i]);
		i++;
		chart.data.push(row);
	});

	return assign(result, chart);
};

var getWithdrawalTime = function (data) {
	var result = { handle: 'chart-withdrawal-time' }, chart = {
		options: assign(copy(exports._commonOptions), {
			isStacked: false,
			legend: null,
			axisTitlesPosition: "none"
		}),
		data: [["Service", "Data", { role: "style" }]]
	}, i = 0;

	if (!data.byStepAndService.frontDesk) {
		return result;
	}
	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		var row = [];
		row.push(services[serviceName].label);
		if (!data.byStepAndService.frontDesk[serviceName]) {
			row.push(0);
		} else {
			row.push(
				Math.round(data.byStepAndService.frontDesk[serviceName].avgTime / 1000 / 60 / 60 / 24)
			);
		}
		row.push(chart.options.colors[i]);
		i++;
		chart.data.push(row);
	});

	return assign(result, chart);
};

var updateChartsData = function (data) {
	var dataForCharts = [], customChartsData = [];
	if (!data) return;

	dataForCharts.push(getFilesCompletedPerDay(data));
	dataForCharts.push(getFilesCompletedByStep(data));
	dataForCharts.push(getPendingFiles(data));
	dataForCharts.push(getAverageTime(data));
	dataForCharts.push(getAverageTimeByService(data));
	dataForCharts.push(getWithdrawalTime(data));
	customChartsData = exports._customChartsGetData.call(this, data);
	if (customChartsData && customChartsData.length) {
		dataForCharts = dataForCharts.concat(customChartsData);
	}
	observableResult.value = dataForCharts;

	nextTick(function () {
		document.emit('statistics-chart-update');
	});
};

exports._parent = require('./statistics-base');

exports['dashboard-nav'] = { class: { 'pills-nav-active': true } };

exports['statistics-main'] = function () {
	var queryHandler;
	getStepLabelByShortPath = getStepLabelByShortPath(this.processingStepsMeta);

	queryHandler = setupQueryHandler(getQueryHandlerConf({
		db: db,
		processingStepsMeta: this.processingStepsMeta,
		queryConf: null
	}), location, '/');

	queryHandler.on('query', function (query) {
		if (query.dateFrom) {
			query.dateFrom = query.dateFrom.toJSON();
		}
		if (query.dateTo) {
			query.dateTo = query.dateTo.toJSON();
		}
		queryServer(query)(function (result) {
			updateChartsData(result);
		}).done();
	});

	section({ class: 'section-primary users-table-filter-bar' },
		form({ action: '/', autoSubmit: true },
			div(
				{ class: 'users-table-filter-bar-status' },
				label({ for: 'date-from-input' }, _("Date from"), ":"),
				input({ id: 'date-from-input', type: 'date',
					name: 'dateFrom', value: location.query.get('dateFrom') })
			),
			div(
				{ class: 'users-table-filter-bar-status' },
				label({ for: 'date-to-input' }, _("Date to"), ":"),
				input({ id: 'date-to-input', type: 'date',
					name: 'dateTo', value: location.query.get('dateTo') })
			),
			p({ class: 'submit' }, input({ type: 'submit' }))));

	section({ class: "section-primary" },
		h3(_("Files completed per time range")),
		div({ id: "chart-files-completed-per-day" }));
	section({ class: "section-primary" },
		h3(_("Processed files")),
		div({ id: "chart-files-completed-by-service" }));
	section({ class: "section-primary" }, h3(_("Pending files at ${ date }", {
		date: location.query.get('dateTo').map(function (dateTo) {
			var date = dateTo ? new db.Date(dateTo) : new db.Date();
			return date.toLocaleDateString(db.locale);
		})
	})),
		div({ id: "chart-pending-files" }));
	section({ class: "section-primary" },
		h3(_("Average processing time in days")),
		div({ id: "chart-by-step-and-service" }));
	section({ class: "section-primary" },
		h3(_("Total average processing time per service in days")),
		div({ id: "chart-by-service" }));
	section({ class: "section-primary" },
		h3(_("Withdrawal time in days")), div({ id: "chart-withdrawal-time" }));
	exports._customChartsDOM.call(this);

	script(function () {
		google.charts.load('current', { packages: ['corechart'] });
	});
	script(function (chartsData) {
		var reloadCharts = function () {
			google.charts.setOnLoadCallback(function () {
				if (!chartsData) return;
				chartsData.forEach(function (chart) {
					if (!chart.data) {
						$(chart.handle).innerHtml = '';
						return;
					}
					var googleChart =
						new google.visualization[chart.drawMethod || 'BarChart']($(chart.handle));
					googleChart.draw(google.visualization.arrayToDataTable(chart.data), chart.options);
				});
			});
		};
		reloadCharts();
		// this will be invoked only in SPA
		if (document.on) document.on('statistics-chart-update', reloadCharts);
	}, observableResult);
};
<commit_msg>-- reorder requires<commit_after>'use strict';

var assign              = require('es5-ext/object/assign')
  , copy                = require('es5-ext/object/copy')
  , capitalize          = require('es5-ext/string/#/capitalize')
  , uncapitalize        = require('es5-ext/string/#/uncapitalize')
  , Duration            = require('duration')
  , memoize             = require('memoizee')
  , ObservableValue     = require('observable-value')
  , nextTick            = require('next-tick')
  , _                   = require('mano').i18n.bind('View: Statistics')
  , location            = require('mano/lib/client/location')
  , getData             = require('mano/lib/client/xhr-driver').get
  , db                  = require('../db')
  , setupQueryHandler   = require('../utils/setup-client-query-handler')
  , resolveFullStepPath = require('../utils/resolve-processing-step-full-path')
  , getQueryHandlerConf = require('../routes/utils/get-statistics-time-query-handler-conf')

  , observableResult = new ObservableValue();

exports._servicesColors  = ["#673AB7", "#FFC107", "#FF4B4B", "#3366CC"];
exports._stepsColors     = ["#673AB7", "#FFC107", "#FF4B4B", "#3366CC"];
exports._customChartsDOM     = Function.prototype;
exports._customChartsGetData = Function.prototype;

exports._commonOptions = {
	colors: exports._servicesColors, // by default colors of the services
	animation: {
		startup: true,
		duration: 1200,
		easing: "in"
	},
	legend: { position: "bottom", maxLines: 3 },
	chartArea: { width: "100%", height: "75%" },
	height: 300,
	is3D: true,
	isStacked: true,
	titlePosition: "out",
	axisTitlesPosition: "in",
	vAxis: {
		textPosition: "in",
		viewWindow: { min: 0 },
		minValue: 0
	},
	width: "100%"
};

var queryServer = memoize(function (query) {
	return getData('/get-dashboard-data/', query);
}, {
	normalizer: function (args) { return JSON.stringify(args[0]); },
	max: 1000
});

var getServiceNames = function () {
	var services = {};

	db.BusinessProcess.extensions.forEach(function (BusinessProcessClass) {
		services[uncapitalize.call(BusinessProcessClass.__id__.slice('BusinessProcess'.length))] =
			{ label: BusinessProcessClass.prototype.label };
	});

	return services;
};

var dayRangeConfig = {
	31: 1,
	182: 7,
	365: 30,
	Infinity: 365
};

var getGroupByCount = function (dateFrom, dateTo) {
	var duration, groupBy;
	duration = new Duration(dateFrom, dateTo);

	Object.keys(dayRangeConfig).some(function (rangeKey) {
		if (duration.days <= rangeKey) {
			groupBy = dayRangeConfig[rangeKey];
			return true;
		}
	});

	return groupBy;
};

var getStepLabelByShortPath = function (processingStepsMeta) {
	return function (shortStepPath) {
		return db['BusinessProcess' +
			capitalize.call(processingStepsMeta[shortStepPath]._services[0])].prototype
			.processingSteps.map.getBySKeyPath(resolveFullStepPath(shortStepPath)).label;
	};
};

var getFilesCompletedPerDay = function (data) {
	var result = { handle: 'chart-files-completed-per-day' }, chart = {
		options: assign(copy(exports._commonOptions), {
			orientation: 'horizontal'
		}),
		data: [["Service"]]
	}, days = Object.keys(data.filesApprovedByDay),
		dateFrom, dateTo, dateFromStr, rowData, rangeKey, groupByCount,
		daysCount = 0, currentRange,
		setupRange, addAmountToRange, setupRowData;

	if (!days || !days.length) {
		result.data = null;
		return result;
	}
	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		chart.data[0].push(services[serviceName].label);
	});
	dateFrom = new Date(Date.parse(data.filesApprovedByDay.dateFrom));
	dateTo   = new Date(Date.parse(data.filesApprovedByDay.dateTo));
	groupByCount = getGroupByCount(dateFrom, dateTo);

	setupRange = function (currentRange) {
		Object.keys(services).forEach(function (serviceName) {
			currentRange.services[serviceName] = 0;
		});
	};

	addAmountToRange = function (currentRange, dateFromStr) {
		Object.keys(services).forEach(function (serviceName) {
			var amount;
			amount = data.filesApprovedByDay[dateFromStr][serviceName] || 0;
			currentRange.services[serviceName] += amount;
		});
	};

	setupRowData = function (currentRange, rowData) {
		Object.keys(currentRange.services).forEach(function (service) {
			rowData.push(currentRange.services[service] || 0);
		});
	};
	while (dateFrom <= dateTo) {
		daysCount++;
		dateFromStr = dateFrom.toISOString().slice(0, 10);
		if (!currentRange) {
			currentRange = { name: dateFrom.toLocaleDateString(db.locale), services: {} };
			setupRange(currentRange);
		}
		if (data.filesApprovedByDay[dateFromStr]) {
			addAmountToRange(currentRange, dateFromStr);
		}
		if ((daysCount % groupByCount === 0) || dateFrom.getTime() === dateTo.getTime()) {
			rangeKey = groupByCount === 1 ? currentRange.name : currentRange.name + ' - ' +
				dateFrom.toLocaleDateString(db.locale);
			rowData = [rangeKey];
			setupRowData(currentRange, rowData);
			chart.data.push(rowData);
			currentRange = null;
		}
		dateFrom.setUTCDate(dateFrom.getUTCDate() + 1);
	}

	return assign(result, chart);
};

var getFilesCompletedByStep = function (data) {
	var result = { handle: 'chart-files-completed-by-service' }, chart = {
		options: exports._commonOptions,
		data: [["Service"]]
	};
	if (!Object.keys(data.byStepAndService).length) {
		return result;
	}

	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		chart.data[0].push(services[serviceName].label);
	});
	Object.keys(data.byStepAndService).forEach(function (shortPath) {
		var stepData = [getStepLabelByShortPath(shortPath)];
		Object.keys(services).forEach(function (serviceName) {
			if (!data.byStepAndService[shortPath][serviceName]) {
				stepData.push(0);
				return;
			}
			stepData.push(data.byStepAndService[shortPath][serviceName].processed);
		});
		chart.data.push(stepData);
	});

	return assign(result, chart);
};

var getPendingFiles = function (data) {
	var result = { handle: 'chart-pending-files' }, chart = {
		options: assign(copy(exports._commonOptions), {
			colors: exports._stepsColors
		}),
		drawMethod: 'PieChart',
		data: [["Role", "Count"]]
	};

	if (!data.pendingFiles || !Object.keys(data.pendingFiles).length) {
		return result;
	}

	Object.keys(data.pendingFiles).forEach(function (shortPath) {
		chart.data.push([getStepLabelByShortPath(shortPath), data.pendingFiles[shortPath] || 0]);
	});

	return assign(result, chart);
};

var getAverageTime = function (data) {
	var result = { handle: 'chart-by-step-and-service' }, chart = {
		options: assign(copy(exports._commonOptions), {
			isStacked: false
		}),
		data: [["Role"]]
	};

	if (!data.byStepAndService || !Object.keys(data.byStepAndService).length) {
		return result;
	}
	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		chart.data[0].push(services[serviceName].label);
	});
	Object.keys(data.byStepAndService).forEach(function (shortPath) {
		if (shortPath === 'frontDesk') return;
		var stepData = [getStepLabelByShortPath(shortPath)];
		Object.keys(services).forEach(function (serviceName) {
			if (!data.byStepAndService[shortPath][serviceName]) {
				stepData.push(0);
				return;
			}
			stepData.push(
				Math.round(data.byStepAndService[shortPath][serviceName].avgTime / 1000 / 60 / 60 / 24)
			);
		});
		chart.data.push(stepData);
	});

	return assign(result, chart);
};

var getAverageTimeByService = function (data) {
	var result = { handle: 'chart-by-service' }, chart = {
		options: assign(copy(exports._commonOptions), {
			legend: null
		}),
		data: [["Service", "Data", { role: "style" }]]
	};

	if (!data.byService || !Object.keys(data.byService).length) {
		return result;
	}

	var services = getServiceNames(), i = 0;

	Object.keys(services).forEach(function (serviceName) {
		var row = [];
		row.push(services[serviceName].label);
		row.push(Math.round(
			(data.byService[serviceName] ? data.byService[serviceName].avgTime : 0) / 1000 / 60 / 60 / 24
		));
		row.push(chart.options.colors[i]);
		i++;
		chart.data.push(row);
	});

	return assign(result, chart);
};

var getWithdrawalTime = function (data) {
	var result = { handle: 'chart-withdrawal-time' }, chart = {
		options: assign(copy(exports._commonOptions), {
			isStacked: false,
			legend: null,
			axisTitlesPosition: "none"
		}),
		data: [["Service", "Data", { role: "style" }]]
	}, i = 0;

	if (!data.byStepAndService.frontDesk) {
		return result;
	}
	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		var row = [];
		row.push(services[serviceName].label);
		if (!data.byStepAndService.frontDesk[serviceName]) {
			row.push(0);
		} else {
			row.push(
				Math.round(data.byStepAndService.frontDesk[serviceName].avgTime / 1000 / 60 / 60 / 24)
			);
		}
		row.push(chart.options.colors[i]);
		i++;
		chart.data.push(row);
	});

	return assign(result, chart);
};

var updateChartsData = function (data) {
	var dataForCharts = [], customChartsData = [];
	if (!data) return;

	dataForCharts.push(getFilesCompletedPerDay(data));
	dataForCharts.push(getFilesCompletedByStep(data));
	dataForCharts.push(getPendingFiles(data));
	dataForCharts.push(getAverageTime(data));
	dataForCharts.push(getAverageTimeByService(data));
	dataForCharts.push(getWithdrawalTime(data));
	customChartsData = exports._customChartsGetData.call(this, data);
	if (customChartsData && customChartsData.length) {
		dataForCharts = dataForCharts.concat(customChartsData);
	}
	observableResult.value = dataForCharts;

	nextTick(function () {
		document.emit('statistics-chart-update');
	});
};

exports._parent = require('./statistics-base');

exports['dashboard-nav'] = { class: { 'pills-nav-active': true } };

exports['statistics-main'] = function () {
	var queryHandler;
	getStepLabelByShortPath = getStepLabelByShortPath(this.processingStepsMeta);

	queryHandler = setupQueryHandler(getQueryHandlerConf({
		db: db,
		processingStepsMeta: this.processingStepsMeta,
		queryConf: null
	}), location, '/');

	queryHandler.on('query', function (query) {
		if (query.dateFrom) {
			query.dateFrom = query.dateFrom.toJSON();
		}
		if (query.dateTo) {
			query.dateTo = query.dateTo.toJSON();
		}
		queryServer(query)(function (result) {
			updateChartsData(result);
		}).done();
	});

	section({ class: 'section-primary users-table-filter-bar' },
		form({ action: '/', autoSubmit: true },
			div(
				{ class: 'users-table-filter-bar-status' },
				label({ for: 'date-from-input' }, _("Date from"), ":"),
				input({ id: 'date-from-input', type: 'date',
					name: 'dateFrom', value: location.query.get('dateFrom') })
			),
			div(
				{ class: 'users-table-filter-bar-status' },
				label({ for: 'date-to-input' }, _("Date to"), ":"),
				input({ id: 'date-to-input', type: 'date',
					name: 'dateTo', value: location.query.get('dateTo') })
			),
			p({ class: 'submit' }, input({ type: 'submit' }))));

	section({ class: "section-primary" },
		h3(_("Files completed per time range")),
		div({ id: "chart-files-completed-per-day" }));
	section({ class: "section-primary" },
		h3(_("Processed files")),
		div({ id: "chart-files-completed-by-service" }));
	section({ class: "section-primary" }, h3(_("Pending files at ${ date }", {
		date: location.query.get('dateTo').map(function (dateTo) {
			var date = dateTo ? new db.Date(dateTo) : new db.Date();
			return date.toLocaleDateString(db.locale);
		})
	})),
		div({ id: "chart-pending-files" }));
	section({ class: "section-primary" },
		h3(_("Average processing time in days")),
		div({ id: "chart-by-step-and-service" }));
	section({ class: "section-primary" },
		h3(_("Total average processing time per service in days")),
		div({ id: "chart-by-service" }));
	section({ class: "section-primary" },
		h3(_("Withdrawal time in days")), div({ id: "chart-withdrawal-time" }));
	exports._customChartsDOM.call(this);

	script(function () {
		google.charts.load('current', { packages: ['corechart'] });
	});
	script(function (chartsData) {
		var reloadCharts = function () {
			google.charts.setOnLoadCallback(function () {
				if (!chartsData) return;
				chartsData.forEach(function (chart) {
					if (!chart.data) {
						$(chart.handle).innerHtml = '';
						return;
					}
					var googleChart =
						new google.visualization[chart.drawMethod || 'BarChart']($(chart.handle));
					googleChart.draw(google.visualization.arrayToDataTable(chart.data), chart.options);
				});
			});
		};
		reloadCharts();
		// this will be invoked only in SPA
		if (document.on) document.on('statistics-chart-update', reloadCharts);
	}, observableResult);
};
<|endoftext|>


<commit_before>angular.module('ionic-datepicker.provider', [])

  .provider('ionicDatePicker', function () {

    var config = {
      titleLabel: null,
      setLabel: 'Set',
      todayLabel: 'Today',
      closeLabel: 'Close',
      inputDate: new Date(),
      mondayFirst: true,
      weeksList: ["S", "M", "T", "W", "T", "F", "S"],
      monthsList: ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"],
      templateType: 'popup',
      showTodayButton: false,
      closeOnSelect: false,
      disableWeekdays: []
    };

    this.configDatePicker = function (inputObj) {
      angular.extend(config, inputObj);
    };

    this.$get = ['$rootScope', '$ionicPopup', '$ionicModal', 'IonicDatepickerService', function ($rootScope, $ionicPopup, $ionicModal, IonicDatepickerService) {

      var provider = {};

      var $scope = $rootScope.$new();
      $scope.today = resetHMSM(new Date()).getTime();
      $scope.disabledDates = [];
      $scope.data = {};

      //Reset the hours, minutes, seconds and milli seconds
      function resetHMSM(currentDate) {
        currentDate.setHours(0);
        currentDate.setMinutes(0);
        currentDate.setSeconds(0);
        currentDate.setMilliseconds(0);
        return currentDate;
      }

      //Previous month
      $scope.prevMonth = function () {
        if ($scope.currentDate.getMonth() === 1) {
          $scope.currentDate.setFullYear($scope.currentDate.getFullYear());
        }
        $scope.currentDate.setMonth($scope.currentDate.getMonth() - 1);
        $scope.data.currentMonth = $scope.mainObj.monthsList[$scope.currentDate.getMonth()];
        $scope.data.currentYear = $scope.currentDate.getFullYear();
        refreshDateList($scope.currentDate);
      };

      //Next month
      $scope.nextMonth = function () {
        if ($scope.currentDate.getMonth() === 11) {
          $scope.currentDate.setFullYear($scope.currentDate.getFullYear());
        }
        $scope.currentDate.setDate(1);
        $scope.currentDate.setMonth($scope.currentDate.getMonth() + 1);
        $scope.data.currentMonth = $scope.mainObj.monthsList[$scope.currentDate.getMonth()];
        $scope.data.currentYear = $scope.currentDate.getFullYear();
        refreshDateList($scope.currentDate);
      };

      //Date selected
      $scope.dateSelected = function (selectedDate) {
        if (!selectedDate || Object.keys(selectedDate).length === 0) return;
        $scope.selctedDateEpoch = selectedDate.epoch;

        if ($scope.mainObj.closeOnSelect) {
          $scope.mainObj.callback($scope.selctedDateEpoch);
          if ($scope.mainObj.templateType.toLowerCase() == 'popup') {
            $scope.popup.close();
          } else {
            closeModal();
          }
        }
      };

      //Set today as date for the modal
      $scope.setIonicDatePickerTodayDate = function () {
        var today = new Date();
        refreshDateList(new Date());
        $scope.selctedDateEpoch = resetHMSM(today).getTime();
        if ($scope.mainObj.closeOnSelect) {
          $scope.mainObj.callback($scope.selctedDateEpoch);
          closeModal();
        }
      };

      //Set date for the modal
      $scope.setIonicDatePickerDate = function () {
        $scope.mainObj.callback($scope.selctedDateEpoch);
        closeModal();
      };

      //Setting the disabled dates list.
      function setDisabledDates(mainObj) {
        if (!mainObj.disabledDates || mainObj.disabledDates.length === 0) {
          $scope.disabledDates = [];
        } else {
          $scope.disabledDates = [];
          angular.forEach(mainObj.disabledDates, function (val, key) {
            val = resetHMSM(new Date(val));
            $scope.disabledDates.push(val.getTime());
          });
        }
      }

      //Refresh the list of the dates of a month
      function refreshDateList(currentDate) {
        currentDate = resetHMSM(currentDate);
        $scope.currentDate = angular.copy(currentDate);

        var firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1).getDate();
        var lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0).getDate();

        $scope.monthsList = [];
        if ($scope.mainObj.monthsList && $scope.mainObj.monthsList.length === 12) {
          $scope.monthsList = $scope.mainObj.monthsList;
        } else {
          $scope.monthsList = IonicDatepickerService.monthsList;
        }

        $scope.yearsList = IonicDatepickerService.getYearsList($scope.mainObj.from, $scope.mainObj.to);

        $scope.dayList = [];

        var tempDate, disabled;
        $scope.firstDayEpoch = resetHMSM(new Date(currentDate.getFullYear(), currentDate.getMonth(), firstDay)).getTime();
        $scope.lastDayEpoch = resetHMSM(new Date(currentDate.getFullYear(), currentDate.getMonth(), lastDay)).getTime();

        for (var i = firstDay; i <= lastDay; i++) {
          tempDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), i);
          disabled = (tempDate.getTime() < $scope.fromDate) || (tempDate.getTime() > $scope.toDate) || $scope.mainObj.disableWeekdays.indexOf(tempDate.getDay()) >= 0;

          $scope.dayList.push({
            date: tempDate.getDate(),
            month: tempDate.getMonth(),
            year: tempDate.getFullYear(),
            day: tempDate.getDay(),
            epoch: tempDate.getTime(),
            disabled: disabled
          });
        }

        //To set Monday as the first day of the week.
        var firstDayMonday = $scope.dayList[0].day - $scope.mainObj.mondayFirst;
        firstDayMonday = (firstDayMonday < 0) ? 6 : firstDayMonday;

        for (var j = 0; j < firstDayMonday; j++) {
          $scope.dayList.unshift({});
        }

        $scope.rows = [0, 7, 14, 21, 28, 35];
        $scope.cols = [0, 1, 2, 3, 4, 5, 6];

        $scope.data.currentMonth = $scope.mainObj.monthsList[currentDate.getMonth()];
        $scope.data.currentYear = currentDate.getFullYear();
        $scope.data.currentMonthSelected = angular.copy($scope.data.currentMonth);
        $scope.currentYearSelected = angular.copy($scope.data.currentYear);
        $scope.numColumns = 7;
      }

      //Month changed
      $scope.monthChanged = function (month) {
        var monthNumber = $scope.monthsList.indexOf(month);
        $scope.currentDate.setMonth(monthNumber);
        refreshDateList($scope.currentDate);
      };

      //Year changed
      $scope.yearChanged = function (year) {
        $scope.currentDate.setFullYear(year);
        refreshDateList($scope.currentDate);
      };

      //Setting up the initial object
      function setInitialObj(ipObj) {
        $scope.mainObj = angular.copy(ipObj);
        $scope.selctedDateEpoch = resetHMSM($scope.mainObj.inputDate).getTime();

        if ($scope.mainObj.weeksList && $scope.mainObj.weeksList.length === 7) {
          $scope.weeksList = $scope.mainObj.weeksList;
        } else {
          $scope.weeksList = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
        }
        if ($scope.mainObj.mondayFirst) {
          $scope.weeksList.push($scope.mainObj.weeksList.shift());
        }
        $scope.disableWeekdays = $scope.mainObj.disableWeekdays;

        refreshDateList($scope.mainObj.inputDate);
        setDisabledDates($scope.mainObj);
      }

      $ionicModal.fromTemplateUrl('ionic-datepicker-modal.html', {
        scope: $scope,
        animation: 'slide-in-up'
      }).then(function (modal) {
        $scope.modal = modal;
      });

      $scope.$on('$destroy', function () {
        $scope.modal.remove();
      });

      function openModal() {
        $scope.modal.show();
      }

      function closeModal() {
        $scope.modal.hide();
      }

      $scope.closeIonicDatePickerModal = function () {
        closeModal();
      };

      //Open datepicker popup
      provider.openDatePicker = function (ipObj) {
        var buttons = [];
        delete $scope.fromDate;
        delete $scope.toDate;

        $scope.mainObj = angular.extend({}, config, ipObj);
        if ($scope.mainObj.from) {
          $scope.fromDate = resetHMSM(new Date($scope.mainObj.from)).getTime();
        }
        if ($scope.mainObj.to) {
          $scope.toDate = resetHMSM(new Date($scope.mainObj.to)).getTime();
        }

        if (ipObj.disableWeekdays && config.disableWeekdays) {
          $scope.mainObj.disableWeekdays = ipObj.disableWeekdays.concat(config.disableWeekdays);
        }
        setInitialObj($scope.mainObj);

        if (!$scope.mainObj.closeOnSelect) {
          buttons = [{
            text: $scope.mainObj.setLabel,
            type: 'button_set',
            onTap: function (e) {
              $scope.mainObj.callback($scope.selctedDateEpoch);
            }
          }];
        }

        if ($scope.mainObj.showTodayButton) {
          buttons.push({
            text: $scope.mainObj.todayLabel,
            type: 'button_today',
            onTap: function (e) {
              var today = new Date();
              refreshDateList(new Date());
              $scope.selctedDateEpoch = resetHMSM(today).getTime();
              if (!$scope.mainObj.closeOnSelect) {
                e.preventDefault();
              }
            }
          });
        }

        buttons.push({
          text: $scope.mainObj.closeLabel,
          type: 'button_close',
          onTap: function (e) {
            console.log('ionic-datepicker popup closed.');
          }
        });

        if ($scope.mainObj.templateType.toLowerCase() == 'popup') {
          $scope.popup = $ionicPopup.show({
            templateUrl: 'ionic-datepicker-popup.html',
            scope: $scope,
            cssClass: 'ionic_datepicker_popup',
            buttons: buttons
          });
        } else {
          openModal();
        }
      };

      return provider;

    }];

  });
<commit_msg>Fix today button<commit_after>angular.module('ionic-datepicker.provider', [])

  .provider('ionicDatePicker', function () {

    var config = {
      titleLabel: null,
      setLabel: 'Set',
      todayLabel: 'Today',
      closeLabel: 'Close',
      inputDate: new Date(),
      mondayFirst: true,
      weeksList: ["S", "M", "T", "W", "T", "F", "S"],
      monthsList: ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"],
      templateType: 'popup',
      showTodayButton: false,
      closeOnSelect: false,
      disableWeekdays: []
    };

    this.configDatePicker = function (inputObj) {
      angular.extend(config, inputObj);
    };

    this.$get = ['$rootScope', '$ionicPopup', '$ionicModal', 'IonicDatepickerService', function ($rootScope, $ionicPopup, $ionicModal, IonicDatepickerService) {

      var provider = {};

      var $scope = $rootScope.$new();
      $scope.today = resetHMSM(new Date()).getTime();
      $scope.disabledDates = [];
      $scope.data = {};

      //Reset the hours, minutes, seconds and milli seconds
      function resetHMSM(currentDate) {
        currentDate.setHours(0);
        currentDate.setMinutes(0);
        currentDate.setSeconds(0);
        currentDate.setMilliseconds(0);
        return currentDate;
      }

      //Previous month
      $scope.prevMonth = function () {
        if ($scope.currentDate.getMonth() === 1) {
          $scope.currentDate.setFullYear($scope.currentDate.getFullYear());
        }
        $scope.currentDate.setMonth($scope.currentDate.getMonth() - 1);
        $scope.data.currentMonth = $scope.mainObj.monthsList[$scope.currentDate.getMonth()];
        $scope.data.currentYear = $scope.currentDate.getFullYear();
        refreshDateList($scope.currentDate);
      };

      //Next month
      $scope.nextMonth = function () {
        if ($scope.currentDate.getMonth() === 11) {
          $scope.currentDate.setFullYear($scope.currentDate.getFullYear());
        }
        $scope.currentDate.setDate(1);
        $scope.currentDate.setMonth($scope.currentDate.getMonth() + 1);
        $scope.data.currentMonth = $scope.mainObj.monthsList[$scope.currentDate.getMonth()];
        $scope.data.currentYear = $scope.currentDate.getFullYear();
        refreshDateList($scope.currentDate);
      };

      //Date selected
      $scope.dateSelected = function (selectedDate) {
        if (!selectedDate || Object.keys(selectedDate).length === 0) return;
        $scope.selctedDateEpoch = selectedDate.epoch;

        if ($scope.mainObj.closeOnSelect) {
          $scope.mainObj.callback($scope.selctedDateEpoch);
          if ($scope.mainObj.templateType.toLowerCase() == 'popup') {
            $scope.popup.close();
          } else {
            closeModal();
          }
        }
      };

      //Set today as date for the modal
      $scope.setIonicDatePickerTodayDate = function () {
        $scope.dateSelected($scope.today);
      };

      //Set date for the modal
      $scope.setIonicDatePickerDate = function () {
        $scope.mainObj.callback($scope.selctedDateEpoch);
        closeModal();
      };

      //Setting the disabled dates list.
      function setDisabledDates(mainObj) {
        if (!mainObj.disabledDates || mainObj.disabledDates.length === 0) {
          $scope.disabledDates = [];
        } else {
          $scope.disabledDates = [];
          angular.forEach(mainObj.disabledDates, function (val, key) {
            val = resetHMSM(new Date(val));
            $scope.disabledDates.push(val.getTime());
          });
        }
      }

      //Refresh the list of the dates of a month
      function refreshDateList(currentDate) {
        currentDate = resetHMSM(currentDate);
        $scope.currentDate = angular.copy(currentDate);

        var firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1).getDate();
        var lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0).getDate();

        $scope.monthsList = [];
        if ($scope.mainObj.monthsList && $scope.mainObj.monthsList.length === 12) {
          $scope.monthsList = $scope.mainObj.monthsList;
        } else {
          $scope.monthsList = IonicDatepickerService.monthsList;
        }

        $scope.yearsList = IonicDatepickerService.getYearsList($scope.mainObj.from, $scope.mainObj.to);

        $scope.dayList = [];

        var tempDate, disabled;
        $scope.firstDayEpoch = resetHMSM(new Date(currentDate.getFullYear(), currentDate.getMonth(), firstDay)).getTime();
        $scope.lastDayEpoch = resetHMSM(new Date(currentDate.getFullYear(), currentDate.getMonth(), lastDay)).getTime();

        for (var i = firstDay; i <= lastDay; i++) {
          tempDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), i);
          disabled = (tempDate.getTime() < $scope.fromDate) || (tempDate.getTime() > $scope.toDate) || $scope.mainObj.disableWeekdays.indexOf(tempDate.getDay()) >= 0;

          $scope.dayList.push({
            date: tempDate.getDate(),
            month: tempDate.getMonth(),
            year: tempDate.getFullYear(),
            day: tempDate.getDay(),
            epoch: tempDate.getTime(),
            disabled: disabled
          });
        }

        //To set Monday as the first day of the week.
        var firstDayMonday = $scope.dayList[0].day - $scope.mainObj.mondayFirst;
        firstDayMonday = (firstDayMonday < 0) ? 6 : firstDayMonday;

        for (var j = 0; j < firstDayMonday; j++) {
          $scope.dayList.unshift({});
        }

        $scope.rows = [0, 7, 14, 21, 28, 35];
        $scope.cols = [0, 1, 2, 3, 4, 5, 6];

        $scope.data.currentMonth = $scope.mainObj.monthsList[currentDate.getMonth()];
        $scope.data.currentYear = currentDate.getFullYear();
        $scope.data.currentMonthSelected = angular.copy($scope.data.currentMonth);
        $scope.currentYearSelected = angular.copy($scope.data.currentYear);
        $scope.numColumns = 7;
      }

      //Month changed
      $scope.monthChanged = function (month) {
        var monthNumber = $scope.monthsList.indexOf(month);
        $scope.currentDate.setMonth(monthNumber);
        refreshDateList($scope.currentDate);
      };

      //Year changed
      $scope.yearChanged = function (year) {
        $scope.currentDate.setFullYear(year);
        refreshDateList($scope.currentDate);
      };

      //Setting up the initial object
      function setInitialObj(ipObj) {
        $scope.mainObj = angular.copy(ipObj);
        $scope.selctedDateEpoch = resetHMSM($scope.mainObj.inputDate).getTime();

        if ($scope.mainObj.weeksList && $scope.mainObj.weeksList.length === 7) {
          $scope.weeksList = $scope.mainObj.weeksList;
        } else {
          $scope.weeksList = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
        }
        if ($scope.mainObj.mondayFirst) {
          $scope.weeksList.push($scope.mainObj.weeksList.shift());
        }
        $scope.disableWeekdays = $scope.mainObj.disableWeekdays;

        refreshDateList($scope.mainObj.inputDate);
        setDisabledDates($scope.mainObj);
      }

      $ionicModal.fromTemplateUrl('ionic-datepicker-modal.html', {
        scope: $scope,
        animation: 'slide-in-up'
      }).then(function (modal) {
        $scope.modal = modal;
      });

      $scope.$on('$destroy', function () {
        $scope.modal.remove();
      });

      function openModal() {
        $scope.modal.show();
      }

      function closeModal() {
        $scope.modal.hide();
      }

      $scope.closeIonicDatePickerModal = function () {
        closeModal();
      };

      //Open datepicker popup
      provider.openDatePicker = function (ipObj) {
        var buttons = [];
        delete $scope.fromDate;
        delete $scope.toDate;

        $scope.mainObj = angular.extend({}, config, ipObj);
        if ($scope.mainObj.from) {
          $scope.fromDate = resetHMSM(new Date($scope.mainObj.from)).getTime();
        }
        if ($scope.mainObj.to) {
          $scope.toDate = resetHMSM(new Date($scope.mainObj.to)).getTime();
        }

        if (ipObj.disableWeekdays && config.disableWeekdays) {
          $scope.mainObj.disableWeekdays = ipObj.disableWeekdays.concat(config.disableWeekdays);
        }
        setInitialObj($scope.mainObj);

        if (!$scope.mainObj.closeOnSelect) {
          buttons = [{
            text: $scope.mainObj.setLabel,
            type: 'button_set',
            onTap: function (e) {
              $scope.mainObj.callback($scope.selctedDateEpoch);
            }
          }];
        }

        if ($scope.mainObj.showTodayButton) {
          buttons.push({
            text: $scope.mainObj.todayLabel,
            type: 'button_today',
            onTap: function (e) {
              var today = new Date($scope.today);
              var today_obj = {
                date: today.getDate(),
                month: today.getMonth(),
                year: today.getFullYear(),
                day: today.getDay(),
                epoch: today.getTime(),
                disabled: false
              };
              $scope.dateSelected(today_obj);
            }
          });
        }

        buttons.push({
          text: $scope.mainObj.closeLabel,
          type: 'button_close',
          onTap: function (e) {
            console.log('ionic-datepicker popup closed.');
          }
        });

        if ($scope.mainObj.templateType.toLowerCase() == 'popup') {
          $scope.popup = $ionicPopup.show({
            templateUrl: 'ionic-datepicker-popup.html',
            scope: $scope,
            cssClass: 'ionic_datepicker_popup',
            buttons: buttons
          });
        } else {
          openModal();
        }
      };

      return provider;

    }];

  });
<|endoftext|>


<commit_before>var SettingsUserView = Ember.View.extend({
    currentUser: Ember.computed.alias('controller.session.user'),

    isNotOwnProfile: Ember.computed('controller.user.id', 'currentUser.id', function () {
        return this.get('controller.user.id') !== this.get('currentUser.id');
    }),

    isNotOwnersProfile: Ember.computed.not('controller.user.isOwner'),

    canAssignRoles: Ember.computed.or('currentUser.isAdmin', 'currentUser.isOwner'),

    canMakeOwner: Ember.computed.and('currentUser.isOwner', 'isNotOwnProfile', 'controller.user.isAdmin'),

    rolesDropdownIsVisible: Ember.computed.and('isNotOwnProfile', 'canAssignRoles', 'isNotOwnersProfile'),

    deleteUserActionIsVisible: Ember.computed('currentUser', 'canAssignRoles', 'controller.user', function () {
        if ((this.get('canAssignRoles') && this.get('isNotOwnProfile') && !this.get('controller.user.isOwner')) ||
            (this.get('currentUser.isEditor') && (!this.get('isNotOwnProfile') ||
            this.get('controller.user.isAuthor')))) {
            return true;
        }
    }),

    userActionsAreVisible: Ember.computed.or('deleteUserActionIsVisible', 'canMakeOwner')

});

export default SettingsUserView;
<commit_msg>Fixing logic for editors deleting themselves<commit_after>var SettingsUserView = Ember.View.extend({
    currentUser: Ember.computed.alias('controller.session.user'),

    isNotOwnProfile: Ember.computed('controller.user.id', 'currentUser.id', function () {
        return this.get('controller.user.id') !== this.get('currentUser.id');
    }),

    isNotOwnersProfile: Ember.computed.not('controller.user.isOwner'),

    canAssignRoles: Ember.computed.or('currentUser.isAdmin', 'currentUser.isOwner'),

    canMakeOwner: Ember.computed.and('currentUser.isOwner', 'isNotOwnProfile', 'controller.user.isAdmin'),

    rolesDropdownIsVisible: Ember.computed.and('isNotOwnProfile', 'canAssignRoles', 'isNotOwnersProfile'),

    deleteUserActionIsVisible: Ember.computed('currentUser', 'canAssignRoles', 'controller.user', function () {
        if ((this.get('canAssignRoles') && this.get('isNotOwnProfile') && !this.get('controller.user.isOwner')) ||
            (this.get('currentUser.isEditor') && (this.get('isNotOwnProfile') ||
            this.get('controller.user.isAuthor')))) {
            return true;
        }
    }),

    userActionsAreVisible: Ember.computed.or('deleteUserActionIsVisible', 'canMakeOwner')

});

export default SettingsUserView;
<|endoftext|>