<commit_before>(function(UI) {

    "use strict";

    UI.component('tab', {

        defaults: {
            'target'    : '>li:not(.uk-tab-responsive, .uk-disabled)',
            'connect'   : false,
            'active'    : 0,
            'animation' : false,
            'duration'  : 200
        },

        boot: function() {

            // init code
            UI.ready(function(context) {

                UI.$("[data-uk-tab]", context).each(function() {

                    var tab = UI.$(this);

                    if (!tab.data("tab")) {
                        var obj = UI.tab(tab, UI.Utils.options(tab.attr("data-uk-tab")));
                    }
                });
            });
        },

        init: function() {

            var $this = this;

            this.on("click.uikit.tab", this.options.target, function(e) {
                e.preventDefault();

                if ($this.switcher && $this.switcher.animating) {
                    return;
                }

                var current = $this.find($this.options.target).not(this);

                current.removeClass("uk-active").blur();
                $this.trigger("change.uk.tab", [UI.$(this).addClass("uk-active")]);

                // Update ARIA
                if (!$this.options.connect) {
                    current.attr('aria-expanded', 'false');
                    UI.$(this).attr('aria-expanded', 'true');
                }
            });

            if (this.options.connect) {
                this.connect = UI.$(this.options.connect);
            }

            // init responsive tab
            this.responsivetab = UI.$('

').append('

');

            this.responsivetab.dropdown = this.responsivetab.find('.uk-dropdown');
            this.responsivetab.lst      = this.responsivetab.dropdown.find('ul');
            this.responsivetab.caption  = this.responsivetab.find('a:first');

            if (this.element.hasClass("uk-tab-bottom")) this.responsivetab.dropdown.addClass("uk-dropdown-up");

            // handle click
            this.responsivetab.lst.on('click.uikit.tab', 'a', function(e) {

                e.preventDefault();
                e.stopPropagation();

                var link = UI.$(this);

                $this.element.children(':not(.uk-tab-responsive)').eq(link.data('index')).trigger('click');
            });

            this.on('show.uk.switcher change.uk.tab', function(e, tab) {
                $this.responsivetab.caption.html(tab.text());
            });

            this.element.append(this.responsivetab);

            // init UIkit components
            if (this.options.connect) {
                this.switcher = UI.switcher(this.element, {
                    "toggle"    : ">li:not(.uk-tab-responsive)",
                    "connect"   : this.options.connect,
                    "active"    : this.options.active,
                    "animation" : this.options.animation,
                    "duration"  : this.options.duration
                });
            }

            UI.dropdown(this.responsivetab, {"mode": "click"});

            // init
            $this.trigger("change.uk.tab", [this.element.find(this.options.target).filter('.uk-active')]);

            this.check();

            UI.$win.on('resize orientationchange', UI.Utils.debounce(function(){
                if ($this.element.is(":visible"))  $this.check();
            }, 100));

            this.on('display.uk.check', function(){
                if ($this.element.is(":visible"))  $this.check();
            });
        },

        check: function() {

            var children = this.element.children(':not(.uk-tab-responsive)').removeClass('uk-hidden');

            if (!children.length) return;

            var top          = (children.eq(0).offset().top + Math.ceil(children.eq(0).height()/2)),
                doresponsive = false,
                item, link;

            this.responsivetab.lst.empty();

            children.each(function(){

                if (UI.$(this).offset().top > top) {
                    doresponsive = true;
                }
            });

            if (doresponsive) {

                for (var i = 0; i < children.length; i++) {

                    item = UI.$(children.eq(i));
                    link = item.find('a');

                    if (item.css('float') != 'none' && !item.attr('uk-dropdown')) {

                        item.addClass('uk-hidden');

                        if (!item.hasClass('uk-disabled')) {
                            this.responsivetab.lst.append('
'+link.html()+'
');
                        }
                    }
                }
            }

            this.responsivetab[this.responsivetab.lst.children().length ? 'removeClass':'addClass']('uk-hidden');
        }
    });

})(UIkit);
<commit_msg>Fixes #896<commit_after>(function(UI) {

    "use strict";

    UI.component('tab', {

        defaults: {
            'target'    : '>li:not(.uk-tab-responsive, .uk-disabled)',
            'connect'   : false,
            'active'    : 0,
            'animation' : false,
            'duration'  : 200
        },

        boot: function() {

            // init code
            UI.ready(function(context) {

                UI.$("[data-uk-tab]", context).each(function() {

                    var tab = UI.$(this);

                    if (!tab.data("tab")) {
                        var obj = UI.tab(tab, UI.Utils.options(tab.attr("data-uk-tab")));
                    }
                });
            });
        },

        init: function() {

            var $this = this;

            this.current = false;

            this.on("click.uikit.tab", this.options.target, function(e) {

                e.preventDefault();

                if ($this.switcher && $this.switcher.animating) {
                    return;
                }

                var current = $this.find($this.options.target).not(this);

                current.removeClass("uk-active").blur();

                $this.trigger("change.uk.tab", [UI.$(this).addClass("uk-active"), $this.current]);

                $this.current = UI.$(this);

                // Update ARIA
                if (!$this.options.connect) {
                    current.attr('aria-expanded', 'false');
                    UI.$(this).attr('aria-expanded', 'true');
                }
            });

            if (this.options.connect) {
                this.connect = UI.$(this.options.connect);
            }

            // init responsive tab
            this.responsivetab = UI.$('

').append('

');

            this.responsivetab.dropdown = this.responsivetab.find('.uk-dropdown');
            this.responsivetab.lst      = this.responsivetab.dropdown.find('ul');
            this.responsivetab.caption  = this.responsivetab.find('a:first');

            if (this.element.hasClass("uk-tab-bottom")) this.responsivetab.dropdown.addClass("uk-dropdown-up");

            // handle click
            this.responsivetab.lst.on('click.uikit.tab', 'a', function(e) {

                e.preventDefault();
                e.stopPropagation();

                var link = UI.$(this);

                $this.element.children(':not(.uk-tab-responsive)').eq(link.data('index')).trigger('click');
            });

            this.on('show.uk.switcher change.uk.tab', function(e, tab) {
                $this.responsivetab.caption.html(tab.text());
            });

            this.element.append(this.responsivetab);

            // init UIkit components
            if (this.options.connect) {
                this.switcher = UI.switcher(this.element, {
                    "toggle"    : ">li:not(.uk-tab-responsive)",
                    "connect"   : this.options.connect,
                    "active"    : this.options.active,
                    "animation" : this.options.animation,
                    "duration"  : this.options.duration
                });
            }

            UI.dropdown(this.responsivetab, {"mode": "click"});

            // init
            $this.trigger("change.uk.tab", [this.element.find(this.options.target).filter('.uk-active')]);

            this.check();

            UI.$win.on('resize orientationchange', UI.Utils.debounce(function(){
                if ($this.element.is(":visible"))  $this.check();
            }, 100));

            this.on('display.uk.check', function(){
                if ($this.element.is(":visible"))  $this.check();
            });
        },

        check: function() {

            var children = this.element.children(':not(.uk-tab-responsive)').removeClass('uk-hidden');

            if (!children.length) return;

            var top          = (children.eq(0).offset().top + Math.ceil(children.eq(0).height()/2)),
                doresponsive = false,
                item, link;

            this.responsivetab.lst.empty();

            children.each(function(){

                if (UI.$(this).offset().top > top) {
                    doresponsive = true;
                }
            });

            if (doresponsive) {

                for (var i = 0; i < children.length; i++) {

                    item = UI.$(children.eq(i));
                    link = item.find('a');

                    if (item.css('float') != 'none' && !item.attr('uk-dropdown')) {

                        item.addClass('uk-hidden');

                        if (!item.hasClass('uk-disabled')) {
                            this.responsivetab.lst.append('
'+link.html()+'
');
                        }
                    }
                }
            }

            this.responsivetab[this.responsivetab.lst.children().length ? 'removeClass':'addClass']('uk-hidden');
        }
    });

})(UIkit);
<|endoftext|>


<commit_before>var emberize = function (object) {
    for (var i in object) {
        if (object.hasOwnProperty(i)) {
            if (Ember.typeOf(object[i]) == 'object') {
                object[i] = emberize(object[i]);
            }
        }
    }
    return Em.Object.create(object);
};

Ember.Model.reopen({
    _requestedLoadableProps: function () {
        return [];
    }.property().readOnly()
});

Ember.Model.reopenClass({

    makeLoadableProp: function (propName, restFunc, transformFunc) {
        var fakePropName = '_' + propName;
        return Ember.computed(fakePropName, function (key, value) {
            if (arguments.length >= 2) {
                this.set(fakePropName, value);
                return value;
            }

            if (typeof this.get(Em.get(this.constructor, 'primaryKey')) === "undefined") {
                return undefined;
            }

            if (!this.get("_requestedLoadableProps").contains(propName)) {
                var that = this;

                this.get("_requestedLoadableProps").addObject(propName);
                this.callRestOnObject(restFunc).then(function (res) {
                    if (transformFunc) {
                        res = transformFunc(res);
                    } else if (res && typeof res == 'object') {
                        res = emberize(res);
                    }
                    that.set(fakePropName, res);
                    //that.notifyPropertyChange(propName);
                });
            }

            return this.get(fakePropName);

        });
    },

    makeLoadableArrayProp: function (propName, restFunc, transformFunc) {
        var fakePropName = '_' + propName;
        return Ember.computed(fakePropName + '.[]', function (key, value) {
            if (arguments.length >= 2) {
                this.set(fakePropName, value);
                return value;
            }

            if (!this.get("_requestedLoadableProps").contains(propName)) {
                this.get("_requestedLoadableProps").addObject(propName);

                this.set(fakePropName, []);
                var that = this;
                this.callRestOnObject(restFunc).then(function (data) {
                    var d = [];
                    if (transformFunc) {
                        data.forEach(function (item, i) {
                            d.push(transformFunc(i, item));
                        });
                    } else {
                        d = data;
                    }

                    that.get(fakePropName).addObjects(d.sort(function (a, b) {
                        return a.id - b.id;
                    }));
                });
            }
            return this.get(fakePropName);
        });
    }
});

Ember.Model.reopen({
    reloadProp: function (propName) {
        this.get("_requestedLoadableProps").removeObject(propName);
        var that = this;
        var p = new Em.RSVP.Promise(function (resolve, reject) {
            var t = setTimeout(reject, 500);
            var f = function () {
                clearTimeout(t);
                that.removeObserver(propName, that, f);
                resolve(that.get(propName));
            };
            that.addObserver(propName, that, f);
        });

        that.notifyPropertyChange(propName);
        return p;
    }
});
<commit_msg>fix deprecated getter and setter syntax<commit_after>var emberize = function (object) {
    for (var i in object) {
        if (object.hasOwnProperty(i)) {
            if (Ember.typeOf(object[i]) == 'object') {
                object[i] = emberize(object[i]);
            }
        }
    }
    return Em.Object.create(object);
};

Ember.Model.reopen({
    _requestedLoadableProps: function () {
        return [];
    }.property().readOnly()
});

Ember.Model.reopenClass({

    makeLoadableProp: function (propName, restFunc, transformFunc) {
        var fakePropName = '_' + propName;
        return Ember.computed(fakePropName, {
            get: function(){
                if (typeof this.get(Em.get(this.constructor, 'primaryKey')) === "undefined") {
                    return undefined;
                }

                if (!this.get("_requestedLoadableProps").contains(propName)) {
                    var that = this;

                    this.get("_requestedLoadableProps").addObject(propName);
                    this.callRestOnObject(restFunc).then(function (res) {
                        if (transformFunc) {
                            res = transformFunc(res);
                        } else if (res && typeof res == 'object') {
                            res = emberize(res);
                        }
                        that.set(fakePropName, res);
                        //that.notifyPropertyChange(propName);
                    });
                }

                return this.get(fakePropName);
            },
            set: function(key, value){
                this.set(fakePropName, value);
                return value;
            }
        });
    },

    makeLoadableArrayProp: function (propName, restFunc, transformFunc) {
        var fakePropName = '_' + propName;

        return Ember.computed(fakePropName + '.[]', {
            get: function(){
                if (!this.get("_requestedLoadableProps").contains(propName)) {
                    this.get("_requestedLoadableProps").addObject(propName);

                    this.set(fakePropName, []);
                    var that = this;
                    this.callRestOnObject(restFunc).then(function (data) {
                        var d = [];
                        if (transformFunc) {
                            data.forEach(function (item, i) {
                                d.push(transformFunc(i, item));
                            });
                        } else {
                            d = data;
                        }

                        that.get(fakePropName).addObjects(d.sort(function (a, b) {
                            return a.id - b.id;
                        }));
                    });
                }
                return this.get(fakePropName);
            },
            set: function (key, value) {
                this.set(fakePropName, value);
                return value;
            }
        });
    }
});

Ember.Model.reopen({
    reloadProp: function (propName) {
        this.get("_requestedLoadableProps").removeObject(propName);
        var that = this;
        var p = new Em.RSVP.Promise(function (resolve, reject) {
            var t = setTimeout(reject, 500);
            var f = function () {
                clearTimeout(t);
                that.removeObserver(propName, that, f);
                resolve(that.get(propName));
            };
            that.addObserver(propName, that, f);
        });

        that.notifyPropertyChange(propName);
        return p;
    }
});
<|endoftext|>


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

foam.CLASS({
  package: 'foam.nanos.logger',
  name: 'AbstractLogger',
  implements: [ 'foam.nanos.logger.Logger' ],

  abstract: true,

  javaImports: [
    'java.io.PrintWriter',
    'java.io.StringWriter',
    'java.io.Writer',
    'java.text.SimpleDateFormat'
  ],

  axioms: [
    {
      name: 'javaExtras',
      buildJavaClass: function(cls) {
        cls.extras.push(foam.java.Code.create({
          data:
`protected static final ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {
  @Override
  protected SimpleDateFormat initialValue() {
    return new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss.Z");
  }
};

protected ThreadLocal<StringBuilder> sb = new ThreadLocal<StringBuilder>() {
  @Override
  protected StringBuilder initialValue() {
    return new StringBuilder();
  }

  @Override
  public StringBuilder get() {
    StringBuilder b = super.get();
    b.setLength(0);
    return b;
  }
};`
        }))
      }
    }
  ],

  methods: [
    {
      name: 'formatArg',
      args: [
        {
          name: 'obj',
          javaType: 'Object'
        }
      ],
      javaReturns: 'String',
      javaCode:
`if ( obj instanceof Throwable ) {
  Throwable   t  = (Throwable) obj;
  Writer      w  = new StringWriter();
  PrintWriter pw = new PrintWriter(w);

  t.printStackTrace(pw);

  return w.toString();
}

return String.valueOf(obj);`
    },
    {
      name: 'combine',
      args: [
        {
          name: 'args',
          javaType: 'Object[]'
        }
      ],
      javaReturns: 'String',
      javaCode:
      `StringBuilder str = sb.get();
for ( Object n : args ) {
  str.append(',');
  str.append(formatArg(n));
}
return str.toString();`
    }
  ]
});
<commit_msg>Correct millisecond SimpleDateFormat specifier.<commit_after>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.logger',
  name: 'AbstractLogger',
  implements: [ 'foam.nanos.logger.Logger' ],

  abstract: true,

  javaImports: [
    'java.io.PrintWriter',
    'java.io.StringWriter',
    'java.io.Writer',
    'java.text.SimpleDateFormat'
  ],

  axioms: [
    {
      name: 'javaExtras',
      buildJavaClass: function(cls) {
        cls.extras.push(foam.java.Code.create({
          data:
`protected static final ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {
  @Override
  protected SimpleDateFormat initialValue() {
    return new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss.SSS");
  }
};

protected ThreadLocal<StringBuilder> sb = new ThreadLocal<StringBuilder>() {
  @Override
  protected StringBuilder initialValue() {
    return new StringBuilder();
  }

  @Override
  public StringBuilder get() {
    StringBuilder b = super.get();
    b.setLength(0);
    return b;
  }
};`
        }))
      }
    }
  ],

  methods: [
    {
      name: 'formatArg',
      args: [
        {
          name: 'obj',
          javaType: 'Object'
        }
      ],
      javaReturns: 'String',
      javaCode:
`if ( obj instanceof Throwable ) {
  Throwable   t  = (Throwable) obj;
  Writer      w  = new StringWriter();
  PrintWriter pw = new PrintWriter(w);

  t.printStackTrace(pw);

  return w.toString();
}

return String.valueOf(obj);`
    },
    {
      name: 'combine',
      args: [
        {
          name: 'args',
          javaType: 'Object[]'
        }
      ],
      javaReturns: 'String',
      javaCode:
      `StringBuilder str = sb.get();
for ( Object n : args ) {
  str.append(',');
  str.append(formatArg(n));
}
return str.toString();`
    }
  ]
});
<|endoftext|>


<commit_before>(function( undefined ) {
	"use strict";

	/**
	 * Please make note of the following conventions:
	 * 1. Function-scope local variables must be prefixed with a single underscore.
	 *    This indicates a temporary variable.
	 * 2. Private variables that are persisted onto publicly accessible entities must be prefixed with two underscores.
	 *    This indicates a publicly visible, private variable.
	 *    Hiding private variables, by using closures, is discouraged.
	 *    Modifying these values from outside of absync is discouraged, but should be respected whenever possible.
	 */

	angular
		.module( "absync" )
		.provider( "absync", getAbsyncProvider );

	/**
	 * Retrieves the absync provider.
	 * @param {angular.auto.IProvideService|Object} $provide The $provide provider
	 * @param {Function} absyncCache The AbsyncCache service constructor.
	 * @ngInject
	 */
	function getAbsyncProvider( $provide, absyncCache ) {
		return new AbsyncProvider( $provide, absyncCache );
	}

	/**
	 * Retrieves the absync provider.
	 * @param {angular.auto.IProvideService|Object} $provide The $provide provider
	 * @param {Function} absyncCache The AbsyncCache service constructor.
	 * @constructor
	 */
	function AbsyncProvider( $provide, absyncCache ) {
		var _absyncProvider = this;

		// Store a reference to the provide provider.
		_absyncProvider.__provide = $provide;
		// Store a reference to the cache service constructor.
		_absyncProvider.__absyncCache = absyncCache;

		// A reference to the socket.io instance we're using to receive updates from the server.
		_absyncProvider.__ioSocket = null;
		// We usually register event listeners on the socket.io instance right away.
		// If socket.io was not connected when a service was constructed, we put the registration request
		// into this array and register it as soon as socket.io is configured.
		_absyncProvider.__registerLater = [];

		// The collections that absync provides.
		// The keys are the names of the collections, the value contains the constructor of
		// the respective cache service.
		_absyncProvider.__collections = {};
	}

	/**
	 * Register the configurator on the provider itself to allow early configuration during setup phase.
	 * It is recommended to configure absync within a configuration phase of a module.
	 * @param {io.Socket|Function|Object} configuration The socket.io instance to use.
	 * Can also be a constructor for a socket.
	 * Can also be an object with a "socket" member that provides either of the above.
	 */
	AbsyncProvider.prototype.configure = function AbsyncProvider$configure( configuration ) {
		var _absyncProvider = this;

		// If the configuration has a "socket" member, unpack it.
		//noinspection JSUnresolvedVariable
		var socket = configuration.socket || configuration;
		// Determine if the socket is an io.Socket.
		//noinspection JSUnresolvedVariable
		var isSocket = io && io.Socket && socket instanceof io.Socket;

		if( typeof socket == "function" ) {
			// Expect the passed socket to be a constructor.
			_absyncProvider.__ioSocket = socket();

		} else if( isSocket ) {
			// Expect the passed socket to be an io.Socket instance.
			_absyncProvider.__ioSocket = socket;

		} else {
			throw new Error( "configure() expects input to be a function or a socket.io Socket instance." );
		}

		// Check if services already tried to register listeners, if so, register them now.
		// This can happen when a service was constructed before absync was configured.
		if( _absyncProvider.__registerLater.length ) {
			_absyncProvider.__registerLater.forEach( _absyncProvider.__registerListener );
			_absyncProvider.__registerLater = [];
		}
	};

	AbsyncProvider.prototype.__registerListener = function AbsyncProvider$__registerListener( listener ) {
		var _absyncProvider = this;
		_absyncProvider.__handleEntityEvent( listener.eventName, listener.callback );
	};

	//TODO: Remove this noinspection when WebStorm 11 is available.
	//noinspection JSValidateJSDoc
	/**
	 * Request a new synchronized collection.
	 * This only registers the intent to use that collection. It will be constructed when it is first used.
	 * @param {String} name The name of the collection and service name.
	 * @param {AbsyncServiceConfiguration|Object} configuration The configuration for this collection.
	 */
	AbsyncProvider.prototype.collection = function AbsyncProvider$collection( name, configuration ) {
		var _absyncProvider = this;

		// Collection names (and, thus service names) have to be unique.
		// We can't create multiple services with the same name.
		if( _absyncProvider.__collections[ name ] ) {
			throw new Error( "A collection with the name '" + name + "' was already requested. Names for collections must be unique." );
		}

		// Register the service configuration.
		// __absyncCache will return a constructor for a service with the given configuration.
		_absyncProvider.__collections[ name ] = _absyncProvider.__absyncCache( name, configuration );

		// Register the new service.
		// Yes, we want an Angular "service" here, because we want it constructed with "new".
		_absyncProvider.__provide.service( name, _absyncProvider.__collections[ name ] );
	};

	//noinspection JSUnusedGlobalSymbols
	/**
	 * Register the service factory.
	 * @returns {AbsyncService}
	 * @ngInject
	 */
	AbsyncProvider.prototype.$get = function AbsyncProvider$$get() {
		return new AbsyncService( this );
	};

	/**
	 * The service that is received when injecting "absync".
	 * This service is primarily used internally to set up the connection between socket.io and the individual
	 * caching services.
	 * @param {AbsyncProvider|Object} parentProvider The AbsyncProvider that provides this service.
	 * @constructor
	 */
	function AbsyncService( parentProvider ) {
		this.__absyncProvider = parentProvider;
	}

	/**
	 * Configure the socket.io connection for absync.
	 * This configuration of absync should usually be performed through the absyncProvider in the configuration
	 * phase of a module.
	 * @param {io.Socket|Function|Object} configuration The socket.io instance to use.
	 */
	AbsyncService.prototype.configure = function AbsyncService$configure( configuration ) {
		var _absyncProvider = this.__absyncProvider;
		_absyncProvider.configure( configuration );
	};

	/**
	 * Register an event listener that is called when a specific entity is received on the websocket.
	 * @param {String} eventName The event name, usually the name of the entity.
	 * @param {Function} callback The function to call when the entity is received.
	 * @return {Function|null} If the listener could be registered, it returns a function that, when called, removes
	 * the event listener.
	 * If the listener registration was delayed, null is returned.
	 */
	AbsyncService.prototype.on = function AbsyncService$on( eventName, callback ) {
		var _absyncProvider = this.__absyncProvider;
		var _absyncService = this;

		// If we have no configured socket.io connection yet, remember to register it later.
		if( !_absyncProvider.__ioSocket ) {

			if( _absyncProvider.__registerLater.length > 9999 ) {
				// Be defensive, something is probably not right here.
				return null;
			}

			// TODO: Use promises here, so that we can always return the event listener removal function.
			_absyncProvider.__registerLater.push( {
				eventName : eventName,
				callback  : callback
			} );
			return null;
		}

		return _absyncService.__handleEntityEvent( eventName, callback );
	};

	/**
	 * Register an event listener on the websocket.
	 * @param {String} eventName The event name, usually the name of the entity.
	 * @param {Function} callback The function to call when the entity is received.
	 * @returns {Function}
	 */
	AbsyncService.prototype.__handleEntityEvent = function AbsyncService$__handleEntityEvent( eventName, callback ) {
		var _absyncProvider = this.__absyncProvider;

		// Register the callback with socket.io.
		_absyncProvider.__ioSocket.on( eventName, callback );

		// Return a function that removes the listener.
		return function removeListener() {
			_absyncProvider.__ioSocket.removeListener( eventName, callback );
		};
	};

	/**
	 * Convenience method to allow the user to emit() from the websocket.
	 * This is not utilized in absync internally.
	 * @param {String} eventName
	 * @param {*} data
	 * @param {Function} [callback]
	 */
	AbsyncService.prototype.emit = function AbsyncService$emit( eventName, data, callback ) {
		var _absyncProvider = this.__absyncProvider;

		if( !_absyncProvider.__ioSocket ) {
			throw new Error( "socket.io is not initialized." );
		}

		_absyncProvider.__ioSocket.emit( eventName, data, function afterEmit() {
			if( callback ) {
				callback.apply( _absyncProvider.__ioSocket, arguments );
			}
		} );
	};
}());
<commit_msg>[TASK] Use base2 upper limit in in range check<commit_after>(function( undefined ) {
	"use strict";

	/**
	 * Please make note of the following conventions:
	 * 1. Function-scope local variables must be prefixed with a single underscore.
	 *    This indicates a temporary variable.
	 * 2. Private variables that are persisted onto publicly accessible entities must be prefixed with two underscores.
	 *    This indicates a publicly visible, private variable.
	 *    Hiding private variables, by using closures, is discouraged.
	 *    Modifying these values from outside of absync is discouraged, but should be respected whenever possible.
	 */

	angular
		.module( "absync" )
		.provider( "absync", getAbsyncProvider );

	/**
	 * Retrieves the absync provider.
	 * @param {angular.auto.IProvideService|Object} $provide The $provide provider
	 * @param {Function} absyncCache The AbsyncCache service constructor.
	 * @ngInject
	 */
	function getAbsyncProvider( $provide, absyncCache ) {
		return new AbsyncProvider( $provide, absyncCache );
	}

	/**
	 * Retrieves the absync provider.
	 * @param {angular.auto.IProvideService|Object} $provide The $provide provider
	 * @param {Function} absyncCache The AbsyncCache service constructor.
	 * @constructor
	 */
	function AbsyncProvider( $provide, absyncCache ) {
		var _absyncProvider = this;

		// Store a reference to the provide provider.
		_absyncProvider.__provide = $provide;
		// Store a reference to the cache service constructor.
		_absyncProvider.__absyncCache = absyncCache;

		// A reference to the socket.io instance we're using to receive updates from the server.
		_absyncProvider.__ioSocket = null;
		// We usually register event listeners on the socket.io instance right away.
		// If socket.io was not connected when a service was constructed, we put the registration request
		// into this array and register it as soon as socket.io is configured.
		_absyncProvider.__registerLater = [];

		// The collections that absync provides.
		// The keys are the names of the collections, the value contains the constructor of
		// the respective cache service.
		_absyncProvider.__collections = {};
	}

	/**
	 * Register the configurator on the provider itself to allow early configuration during setup phase.
	 * It is recommended to configure absync within a configuration phase of a module.
	 * @param {io.Socket|Function|Object} configuration The socket.io instance to use.
	 * Can also be a constructor for a socket.
	 * Can also be an object with a "socket" member that provides either of the above.
	 */
	AbsyncProvider.prototype.configure = function AbsyncProvider$configure( configuration ) {
		var _absyncProvider = this;

		// If the configuration has a "socket" member, unpack it.
		//noinspection JSUnresolvedVariable
		var socket = configuration.socket || configuration;
		// Determine if the socket is an io.Socket.
		//noinspection JSUnresolvedVariable
		var isSocket = io && io.Socket && socket instanceof io.Socket;

		if( typeof socket == "function" ) {
			// Expect the passed socket to be a constructor.
			_absyncProvider.__ioSocket = socket();

		} else if( isSocket ) {
			// Expect the passed socket to be an io.Socket instance.
			_absyncProvider.__ioSocket = socket;

		} else {
			throw new Error( "configure() expects input to be a function or a socket.io Socket instance." );
		}

		// Check if services already tried to register listeners, if so, register them now.
		// This can happen when a service was constructed before absync was configured.
		if( _absyncProvider.__registerLater.length ) {
			_absyncProvider.__registerLater.forEach( _absyncProvider.__registerListener );
			_absyncProvider.__registerLater = [];
		}
	};

	AbsyncProvider.prototype.__registerListener = function AbsyncProvider$__registerListener( listener ) {
		var _absyncProvider = this;
		_absyncProvider.__handleEntityEvent( listener.eventName, listener.callback );
	};

	//TODO: Remove this noinspection when WebStorm 11 is available.
	//noinspection JSValidateJSDoc
	/**
	 * Request a new synchronized collection.
	 * This only registers the intent to use that collection. It will be constructed when it is first used.
	 * @param {String} name The name of the collection and service name.
	 * @param {AbsyncServiceConfiguration|Object} configuration The configuration for this collection.
	 */
	AbsyncProvider.prototype.collection = function AbsyncProvider$collection( name, configuration ) {
		var _absyncProvider = this;

		// Collection names (and, thus service names) have to be unique.
		// We can't create multiple services with the same name.
		if( _absyncProvider.__collections[ name ] ) {
			throw new Error( "A collection with the name '" + name + "' was already requested. Names for collections must be unique." );
		}

		// Register the service configuration.
		// __absyncCache will return a constructor for a service with the given configuration.
		_absyncProvider.__collections[ name ] = _absyncProvider.__absyncCache( name, configuration );

		// Register the new service.
		// Yes, we want an Angular "service" here, because we want it constructed with "new".
		_absyncProvider.__provide.service( name, _absyncProvider.__collections[ name ] );
	};

	//noinspection JSUnusedGlobalSymbols
	/**
	 * Register the service factory.
	 * @returns {AbsyncService}
	 * @ngInject
	 */
	AbsyncProvider.prototype.$get = function AbsyncProvider$$get() {
		return new AbsyncService( this );
	};

	/**
	 * The service that is received when injecting "absync".
	 * This service is primarily used internally to set up the connection between socket.io and the individual
	 * caching services.
	 * @param {AbsyncProvider|Object} parentProvider The AbsyncProvider that provides this service.
	 * @constructor
	 */
	function AbsyncService( parentProvider ) {
		this.__absyncProvider = parentProvider;
	}

	/**
	 * Configure the socket.io connection for absync.
	 * This configuration of absync should usually be performed through the absyncProvider in the configuration
	 * phase of a module.
	 * @param {io.Socket|Function|Object} configuration The socket.io instance to use.
	 */
	AbsyncService.prototype.configure = function AbsyncService$configure( configuration ) {
		var _absyncProvider = this.__absyncProvider;
		_absyncProvider.configure( configuration );
	};

	/**
	 * Register an event listener that is called when a specific entity is received on the websocket.
	 * @param {String} eventName The event name, usually the name of the entity.
	 * @param {Function} callback The function to call when the entity is received.
	 * @return {Function|null} If the listener could be registered, it returns a function that, when called, removes
	 * the event listener.
	 * If the listener registration was delayed, null is returned.
	 */
	AbsyncService.prototype.on = function AbsyncService$on( eventName, callback ) {
		var _absyncProvider = this.__absyncProvider;
		var _absyncService = this;

		// If we have no configured socket.io connection yet, remember to register it later.
		if( !_absyncProvider.__ioSocket ) {

			if( _absyncProvider.__registerLater.length > 8192 ) {
				// Be defensive, something is probably not right here.
				return null;
			}

			// TODO: Use promises here, so that we can always return the event listener removal function.
			_absyncProvider.__registerLater.push( {
				eventName : eventName,
				callback  : callback
			} );
			return null;
		}

		return _absyncService.__handleEntityEvent( eventName, callback );
	};

	/**
	 * Register an event listener on the websocket.
	 * @param {String} eventName The event name, usually the name of the entity.
	 * @param {Function} callback The function to call when the entity is received.
	 * @returns {Function}
	 */
	AbsyncService.prototype.__handleEntityEvent = function AbsyncService$__handleEntityEvent( eventName, callback ) {
		var _absyncProvider = this.__absyncProvider;

		// Register the callback with socket.io.
		_absyncProvider.__ioSocket.on( eventName, callback );

		// Return a function that removes the listener.
		return function removeListener() {
			_absyncProvider.__ioSocket.removeListener( eventName, callback );
		};
	};

	/**
	 * Convenience method to allow the user to emit() from the websocket.
	 * This is not utilized in absync internally.
	 * @param {String} eventName
	 * @param {*} data
	 * @param {Function} [callback]
	 */
	AbsyncService.prototype.emit = function AbsyncService$emit( eventName, data, callback ) {
		var _absyncProvider = this.__absyncProvider;

		if( !_absyncProvider.__ioSocket ) {
			throw new Error( "socket.io is not initialized." );
		}

		_absyncProvider.__ioSocket.emit( eventName, data, function afterEmit() {
			if( callback ) {
				callback.apply( _absyncProvider.__ioSocket, arguments );
			}
		} );
	};
}());
<|endoftext|>


<commit_before>'use strict';

exports.find = function(req, res, next){
  var outcome = {};

  var getStatusOptions = function(callback) {
    req.app.db.models.Status.find({ pivot: 'Account' }, 'name').sort('name').exec(function(err, statuses) {
      if (err) {
        return callback(err, null);
      }

      outcome.statuses = statuses;
      return callback(null, 'done');
    });
  };

  var getResults = function(callback) {
    req.query.search = req.query.search ? req.query.search : '';
    req.query.status = req.query.status ? req.query.status : '';
    req.query.limit = req.query.limit ? parseInt(req.query.limit, null) : 20;
    req.query.page = req.query.page ? parseInt(req.query.page, null) : 1;
    req.query.sort = req.query.sort ? req.query.sort : '_id';

    var filters = {};
    if (req.query.search) {
      filters.search = new RegExp('^.*?'+ req.query.search +'.*$', 'i');
    }

    if (req.query.status) {
      filters['status.id'] = req.query.status;
    }

    console.log('database is: ');
    console.dir(req.app.get('mysql').Wine);
    var wine = req.app.get('mysql').Wine;

    wine.findAll({
        where: { createdBy: req.user.id },
        attributes: ['id', 'grape', 'estate', 'name', 'notes', 'pairing', 'rating', 'year'],
     })
    .error(function(err) {
      // error callback
      console.log('Couldnt find wines: ' + err);
    })
    .success(function(wines) {
        console.log('Wines returned.');
        console.dir(wines);
    });

    req.app.db.models.Account.pagedFind({
      filters: filters,
      keys: 'name company phone zip userCreated status',
      limit: req.query.limit,
      page: req.query.page,
      sort: req.query.sort
    }, function(err, results) {
      if (err) {
        return callback(err, null);
      }

      outcome.results = results;
      return callback(null, 'done');
    });
  };

  var asyncFinally = function(err, results) {
    if (err) {
      return next(err);
    }

    if (req.xhr) {

      res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
      outcome.results.filters = req.query;
      console.log('sending xhr: ');
      console.dir(outcome.results);
      res.send(outcome.results);
    }
    else {
      outcome.results.filters = req.query;
      console.log('sending with template: ');
      console.dir(outcome.results);
      res.render('admin/accounts/index', {
        data: {
          results: escape(JSON.stringify(outcome.results)),
          statuses: outcome.statuses
        }
      });
    }
  };

  require('async').parallel([getStatusOptions, getResults], asyncFinally);
};

exports.read = function(req, res, next){
  var outcome = {};

  var getStatusOptions = function(callback) {
    req.app.db.models.Status.find({ pivot: 'Account' }, 'name').sort('name').exec(function(err, statuses) {
      if (err) {
        return callback(err, null);
      }

      outcome.statuses = statuses;
      return callback(null, 'done');
    });
  };

  var getRecord = function(callback) {
    req.app.db.models.Account.findById(req.params.id).exec(function(err, record) {
      if (err) {
        return callback(err, null);
      }

      outcome.record = record;
      return callback(null, 'done');
    });
  };

  var asyncFinally = function(err, results) {
    if (err) {
      return next(err);
    }

    if (req.xhr) {
      res.send(outcome.record);
    }
    else {
      res.render('admin/accounts/details', {
        data: {
          record: escape(JSON.stringify(outcome.record)),
          statuses: outcome.statuses
        }
      });
    }
  };

  require('async').parallel([getStatusOptions, getRecord], asyncFinally);
};

exports.create = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body['name.full']) {
      workflow.outcome.errors.push('Please enter a name.');
      return workflow.emit('response');
    }

    workflow.emit('createAccount');
  });

  workflow.on('createAccount', function() {
    var nameParts = req.body['name.full'].trim().split(/\s/);
    var fieldsToSet = {
      name: {
        first: nameParts.shift(),
        middle: (nameParts.length > 1 ? nameParts.shift() : ''),
        last: (nameParts.length === 0 ? '' : nameParts.join(' ')),
      },
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };
    fieldsToSet.name.full = fieldsToSet.name.first + (fieldsToSet.name.last ? ' '+ fieldsToSet.name.last : '');
    fieldsToSet.search = [
      fieldsToSet.name.first,
      fieldsToSet.name.middle,
      fieldsToSet.name.last
    ];

    req.app.db.models.Account.create(fieldsToSet, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.record = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.update = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.first) {
      workflow.outcome.errfor.first = 'required';
    }

    if (!req.body.last) {
      workflow.outcome.errfor.last = 'required';
    }

    if (workflow.hasErrors()) {
      return workflow.emit('response');
    }

    workflow.emit('patchAccount');
  });

  workflow.on('patchAccount', function() {
    var fieldsToSet = {
      name: {
        first: req.body.first,
        middle: req.body.middle,
        last: req.body.last,
        full: req.body.first +' '+ req.body.last
      },
      company: req.body.company,
      phone: req.body.phone,
      zip: req.body.zip,
      search: [
        req.body.first,
        req.body.middle,
        req.body.last,
        req.body.company,
        req.body.phone,
        req.body.zip
      ]
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, fieldsToSet, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.linkUser = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not link accounts to users.');
      return workflow.emit('response');
    }

    if (!req.body.newUsername) {
      workflow.outcome.errfor.newUsername = 'required';
      return workflow.emit('response');
    }

    workflow.emit('verifyUser');
  });

  workflow.on('verifyUser', function(callback) {
    req.app.db.models.User.findOne({ username: req.body.newUsername }).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!user) {
        workflow.outcome.errors.push('User not found.');
        return workflow.emit('response');
      }
      else if (user.roles && user.roles.account && user.roles.account !== req.params.id) {
        workflow.outcome.errors.push('User is already linked to a different account.');
        return workflow.emit('response');
      }

      workflow.user = user;
      workflow.emit('duplicateLinkCheck');
    });
  });

  workflow.on('duplicateLinkCheck', function(callback) {
    req.app.db.models.Account.findOne({ 'user.id': workflow.user._id, _id: {$ne: req.params.id} }).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (account) {
        workflow.outcome.errors.push('Another account is already linked to that user.');
        return workflow.emit('response');
      }

      workflow.emit('patchUser');
    });
  });

  workflow.on('patchUser', function() {
    req.app.db.models.User.findByIdAndUpdate(workflow.user._id, { 'roles.account': req.params.id }).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.emit('patchAccount');
    });
  });

  workflow.on('patchAccount', function(callback) {
    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { user: { id: workflow.user._id, name: workflow.user.username } }).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.unlinkUser = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not unlink users from accounts.');
      return workflow.emit('response');
    }

    workflow.emit('patchAccount');
  });

  workflow.on('patchAccount', function() {
    req.app.db.models.Account.findById(req.params.id).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!account) {
        workflow.outcome.errors.push('Account was not found.');
        return workflow.emit('response');
      }

      var userId = account.user.id;
      account.user = { id: undefined, name: '' };
      account.save(function(err, account) {
        if (err) {
          return workflow.emit('exception', err);
        }

        workflow.outcome.account = account;
        workflow.emit('patchUser', userId);
      });
    });
  });

  workflow.on('patchUser', function(id) {
    req.app.db.models.User.findById(id).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!user) {
        workflow.outcome.errors.push('User was not found.');
        return workflow.emit('response');
      }

      user.roles.account = undefined;
      user.save(function(err, user) {
        if (err) {
          return workflow.emit('exception', err);
        }

        workflow.emit('response');
      });
    });
  });

  workflow.emit('validate');
};

exports.newNote = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.data) {
      workflow.outcome.errors.push('Data is required.');
      return workflow.emit('response');
    }

    workflow.emit('addNote');
  });

  workflow.on('addNote', function() {
    var noteToAdd = {
      data: req.body.data,
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { $push: { notes: noteToAdd } }, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.newStatus = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.id) {
      workflow.outcome.errors.push('Please choose a status.');
    }

    if (workflow.hasErrors()) {
      return workflow.emit('response');
    }

    workflow.emit('addStatus');
  });

  workflow.on('addStatus', function() {
    var statusToAdd = {
      id: req.body.id,
      name: req.body.name,
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { status: statusToAdd, $push: { statusLog: statusToAdd } }, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.delete = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not delete accounts.');
      return workflow.emit('response');
    }

    workflow.emit('deleteAccount');
  });

  workflow.on('deleteAccount', function(err) {
    req.app.db.models.Account.findByIdAndRemove(req.params.id, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      workflow.emit('response');
    });
  });

  workflow.emit('validate');
};
<commit_msg>testing<commit_after>'use strict';

exports.find = function(req, res, next){
  var outcome = {};

  var getStatusOptions = function(callback) {
    req.app.db.models.Status.find({ pivot: 'Account' }, 'name').sort('name').exec(function(err, statuses) {
      if (err) {
        return callback(err, null);
      }

      outcome.statuses = statuses;
      return callback(null, 'done');
    });
  };

  var getResults = function(callback) {
    req.query.search = req.query.search ? req.query.search : '';
    req.query.status = req.query.status ? req.query.status : '';
    req.query.limit = req.query.limit ? parseInt(req.query.limit, null) : 20;
    req.query.page = req.query.page ? parseInt(req.query.page, null) : 1;
    req.query.sort = req.query.sort ? req.query.sort : '_id';

    var filters = {};
    if (req.query.search) {
      filters.search = new RegExp('^.*?'+ req.query.search +'.*$', 'i');
    }

    if (req.query.status) {
      filters['status.id'] = req.query.status;
    }

    console.log('database is: ');
    console.dir(req.app.get('mysql').Wine);
    var wine = req.app.get('mysql').Wine;

    /*wine.findAll({
        where: { createdBy: req.user.id },
        attributes: ['id', 'grape', 'estate', 'name', 'notes', 'pairing', 'rating', 'year'],
     })
    .error(function(err) {
      // error callback
      console.log('Couldnt find wines: ' + err);
    })
    .success(function(wines) {
        console.log('Wines returned.');
        console.dir(wines);
    });*/

    req.app.db.models.Account.pagedFind({
      filters: filters,
      keys: 'name company phone zip userCreated status',
      limit: req.query.limit,
      page: req.query.page,
      sort: req.query.sort
    }, function(err, results) {
      if (err) {
        return callback(err, null);
      }

      outcome.results = results;
      return callback(null, 'done');
    });
  };

  var asyncFinally = function(err, results) {
    if (err) {
      return next(err);
    }

    if (req.xhr) {

      res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
      outcome.results.filters = req.query;
      console.log('sending xhr: ');
      console.dir(outcome.results);
      res.send(outcome.results);
    }
    else {
      outcome.results.filters = req.query;
      console.log('sending with template: ');
      console.dir(outcome.results);
      res.render('admin/accounts/index', {
        data: {
          results: escape(JSON.stringify(outcome.results)),
          statuses: outcome.statuses
        }
      });
    }
  };

  require('async').parallel([getStatusOptions, getResults], asyncFinally);
};

exports.read = function(req, res, next){
  var outcome = {};

  var getStatusOptions = function(callback) {
    req.app.db.models.Status.find({ pivot: 'Account' }, 'name').sort('name').exec(function(err, statuses) {
      if (err) {
        return callback(err, null);
      }

      outcome.statuses = statuses;
      return callback(null, 'done');
    });
  };

  var getRecord = function(callback) {
    req.app.db.models.Account.findById(req.params.id).exec(function(err, record) {
      if (err) {
        return callback(err, null);
      }

      outcome.record = record;
      return callback(null, 'done');
    });
  };

  var asyncFinally = function(err, results) {
    if (err) {
      return next(err);
    }

    if (req.xhr) {
      res.send(outcome.record);
    }
    else {
      res.render('admin/accounts/details', {
        data: {
          record: escape(JSON.stringify(outcome.record)),
          statuses: outcome.statuses
        }
      });
    }
  };

  require('async').parallel([getStatusOptions, getRecord], asyncFinally);
};

exports.create = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body['name.full']) {
      workflow.outcome.errors.push('Please enter a name.');
      return workflow.emit('response');
    }

    workflow.emit('createAccount');
  });

  workflow.on('createAccount', function() {
    var nameParts = req.body['name.full'].trim().split(/\s/);
    var fieldsToSet = {
      name: {
        first: nameParts.shift(),
        middle: (nameParts.length > 1 ? nameParts.shift() : ''),
        last: (nameParts.length === 0 ? '' : nameParts.join(' ')),
      },
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };
    fieldsToSet.name.full = fieldsToSet.name.first + (fieldsToSet.name.last ? ' '+ fieldsToSet.name.last : '');
    fieldsToSet.search = [
      fieldsToSet.name.first,
      fieldsToSet.name.middle,
      fieldsToSet.name.last
    ];

    req.app.db.models.Account.create(fieldsToSet, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.record = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.update = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.first) {
      workflow.outcome.errfor.first = 'required';
    }

    if (!req.body.last) {
      workflow.outcome.errfor.last = 'required';
    }

    if (workflow.hasErrors()) {
      return workflow.emit('response');
    }

    workflow.emit('patchAccount');
  });

  workflow.on('patchAccount', function() {
    var fieldsToSet = {
      name: {
        first: req.body.first,
        middle: req.body.middle,
        last: req.body.last,
        full: req.body.first +' '+ req.body.last
      },
      company: req.body.company,
      phone: req.body.phone,
      zip: req.body.zip,
      search: [
        req.body.first,
        req.body.middle,
        req.body.last,
        req.body.company,
        req.body.phone,
        req.body.zip
      ]
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, fieldsToSet, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.linkUser = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not link accounts to users.');
      return workflow.emit('response');
    }

    if (!req.body.newUsername) {
      workflow.outcome.errfor.newUsername = 'required';
      return workflow.emit('response');
    }

    workflow.emit('verifyUser');
  });

  workflow.on('verifyUser', function(callback) {
    req.app.db.models.User.findOne({ username: req.body.newUsername }).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!user) {
        workflow.outcome.errors.push('User not found.');
        return workflow.emit('response');
      }
      else if (user.roles && user.roles.account && user.roles.account !== req.params.id) {
        workflow.outcome.errors.push('User is already linked to a different account.');
        return workflow.emit('response');
      }

      workflow.user = user;
      workflow.emit('duplicateLinkCheck');
    });
  });

  workflow.on('duplicateLinkCheck', function(callback) {
    req.app.db.models.Account.findOne({ 'user.id': workflow.user._id, _id: {$ne: req.params.id} }).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (account) {
        workflow.outcome.errors.push('Another account is already linked to that user.');
        return workflow.emit('response');
      }

      workflow.emit('patchUser');
    });
  });

  workflow.on('patchUser', function() {
    req.app.db.models.User.findByIdAndUpdate(workflow.user._id, { 'roles.account': req.params.id }).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.emit('patchAccount');
    });
  });

  workflow.on('patchAccount', function(callback) {
    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { user: { id: workflow.user._id, name: workflow.user.username } }).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.unlinkUser = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not unlink users from accounts.');
      return workflow.emit('response');
    }

    workflow.emit('patchAccount');
  });

  workflow.on('patchAccount', function() {
    req.app.db.models.Account.findById(req.params.id).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!account) {
        workflow.outcome.errors.push('Account was not found.');
        return workflow.emit('response');
      }

      var userId = account.user.id;
      account.user = { id: undefined, name: '' };
      account.save(function(err, account) {
        if (err) {
          return workflow.emit('exception', err);
        }

        workflow.outcome.account = account;
        workflow.emit('patchUser', userId);
      });
    });
  });

  workflow.on('patchUser', function(id) {
    req.app.db.models.User.findById(id).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!user) {
        workflow.outcome.errors.push('User was not found.');
        return workflow.emit('response');
      }

      user.roles.account = undefined;
      user.save(function(err, user) {
        if (err) {
          return workflow.emit('exception', err);
        }

        workflow.emit('response');
      });
    });
  });

  workflow.emit('validate');
};

exports.newNote = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.data) {
      workflow.outcome.errors.push('Data is required.');
      return workflow.emit('response');
    }

    workflow.emit('addNote');
  });

  workflow.on('addNote', function() {
    var noteToAdd = {
      data: req.body.data,
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { $push: { notes: noteToAdd } }, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.newStatus = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.id) {
      workflow.outcome.errors.push('Please choose a status.');
    }

    if (workflow.hasErrors()) {
      return workflow.emit('response');
    }

    workflow.emit('addStatus');
  });

  workflow.on('addStatus', function() {
    var statusToAdd = {
      id: req.body.id,
      name: req.body.name,
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { status: statusToAdd, $push: { statusLog: statusToAdd } }, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.delete = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not delete accounts.');
      return workflow.emit('response');
    }

    workflow.emit('deleteAccount');
  });

  workflow.on('deleteAccount', function(err) {
    req.app.db.models.Account.findByIdAndRemove(req.params.id, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      workflow.emit('response');
    });
  });

  workflow.emit('validate');
};
<|endoftext|>


<commit_before>var RawModule = require("../lib/RawModule");
var OriginalSource = require("webpack-sources").OriginalSource;
var RawSource = require("webpack-sources").RawSource;
var RequestShortener = require("../lib/RequestShortener");
var should = require("should");
var path = require("path")

describe("RawModule", function() {
	var myRawModule;

	before(function() {
		var source = 'sourceStr attribute';
		var identifier = 'identifierStr attribute';
		var readableIdentifier = 'readableIdentifierStr attribute';
		myRawModule = new RawModule(source, identifier, readableIdentifier);
	});

	describe('identifier', function() {
		it('returns value for identifierStr attribute', function() {
			should(myRawModule.identifier()).be.exactly('identifierStr attribute');
		});
	});

	describe('size', function() {
		it('returns value for sourceStr attribute\'s length property', function() {
			var sourceStrLength = myRawModule.sourceStr.length;
			should(myRawModule.size()).be.exactly(sourceStrLength);
		});
	});

	describe('readableIdentifier', function() {
		it('returns result of calling provided requestShortener\'s shorten method\
     on readableIdentifierStr attribute', function() {
			var requestShortener = new RequestShortener(path.resolve());
			should.exist(myRawModule.readableIdentifier(requestShortener));
		});
	});

	describe('needRebuild', function() {
		it('returns false', function() {
			should(myRawModule.needRebuild()).be.false();
		});
	});

	describe('source', function() {
		it('returns a new OriginalSource instance with sourceStr attribute and\
        return value of identifier() function provided as constructor arguments',
			function() {
				var originalSource = new OriginalSource(myRawModule.sourceStr, myRawModule.identifier());
				myRawModule.useSourceMap = true;
				myRawModule.source().should.match(originalSource);
			});

		it('returns a new RawSource instance with sourceStr attribute provided\
        as constructor argument if useSourceMap is falsey', function() {
			var rawSource = new RawSource(myRawModule.sourceStr);
			myRawModule.useSourceMap = false;
			myRawModule.source().should.match(rawSource);
		});
	});
});
<commit_msg>refactor(ES6): RawModule.test.js<commit_after>"use strict";

const RawModule = require("../lib/RawModule");
const OriginalSource = require("webpack-sources").OriginalSource;
const RawSource = require("webpack-sources").RawSource;
const RequestShortener = require("../lib/RequestShortener");
const should = require("should");
const path = require("path");

describe("RawModule", () => {
	let myRawModule;

	before(() => {
		const source = "sourceStr attribute";
		const identifier = "identifierStr attribute";
		const readableIdentifier = "readableIdentifierStr attribute";
		myRawModule = new RawModule(source, identifier, readableIdentifier);
	});

	describe("identifier", () => {
		it("returns value for identifierStr attribute", () =>
			should(myRawModule.identifier()).be.exactly("identifierStr attribute"));
	});

	describe("size", () => {
		it("returns value for sourceStr attribute\"s length property", () => {
			const sourceStrLength = myRawModule.sourceStr.length;
			should(myRawModule.size()).be.exactly(sourceStrLength);
		});
	});

	describe("readableIdentifier", () => {
		it("returns result of calling provided requestShortener\"s shorten method\
     on readableIdentifierStr attribute", () => {
			const requestShortener = new RequestShortener(path.resolve());
			should.exist(myRawModule.readableIdentifier(requestShortener));
		});
	});

	describe("needRebuild", () => {
		it("returns false", () => should(myRawModule.needRebuild()).be.false());
	});

	describe("source", () => {
		it("returns a new OriginalSource instance with sourceStr attribute and\
        return value of identifier() function provided as constructor arguments",
			() => {
				const originalSource = new OriginalSource(myRawModule.sourceStr, myRawModule.identifier());
				myRawModule.useSourceMap = true;
				myRawModule.source().should.match(originalSource);
			});

		it("returns a new RawSource instance with sourceStr attribute provided\
        as constructor argument if useSourceMap is falsey", () => {
			const rawSource = new RawSource(myRawModule.sourceStr);
			myRawModule.useSourceMap = false;
			myRawModule.source().should.match(rawSource);
		});
	});
});
<|endoftext|>


<commit_before>'use strict';
/*===========================
Framework 7
===========================*/
window.Framework7 = function (params) {

    // App
    var app = this;

    // Version
    app.version = '0.9.6';

    // Default Parameters
    app.params = {
        cache: true,
        cacheIgnore: [],
        cacheIgnoreGetParameters: false,
        cacheDuration: 1000 * 60 * 10, // Ten minutes
        preloadPreviousPage: true,
        uniqueHistory: false,
        uniqueHistoryIgnoreGetParameters: false,
        dynamicPageUrl: 'content-{{index}}',
        router: true,
        // Push State
        pushState: false,
        pushStateRoot: undefined,
        pushStateNoAnimation: false,
        pushStateSeparator: '#!/',
        // Fast clicks
        fastClicks: true,
        fastClicksDistanceThreshold: 0,
        // Active State
        activeState: true,
        activeStateElements: 'a, button, label, span',
        // Animate Nav Back Icon
        animateNavBackIcon: false,
        // Swipe Back
        swipeBackPage: true,
        swipeBackPageThreshold: 0,
        swipeBackPageActiveArea: 30,
        swipeBackPageAnimateShadow: true,
        swipeBackPageAnimateOpacity: true,
        // Ajax
        ajaxLinks: undefined, // or CSS selector
        // External Links
        externalLinks: ['external'], // array of CSS class selectors and/or rel attributes
        // Sortable
        sortable: true,
        // Scroll toolbars
        hideNavbarOnPageScroll: false,
        hideToolbarOnPageScroll: false,
        showBarsOnPageScrollEnd: true,
        // Swipeout
        swipeout: true,
        swipeoutNoFollow: false,
        // Smart Select Back link template
        smartSelectBackTemplate: '
{{backText}}
',
        smartSelectBackText: 'Back',
        smartSelectInPopup: false,
        smartSelectPopupCloseTemplate: '
{{closeText}}
',
        smartSelectPopupCloseText: 'Close',
        smartSelectSearchbar: false,
        smartSelectBackOnSelect: false,
        // Searchbar
        searchbarHideDividers: true,
        searchbarHideGroups: true,
        // Panels
        swipePanel: false, // or 'left' or 'right'
        swipePanelActiveArea: 0,
        swipePanelCloseOpposite: true,
        swipePanelNoFollow: false,
        swipePanelThreshold: 0,
        panelsCloseByOutside: true,
        // Modals
        modalButtonOk: 'OK',
        modalButtonCancel: 'Cancel',
        modalUsernamePlaceholder: 'Username',
        modalPasswordPlaceholder: 'Password',
        modalTitle: 'Framework7',
        modalCloseByOutside: false,
        actionsCloseByOutside: true,
        popupCloseByOutside: true,
        modalPreloaderTitle: 'Loading... ',
        // Name space
        viewClass: 'view',
        viewMainClass: 'view-main',
        viewsClass: 'views',
        // Notifications defaults
        notificationCloseOnClick: false,
        notificationCloseIcon: true,
        // Animate Pages
        animatePages: true,
        // Template7
        templates: {},
        templatesData: {},
        template7Pages: false,
        precompileTemplates: false,
        // Auto init
        init: true,
    };

    // Extend defaults with parameters
    for (var param in params) {
        app.params[param] = params[param];
    }

    // DOM lib
    var $ = Dom7;

    // Template7 lib
    var t7 = Template7;
    app._compiledTemplates = {};

    // Touch events
    app.touchEvents = {
        start: app.support.touch ? 'touchstart' : 'mousedown',
        move: app.support.touch ? 'touchmove' : 'mousemove',
        end: app.support.touch ? 'touchend' : 'mouseup'
    };

    // Link to local storage
    app.ls = localStorage;

    // RTL
    app.rtl = $('body').css('direction') === 'rtl';
    if (app.rtl) $('html').attr('dir', 'rtl');

    // Overwrite statusbar overlay
    if (typeof app.params.statusbarOverlay !== 'undefined') {
        if (app.params.statusbarOverlay) $('html').addClass('with-statusbar-overlay');
        else $('html').removeClass('with-statusbar-overlay');
    }

<commit_msg>Fix version<commit_after>'use strict';
/*===========================
Framework 7
===========================*/
window.Framework7 = function (params) {

    // App
    var app = this;

    // Version
    app.version = '0.9.7';

    // Default Parameters
    app.params = {
        cache: true,
        cacheIgnore: [],
        cacheIgnoreGetParameters: false,
        cacheDuration: 1000 * 60 * 10, // Ten minutes
        preloadPreviousPage: true,
        uniqueHistory: false,
        uniqueHistoryIgnoreGetParameters: false,
        dynamicPageUrl: 'content-{{index}}',
        router: true,
        // Push State
        pushState: false,
        pushStateRoot: undefined,
        pushStateNoAnimation: false,
        pushStateSeparator: '#!/',
        // Fast clicks
        fastClicks: true,
        fastClicksDistanceThreshold: 0,
        // Active State
        activeState: true,
        activeStateElements: 'a, button, label, span',
        // Animate Nav Back Icon
        animateNavBackIcon: false,
        // Swipe Back
        swipeBackPage: true,
        swipeBackPageThreshold: 0,
        swipeBackPageActiveArea: 30,
        swipeBackPageAnimateShadow: true,
        swipeBackPageAnimateOpacity: true,
        // Ajax
        ajaxLinks: undefined, // or CSS selector
        // External Links
        externalLinks: ['external'], // array of CSS class selectors and/or rel attributes
        // Sortable
        sortable: true,
        // Scroll toolbars
        hideNavbarOnPageScroll: false,
        hideToolbarOnPageScroll: false,
        showBarsOnPageScrollEnd: true,
        // Swipeout
        swipeout: true,
        swipeoutNoFollow: false,
        // Smart Select Back link template
        smartSelectBackTemplate: '
{{backText}}
',
        smartSelectBackText: 'Back',
        smartSelectInPopup: false,
        smartSelectPopupCloseTemplate: '
{{closeText}}
',
        smartSelectPopupCloseText: 'Close',
        smartSelectSearchbar: false,
        smartSelectBackOnSelect: false,
        // Searchbar
        searchbarHideDividers: true,
        searchbarHideGroups: true,
        // Panels
        swipePanel: false, // or 'left' or 'right'
        swipePanelActiveArea: 0,
        swipePanelCloseOpposite: true,
        swipePanelNoFollow: false,
        swipePanelThreshold: 0,
        panelsCloseByOutside: true,
        // Modals
        modalButtonOk: 'OK',
        modalButtonCancel: 'Cancel',
        modalUsernamePlaceholder: 'Username',
        modalPasswordPlaceholder: 'Password',
        modalTitle: 'Framework7',
        modalCloseByOutside: false,
        actionsCloseByOutside: true,
        popupCloseByOutside: true,
        modalPreloaderTitle: 'Loading... ',
        // Name space
        viewClass: 'view',
        viewMainClass: 'view-main',
        viewsClass: 'views',
        // Notifications defaults
        notificationCloseOnClick: false,
        notificationCloseIcon: true,
        // Animate Pages
        animatePages: true,
        // Template7
        templates: {},
        templatesData: {},
        template7Pages: false,
        precompileTemplates: false,
        // Auto init
        init: true,
    };

    // Extend defaults with parameters
    for (var param in params) {
        app.params[param] = params[param];
    }

    // DOM lib
    var $ = Dom7;

    // Template7 lib
    var t7 = Template7;
    app._compiledTemplates = {};

    // Touch events
    app.touchEvents = {
        start: app.support.touch ? 'touchstart' : 'mousedown',
        move: app.support.touch ? 'touchmove' : 'mousemove',
        end: app.support.touch ? 'touchend' : 'mouseup'
    };

    // Link to local storage
    app.ls = localStorage;

    // RTL
    app.rtl = $('body').css('direction') === 'rtl';
    if (app.rtl) $('html').attr('dir', 'rtl');

    // Overwrite statusbar overlay
    if (typeof app.params.statusbarOverlay !== 'undefined') {
        if (app.params.statusbarOverlay) $('html').addClass('with-statusbar-overlay');
        else $('html').removeClass('with-statusbar-overlay');
    }

<|endoftext|>


<commit_before>'use strict';

chrome.runtime.sendMessage({
    type: 'pontoon-page-loaded',
    url: document.location.toString(),
    value: document.documentElement.innerHTML
});
const unreadNotificationsIcon = document.querySelector('#notifications.unread .button .icon');

function unreadNotificationsIconClick() {
    unreadNotificationsIcon.removeEventListener('click', unreadNotificationsIconClick);
    chrome.runtime.sendMessage({type: 'mark-all-notifications-as-read-from-page'});
}

if (unreadNotificationsIcon !== undefined) {
    unreadNotificationsIcon.addEventListener('click', unreadNotificationsIconClick);

    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        if (request.type === 'mark-all-notifications-as-read-from-extension') {
            unreadNotificationsIcon.style.color = '#4D5967';
        }
    });
}
<commit_msg>fix TypeError in content-script.js<commit_after>'use strict';

chrome.runtime.sendMessage({
    type: 'pontoon-page-loaded',
    url: document.location.toString(),
    value: document.documentElement.innerHTML
});
const unreadNotificationsIcon = document.querySelector('#notifications.unread .button .icon');

function unreadNotificationsIconClick() {
    unreadNotificationsIcon.removeEventListener('click', unreadNotificationsIconClick);
    chrome.runtime.sendMessage({type: 'mark-all-notifications-as-read-from-page'});
}

if (unreadNotificationsIcon !== null) {
    unreadNotificationsIcon.addEventListener('click', unreadNotificationsIconClick);

    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        if (request.type === 'mark-all-notifications-as-read-from-extension') {
            unreadNotificationsIcon.style.color = '#4D5967';
        }
    });
}
<|endoftext|>


<commit_before>'use strict';

exports.find = function(req, res, next){
  var outcome = {};

  req.app.db.models.Wine.findAll({
      where: { createdBy: req.user.id },
      attributes: ['id', 'grape', 'estate', 'name', 'notes', 'rating', 'createdBy']
   })
  .error(function(err) {
    // error callback
    console.log('Couldnt find items: ' + err);
    return next(err);
  })
  .success(function(items) {
      //console.log('Items returned.');
      //console.dir(items);

      outcome.results = JSON.stringify(items);

      if (req.xhr) {

        res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
        console.log('sending xhr: ');
        console.dir(outcome.results);
        res.send(outcome.results);
      }
      else {
        //?
      }

  });

};

exports.read = function(req, res, next){
  var outcome = {};

  var getStatusOptions = function(callback) {
    req.app.db.models.Status.find({ pivot: 'Account' }, 'name').sort('name').exec(function(err, statuses) {
      if (err) {
        return callback(err, null);
      }

      outcome.statuses = statuses;
      return callback(null, 'done');
    });
  };

  var getRecord = function(callback) {
    req.app.db.models.Account.findById(req.params.id).exec(function(err, record) {
      if (err) {
        return callback(err, null);
      }

      outcome.record = record;
      return callback(null, 'done');
    });
  };

  var asyncFinally = function(err, results) {
    if (err) {
      return next(err);
    }

    if (req.xhr) {
      res.send(outcome.record);
    }
    else {
      res.render('admin/accounts/details', {
        data: {
          record: escape(JSON.stringify(outcome.record)),
          statuses: outcome.statuses
        }
      });
    }
  };

  require('async').parallel([getStatusOptions, getRecord], asyncFinally);
};

exports.create = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    /*if (!req.body['name.full']) {
      workflow.outcome.errors.push('Please enter a name.');
      return workflow.emit('response');
    }*/

    workflow.emit('createWine');
  });

  workflow.on('createWine', function() {

    var fieldsToSet = {
      grape: req.body.grape,
      estate: req.body.estate,
      name: req.body.name,
      notes: req.body.notes,
      rating: req.body.rating,
      createdBy: req.user._id
    };

    req.app.db.models.Wine.create(fieldsToSet, function(err, wine) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.record = wine;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.update = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.first) {
      workflow.outcome.errfor.first = 'required';
    }

    if (!req.body.last) {
      workflow.outcome.errfor.last = 'required';
    }

    if (workflow.hasErrors()) {
      return workflow.emit('response');
    }

    workflow.emit('patchAccount');
  });

  workflow.on('patchAccount', function() {
    var fieldsToSet = {
      name: {
        first: req.body.first,
        middle: req.body.middle,
        last: req.body.last,
        full: req.body.first +' '+ req.body.last
      },
      company: req.body.company,
      phone: req.body.phone,
      zip: req.body.zip,
      search: [
        req.body.first,
        req.body.middle,
        req.body.last,
        req.body.company,
        req.body.phone,
        req.body.zip
      ]
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, fieldsToSet, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.linkUser = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not link accounts to users.');
      return workflow.emit('response');
    }

    if (!req.body.newUsername) {
      workflow.outcome.errfor.newUsername = 'required';
      return workflow.emit('response');
    }

    workflow.emit('verifyUser');
  });

  workflow.on('verifyUser', function(callback) {
    req.app.db.models.User.findOne({ username: req.body.newUsername }).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!user) {
        workflow.outcome.errors.push('User not found.');
        return workflow.emit('response');
      }
      else if (user.roles && user.roles.account && user.roles.account !== req.params.id) {
        workflow.outcome.errors.push('User is already linked to a different account.');
        return workflow.emit('response');
      }

      workflow.user = user;
      workflow.emit('duplicateLinkCheck');
    });
  });

  workflow.on('duplicateLinkCheck', function(callback) {
    req.app.db.models.Account.findOne({ 'user.id': workflow.user._id, _id: {$ne: req.params.id} }).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (account) {
        workflow.outcome.errors.push('Another account is already linked to that user.');
        return workflow.emit('response');
      }

      workflow.emit('patchUser');
    });
  });

  workflow.on('patchUser', function() {
    req.app.db.models.User.findByIdAndUpdate(workflow.user._id, { 'roles.account': req.params.id }).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.emit('patchAccount');
    });
  });

  workflow.on('patchAccount', function(callback) {
    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { user: { id: workflow.user._id, name: workflow.user.username } }).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.unlinkUser = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not unlink users from accounts.');
      return workflow.emit('response');
    }

    workflow.emit('patchAccount');
  });

  workflow.on('patchAccount', function() {
    req.app.db.models.Account.findById(req.params.id).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!account) {
        workflow.outcome.errors.push('Account was not found.');
        return workflow.emit('response');
      }

      var userId = account.user.id;
      account.user = { id: undefined, name: '' };
      account.save(function(err, account) {
        if (err) {
          return workflow.emit('exception', err);
        }

        workflow.outcome.account = account;
        workflow.emit('patchUser', userId);
      });
    });
  });

  workflow.on('patchUser', function(id) {
    req.app.db.models.User.findById(id).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!user) {
        workflow.outcome.errors.push('User was not found.');
        return workflow.emit('response');
      }

      user.roles.account = undefined;
      user.save(function(err, user) {
        if (err) {
          return workflow.emit('exception', err);
        }

        workflow.emit('response');
      });
    });
  });

  workflow.emit('validate');
};

exports.newNote = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.data) {
      workflow.outcome.errors.push('Data is required.');
      return workflow.emit('response');
    }

    workflow.emit('addNote');
  });

  workflow.on('addNote', function() {
    var noteToAdd = {
      data: req.body.data,
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { $push: { notes: noteToAdd } }, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.newStatus = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.id) {
      workflow.outcome.errors.push('Please choose a status.');
    }

    if (workflow.hasErrors()) {
      return workflow.emit('response');
    }

    workflow.emit('addStatus');
  });

  workflow.on('addStatus', function() {
    var statusToAdd = {
      id: req.body.id,
      name: req.body.name,
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { status: statusToAdd, $push: { statusLog: statusToAdd } }, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.delete = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not delete accounts.');
      return workflow.emit('response');
    }

    workflow.emit('deleteAccount');
  });

  workflow.on('deleteAccount', function(err) {
    req.app.db.models.Account.findByIdAndRemove(req.params.id, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      workflow.emit('response');
    });
  });

  workflow.emit('validate');
};
<commit_msg>updated wine create fn<commit_after>'use strict';

exports.find = function(req, res, next){
  var outcome = {};

  req.app.db.models.Wine.findAll({
      where: { createdBy: req.user.id },
      attributes: ['id', 'grape', 'estate', 'name', 'notes', 'rating', 'createdBy']
   })
  .error(function(err) {
    // error callback
    console.log('Couldnt find items: ' + err);
    return next(err);
  })
  .success(function(items) {
      //console.log('Items returned.');
      //console.dir(items);

      outcome.results = JSON.stringify(items);

      if (req.xhr) {

        res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
        console.log('sending xhr: ');
        console.dir(outcome.results);
        res.send(outcome.results);
      }
      else {
        //?
      }

  });

};

exports.read = function(req, res, next){
  var outcome = {};

  var getStatusOptions = function(callback) {
    req.app.db.models.Status.find({ pivot: 'Account' }, 'name').sort('name').exec(function(err, statuses) {
      if (err) {
        return callback(err, null);
      }

      outcome.statuses = statuses;
      return callback(null, 'done');
    });
  };

  var getRecord = function(callback) {
    req.app.db.models.Account.findById(req.params.id).exec(function(err, record) {
      if (err) {
        return callback(err, null);
      }

      outcome.record = record;
      return callback(null, 'done');
    });
  };

  var asyncFinally = function(err, results) {
    if (err) {
      return next(err);
    }

    if (req.xhr) {
      res.send(outcome.record);
    }
    else {
      res.render('admin/accounts/details', {
        data: {
          record: escape(JSON.stringify(outcome.record)),
          statuses: outcome.statuses
        }
      });
    }
  };

  require('async').parallel([getStatusOptions, getRecord], asyncFinally);
};

exports.create = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    /*if (!req.body['name.full']) {
      workflow.outcome.errors.push('Please enter a name.');
      return workflow.emit('response');
    }*/

    workflow.emit('createWine');
  });

  workflow.on('createWine', function() {

    var wine = req.app.db.models.Wine.build({
      grape: req.body.grape,
      estate: req.body.estate,
      name: req.body.name,
      notes: req.body.notes,
      rating: req.body.rating,
      createdBy: req.user._id
    });

    // persist an instance
    wine.save()
      .error(function(err) {
        // error callback
        console.log('Couldnt save it: ' + err);
        return workflow.emit('exception', err);
      })
      .success(function(newWine) {
        // success callback
        console.log('Saved new wine: ' + newWine.id);
        workflow.outcome.record = newWine;
        return workflow.emit('response');
      });

  });

  workflow.emit('validate');
};

exports.update = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.first) {
      workflow.outcome.errfor.first = 'required';
    }

    if (!req.body.last) {
      workflow.outcome.errfor.last = 'required';
    }

    if (workflow.hasErrors()) {
      return workflow.emit('response');
    }

    workflow.emit('patchAccount');
  });

  workflow.on('patchAccount', function() {
    var fieldsToSet = {
      name: {
        first: req.body.first,
        middle: req.body.middle,
        last: req.body.last,
        full: req.body.first +' '+ req.body.last
      },
      company: req.body.company,
      phone: req.body.phone,
      zip: req.body.zip,
      search: [
        req.body.first,
        req.body.middle,
        req.body.last,
        req.body.company,
        req.body.phone,
        req.body.zip
      ]
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, fieldsToSet, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.linkUser = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not link accounts to users.');
      return workflow.emit('response');
    }

    if (!req.body.newUsername) {
      workflow.outcome.errfor.newUsername = 'required';
      return workflow.emit('response');
    }

    workflow.emit('verifyUser');
  });

  workflow.on('verifyUser', function(callback) {
    req.app.db.models.User.findOne({ username: req.body.newUsername }).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!user) {
        workflow.outcome.errors.push('User not found.');
        return workflow.emit('response');
      }
      else if (user.roles && user.roles.account && user.roles.account !== req.params.id) {
        workflow.outcome.errors.push('User is already linked to a different account.');
        return workflow.emit('response');
      }

      workflow.user = user;
      workflow.emit('duplicateLinkCheck');
    });
  });

  workflow.on('duplicateLinkCheck', function(callback) {
    req.app.db.models.Account.findOne({ 'user.id': workflow.user._id, _id: {$ne: req.params.id} }).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (account) {
        workflow.outcome.errors.push('Another account is already linked to that user.');
        return workflow.emit('response');
      }

      workflow.emit('patchUser');
    });
  });

  workflow.on('patchUser', function() {
    req.app.db.models.User.findByIdAndUpdate(workflow.user._id, { 'roles.account': req.params.id }).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.emit('patchAccount');
    });
  });

  workflow.on('patchAccount', function(callback) {
    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { user: { id: workflow.user._id, name: workflow.user.username } }).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.unlinkUser = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not unlink users from accounts.');
      return workflow.emit('response');
    }

    workflow.emit('patchAccount');
  });

  workflow.on('patchAccount', function() {
    req.app.db.models.Account.findById(req.params.id).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!account) {
        workflow.outcome.errors.push('Account was not found.');
        return workflow.emit('response');
      }

      var userId = account.user.id;
      account.user = { id: undefined, name: '' };
      account.save(function(err, account) {
        if (err) {
          return workflow.emit('exception', err);
        }

        workflow.outcome.account = account;
        workflow.emit('patchUser', userId);
      });
    });
  });

  workflow.on('patchUser', function(id) {
    req.app.db.models.User.findById(id).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!user) {
        workflow.outcome.errors.push('User was not found.');
        return workflow.emit('response');
      }

      user.roles.account = undefined;
      user.save(function(err, user) {
        if (err) {
          return workflow.emit('exception', err);
        }

        workflow.emit('response');
      });
    });
  });

  workflow.emit('validate');
};

exports.newNote = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.data) {
      workflow.outcome.errors.push('Data is required.');
      return workflow.emit('response');
    }

    workflow.emit('addNote');
  });

  workflow.on('addNote', function() {
    var noteToAdd = {
      data: req.body.data,
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { $push: { notes: noteToAdd } }, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.newStatus = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.id) {
      workflow.outcome.errors.push('Please choose a status.');
    }

    if (workflow.hasErrors()) {
      return workflow.emit('response');
    }

    workflow.emit('addStatus');
  });

  workflow.on('addStatus', function() {
    var statusToAdd = {
      id: req.body.id,
      name: req.body.name,
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { status: statusToAdd, $push: { statusLog: statusToAdd } }, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.delete = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not delete accounts.');
      return workflow.emit('response');
    }

    workflow.emit('deleteAccount');
  });

  workflow.on('deleteAccount', function(err) {
    req.app.db.models.Account.findByIdAndRemove(req.params.id, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      workflow.emit('response');
    });
  });

  workflow.emit('validate');
};
<|endoftext|>