<commit_before>/*!
 * ${copyright}
 */

// Provides control sap.m.Switch.
sap.ui.define(['jquery.sap.global', './SwitchRenderer', './library', 'sap/ui/core/Control', 'sap/ui/core/EnabledPropagator', 'sap/ui/core/IconPool', 'sap/ui/core/theming/Parameters'],
	function(jQuery, SwitchRenderer, library, Control, EnabledPropagator, IconPool, Parameters) {
		"use strict";

		/**
		 * Constructor for a new Switch.
		 *
		 * @param {string} [sId] id for the new control, generated automatically if no id is given
		 * @param {object} [mSettings] initial settings for the new control
		 *
		 * @class
		 * A switch is a user interface control on mobile devices that is used for change between binary states. The user can also drag the button handle or tap to change the state.
		 * @extends sap.ui.core.Control
		 *
		 * @author SAP SE
		 * @version ${version}
		 *
		 * @constructor
		 * @public
		 * @alias sap.m.Switch
		 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
		 */
		var Switch = Control.extend("sap.m.Switch", /** @lends sap.m.Switch.prototype */ { metadata: {

			library: "sap.m",
			properties: {

				/**
				 * A boolean value indicating whether the switch is on or off.
				 */
				state: { type: "boolean", group: "Misc", defaultValue: false },

				/**
				 * Custom text for the "ON" state.
				 *
				 * "ON" translated to the current language is the default value.
				 * Beware that the given text will be cut off after three characters.
				 */
				customTextOn: { type: "string", group: "Misc", defaultValue: "" },

				/**
				 * Custom text for the "OFF" state.
				 *
				 * "OFF" translated to the current language is the default value.
				 * Beware that the given text will be cut off after three characters.
				 */
				customTextOff: { type: "string", group: "Misc", defaultValue: "" },

				/**
				 * Whether the switch is enabled.
				 */
				enabled: { type: "boolean", group: "Data", defaultValue: true },

				/**
				 * The name to be used in the HTML code for the switch (e.g. for HTML forms that send data to the server via submit).
				 */
				name: { type: "string", group: "Misc", defaultValue: "" },

				/**
				 * Type of a Switch. Possibles values "Default", "AcceptReject".
				 */
				type: { type : "sap.m.SwitchType", group: "Appearance", defaultValue: sap.m.SwitchType.Default }
			},
			events: {

				/**
				 * Triggered when a switch changes the state.
				 */
				change: {
					parameters: {

						/**
						 * The new state of the switch.
						 */
						state: { type: "boolean" }
					}
				}
			}
		}});

		IconPool.insertFontFaceStyle();
		EnabledPropagator.apply(Switch.prototype, [true]);

		/* =========================================================== */
		/* Internal methods and properties                             */
		/* =========================================================== */

		/**
		 * Slide the switch.
		 *
		 * @private
		 */
		Switch.prototype._slide = function(iPosition) {
			if (iPosition > Switch._OFFPOSITION) {
				iPosition = Switch._OFFPOSITION;
			} else if (iPosition < Switch._ONPOSITION) {
				iPosition = Switch._ONPOSITION;
			} else {
				iPosition = iPosition;
			}

			if (this._iCurrentPosition === iPosition) {
				return;
			}

			this._iCurrentPosition = iPosition;
			this._$SwitchInner[0].style[sap.ui.getCore().getConfiguration().getRTL() ? "right" : "left"] = iPosition + "px";
			this._setTempState(Math.abs(iPosition) < Switch._SWAPPOINT);
		};

		Switch.prototype._setTempState = function(b) {
			if (this._bTempState === b) {
				return;
			}

			this._bTempState = b;
			this._$Handle[0].setAttribute("data-sap-ui-swt", b ? this._sOn : this._sOff);
		};

		Switch.prototype._setDomState = function(bState) {
			var CSS_CLASS = SwitchRenderer.CSS_CLASS,
				sState = bState ? this._sOn : this._sOff;

			if (!this._$Switch) {
				return this;
			}

			this._$Handle[0].setAttribute("data-sap-ui-swt", sState);

			if (this.getName()) {
				this._$Checkbox[0].setAttribute("checked", bState);
				this._$Checkbox[0].setAttribute("value", sState);
			}

			bState ? this._$Switch.removeClass(CSS_CLASS + "Off").addClass(CSS_CLASS + "On")
					: this._$Switch.removeClass(CSS_CLASS + "On").addClass(CSS_CLASS + "Off");

			this._$Switch.addClass(CSS_CLASS + "Trans");

			// remove inline styles
			this._$SwitchInner.removeAttr("style");
		};

		Switch._getCssParameter = function(sParameter) {
			var fnGetCssParameter = Parameters.get;

			return fnGetCssParameter(sParameter) || fnGetCssParameter(sParameter + "-" + sap.ui.Device.os.name.toLowerCase());
		};

		(function() {
			var sParamTransitionTime = "sapMSwitch-TRANSITIONTIME",
				sTransitionTime = Switch._getCssParameter(sParamTransitionTime);

			// the milliseconds takes the transition from one state to another
			Switch._TRANSITIONTIME = Number(sTransitionTime) || 0;
		}());

		// the position of the inner HTML element whether the switch is "ON"
		Switch._ONPOSITION = Number(Switch._getCssParameter("sapMSwitch-ONPOSITION"));

		// the position of the inner HTML element whether the switch is "OFF"
		Switch._OFFPOSITION = Number(Switch._getCssParameter("sapMSwitch-OFFPOSITION"));

		// swap point
		Switch._SWAPPOINT = Math.abs((Switch._ONPOSITION - Switch._OFFPOSITION) / 2);

		// resource bundle
		Switch._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.m");

		/* =========================================================== */
		/* Lifecycle methods                                           */
		/* =========================================================== */

		/**
		 * Required adaptations before rendering.
		 *
		 * @private
		 */
		Switch.prototype.onBeforeRendering = function() {
			var Swt = Switch;

			this._sOn = this.getCustomTextOn() || Swt._oRb.getText("SWITCH_ON");
			this._sOff = this.getCustomTextOff() || Swt._oRb.getText("SWITCH_OFF");
		};

		/**
		 * Required adaptations after rendering.
		 *
		 * @private
		 */
		Switch.prototype.onAfterRendering = function() {
			var $SwitchCont,
				CSS_CLASS = "." + SwitchRenderer.CSS_CLASS;

			// switch control container jQuery DOM reference
			$SwitchCont = this.$();

			// switch jQuery DOM reference
			this._$Switch = $SwitchCont.find(CSS_CLASS);

			// switch inner jQuery DOM reference
			this._$SwitchInner = this._$Switch.children(CSS_CLASS + "Inner");

			// switch handle jQuery DOM reference
			this._$Handle = this._$SwitchInner.children(CSS_CLASS + "Handle");

			// checkbox jQuery DOM reference
			this._$Checkbox = $SwitchCont.children("input");
		};

		/* =========================================================== */
		/* Event handlers                                              */
		/* =========================================================== */

		/**
		 * Handle the touch start event happening on the switch.
		 *
		 * @param {jQuery.Event} oEvent The event object.
		 * @private
		 */
		Switch.prototype.ontouchstart = function(oEvent) {
			var oTargetTouch = oEvent.targetTouches[0],
				CSS_CLASS = SwitchRenderer.CSS_CLASS;

			// mark the event for components that needs to know if the event was handled by the Switch
			oEvent.setMarked();

			// only process single touches (only the first active touch point)
			if (sap.m.touch.countContained(oEvent.touches, this.getId()) > 1 ||
				!this.getEnabled() ||

				// detect which mouse button caused the event and only process the standard click
				// (this is usually the left button, oEvent.button === 0 for standard click)
				// note: if the current event is a touch event oEvent.button property will be not defined
				oEvent.button) {

				return;
			}

			// track the id of the first active touch point
			this._iActiveTouchId = oTargetTouch.identifier;

			// note: force ie browsers to set the focus to switch
			jQuery.sap.delayedCall(0, this, "focus");

			// add active state
			this._$Switch.addClass(CSS_CLASS + "Pressed")
						.removeClass(CSS_CLASS + "Trans");

			this._bTempState = this.getState();
			this._iStartPressPosX = oTargetTouch.pageX;
			this._iPosition = this._$SwitchInner.position().left;

			// track movement to determine if the interaction was a click or a tap
			this._bDragging = false;
		};

		/**
		 * Handle the touch move event on the switch.
		 *
		 * @param {jQuery.Event} oEvent The event object.
		 * @private
		 */
		Switch.prototype.ontouchmove = function(oEvent) {

			// mark the event for components that needs to know if the event was handled by the Switch
			oEvent.setMarked();

			// note: prevent native document scrolling
			oEvent.preventDefault();

			var oTouch,
				iPosition,
				fnTouch = sap.m.touch;

			if (!this.getEnabled() ||

				// detect which mouse button caused the event and only process the standard click
				// (this is usually the left button, oEvent.button === 0 for standard click)
				// note: if the current event is a touch event oEvent.button property will be not defined
				oEvent.button) {

				return;
			}

			// only process single touches (only the first active touch point),
			// the active touch has to be in the list of touches
			jQuery.sap.assert(fnTouch.find(oEvent.touches, this._iActiveTouchId), "missing touchend");

			// find the active touch point
			oTouch = fnTouch.find(oEvent.changedTouches, this._iActiveTouchId);

			// only process the active touch
			if (!oTouch ||

				// note: do not rely on a specific granularity of the touchmove event.
				// On windows 8 surfaces, the touchmove events are dispatched even if
				// the user doesn’t move the touch point along the surface.
				oTouch.pageX === this._iStartPressPosX) {

				return;
			}

			// interaction was not a click or a tap
			this._bDragging = true;

			iPosition = ((this._iStartPressPosX - oTouch.pageX) * -1) + this._iPosition;

			// RTL mirror
			if (sap.ui.getCore().getConfiguration().getRTL()) {
				iPosition = -iPosition;
			}

			this._slide(iPosition);
		};

		/**
		 * Handle the touch end event on the switch.
		 *
		 * @param {jQuery.Event} oEvent The event object.
		 * @private
		 */
		Switch.prototype.ontouchend = function(oEvent) {

			// mark the event for components that needs to know if the event was handled by the Switch
			oEvent.setMarked();

			var oTouch,
				fnTouch = sap.m.touch,
				assert = jQuery.sap.assert,
				bState = this.getState();

			if (!this.getEnabled() ||

				// detect which mouse button caused the event and only process the standard click
				// (this is usually the left button, oEvent.button === 0 for standard click)
				// note: if the current event is a touch event oEvent.button property will be not defined
				oEvent.button) {

				return;
			}

			// only process single touches (only the first active touch)
			assert(this._iActiveTouchId !== undefined, "expect to already be touching");

			// find the active touch point
			oTouch = fnTouch.find(oEvent.changedTouches, this._iActiveTouchId);

			// process this event only if the touch we're tracking has changed
			if (oTouch) {

				// the touchend for the touch we're monitoring
				assert(!fnTouch.find(oEvent.touches, this._iActiveTouchId), "touchend still active");

				// remove active state
				this._$Switch.removeClass(SwitchRenderer.CSS_CLASS + "Pressed");

				// change the state
				this.setState(this._bDragging ? this._bTempState : !this._bTempState);

				if (bState !== this.getState()) {
					bState = this.getState();

					// fire the change event after the CSS transition is completed
					jQuery.sap.delayedCall(Switch._TRANSITIONTIME, this, function() {
						this.fireChange({ state: bState });
					});
				}
			}
		};

		/**
		 * Handle the touchcancel event on the switch.
		 *
		 * @param {jQuery.Event} oEvent The event object.
		 * @private
		 */
		Switch.prototype.ontouchcancel = Switch.prototype.ontouchend;

		/**
		 *  Handle when the space or enter key are pressed.
		 *
		 * @param {jQuery.Event} oEvent The event object.
		 * @private
		 */
		Switch.prototype.onsapselect = function(oEvent) {
			var bState;

			if (this.getEnabled()) {

				// mark the event for components that needs to know if the event was handled by the Switch
				oEvent.setMarked();

				// note: prevent document scrolling when space keys is pressed
				oEvent.preventDefault();

				this.setState(!this.getState());

				bState = this.getState();

				// fire the change event after the CSS transition is completed
				jQuery.sap.delayedCall(Switch._TRANSITIONTIME, this, function() {
					this.fireChange({ state: bState });
				});
			}
		};

		/* =========================================================== */
		/* API method                                                  */
		/* =========================================================== */

		/**
		 * Change the switch state between on and off.
		 *
		 * @param {boolean} bState
		 * @public
		 * @return {sap.m.Switch} this to allow method chaining.
		 */
		Switch.prototype.setState = function(bState) {
			this.setProperty("state", bState, true);
			this._setDomState(this.getState());
			return this;
		};

		return Switch;

	}, /* bExport= */ true);<commit_msg>[INTERNAL] m.Switch: remove inline styles using node.style.cssText<commit_after>/*!
 * ${copyright}
 */

// Provides control sap.m.Switch.
sap.ui.define(['jquery.sap.global', './SwitchRenderer', './library', 'sap/ui/core/Control', 'sap/ui/core/EnabledPropagator', 'sap/ui/core/IconPool', 'sap/ui/core/theming/Parameters'],
	function(jQuery, SwitchRenderer, library, Control, EnabledPropagator, IconPool, Parameters) {
		"use strict";

		/**
		 * Constructor for a new Switch.
		 *
		 * @param {string} [sId] id for the new control, generated automatically if no id is given
		 * @param {object} [mSettings] initial settings for the new control
		 *
		 * @class
		 * A switch is a user interface control on mobile devices that is used for change between binary states. The user can also drag the button handle or tap to change the state.
		 * @extends sap.ui.core.Control
		 *
		 * @author SAP SE
		 * @version ${version}
		 *
		 * @constructor
		 * @public
		 * @alias sap.m.Switch
		 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
		 */
		var Switch = Control.extend("sap.m.Switch", /** @lends sap.m.Switch.prototype */ { metadata: {

			library: "sap.m",
			properties: {

				/**
				 * A boolean value indicating whether the switch is on or off.
				 */
				state: { type: "boolean", group: "Misc", defaultValue: false },

				/**
				 * Custom text for the "ON" state.
				 *
				 * "ON" translated to the current language is the default value.
				 * Beware that the given text will be cut off after three characters.
				 */
				customTextOn: { type: "string", group: "Misc", defaultValue: "" },

				/**
				 * Custom text for the "OFF" state.
				 *
				 * "OFF" translated to the current language is the default value.
				 * Beware that the given text will be cut off after three characters.
				 */
				customTextOff: { type: "string", group: "Misc", defaultValue: "" },

				/**
				 * Whether the switch is enabled.
				 */
				enabled: { type: "boolean", group: "Data", defaultValue: true },

				/**
				 * The name to be used in the HTML code for the switch (e.g. for HTML forms that send data to the server via submit).
				 */
				name: { type: "string", group: "Misc", defaultValue: "" },

				/**
				 * Type of a Switch. Possibles values "Default", "AcceptReject".
				 */
				type: { type : "sap.m.SwitchType", group: "Appearance", defaultValue: sap.m.SwitchType.Default }
			},
			events: {

				/**
				 * Triggered when a switch changes the state.
				 */
				change: {
					parameters: {

						/**
						 * The new state of the switch.
						 */
						state: { type: "boolean" }
					}
				}
			}
		}});

		IconPool.insertFontFaceStyle();
		EnabledPropagator.apply(Switch.prototype, [true]);

		/* =========================================================== */
		/* Internal methods and properties                             */
		/* =========================================================== */

		/**
		 * Slide the switch.
		 *
		 * @private
		 */
		Switch.prototype._slide = function(iPosition) {
			if (iPosition > Switch._OFFPOSITION) {
				iPosition = Switch._OFFPOSITION;
			} else if (iPosition < Switch._ONPOSITION) {
				iPosition = Switch._ONPOSITION;
			} else {
				iPosition = iPosition;
			}

			if (this._iCurrentPosition === iPosition) {
				return;
			}

			this._iCurrentPosition = iPosition;
			this._$SwitchInner[0].style[sap.ui.getCore().getConfiguration().getRTL() ? "right" : "left"] = iPosition + "px";
			this._setTempState(Math.abs(iPosition) < Switch._SWAPPOINT);
		};

		Switch.prototype._setTempState = function(b) {
			if (this._bTempState === b) {
				return;
			}

			this._bTempState = b;
			this._$Handle[0].setAttribute("data-sap-ui-swt", b ? this._sOn : this._sOff);
		};

		Switch.prototype._setDomState = function(bState) {
			var CSS_CLASS = SwitchRenderer.CSS_CLASS,
				sState = bState ? this._sOn : this._sOff;

			if (!this._$Switch) {
				return this;
			}

			this._$Handle[0].setAttribute("data-sap-ui-swt", sState);

			if (this.getName()) {
				this._$Checkbox[0].setAttribute("checked", bState);
				this._$Checkbox[0].setAttribute("value", sState);
			}

			bState ? this._$Switch.removeClass(CSS_CLASS + "Off").addClass(CSS_CLASS + "On")
					: this._$Switch.removeClass(CSS_CLASS + "On").addClass(CSS_CLASS + "Off");

			this._$Switch.addClass(CSS_CLASS + "Trans");

			// remove inline styles
			this._$SwitchInner[0].style.cssText = "";
		};

		Switch._getCssParameter = function(sParameter) {
			var fnGetCssParameter = Parameters.get;

			return fnGetCssParameter(sParameter) || fnGetCssParameter(sParameter + "-" + sap.ui.Device.os.name.toLowerCase());
		};

		(function() {
			var sParamTransitionTime = "sapMSwitch-TRANSITIONTIME",
				sTransitionTime = Switch._getCssParameter(sParamTransitionTime);

			// the milliseconds takes the transition from one state to another
			Switch._TRANSITIONTIME = Number(sTransitionTime) || 0;
		}());

		// the position of the inner HTML element whether the switch is "ON"
		Switch._ONPOSITION = Number(Switch._getCssParameter("sapMSwitch-ONPOSITION"));

		// the position of the inner HTML element whether the switch is "OFF"
		Switch._OFFPOSITION = Number(Switch._getCssParameter("sapMSwitch-OFFPOSITION"));

		// swap point
		Switch._SWAPPOINT = Math.abs((Switch._ONPOSITION - Switch._OFFPOSITION) / 2);

		// resource bundle
		Switch._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.m");

		/* =========================================================== */
		/* Lifecycle methods                                           */
		/* =========================================================== */

		/**
		 * Required adaptations before rendering.
		 *
		 * @private
		 */
		Switch.prototype.onBeforeRendering = function() {
			var Swt = Switch;

			this._sOn = this.getCustomTextOn() || Swt._oRb.getText("SWITCH_ON");
			this._sOff = this.getCustomTextOff() || Swt._oRb.getText("SWITCH_OFF");
		};

		/**
		 * Required adaptations after rendering.
		 *
		 * @private
		 */
		Switch.prototype.onAfterRendering = function() {
			var $SwitchCont,
				CSS_CLASS = "." + SwitchRenderer.CSS_CLASS;

			// switch control container jQuery DOM reference
			$SwitchCont = this.$();

			// switch jQuery DOM reference
			this._$Switch = $SwitchCont.find(CSS_CLASS);

			// switch inner jQuery DOM reference
			this._$SwitchInner = this._$Switch.children(CSS_CLASS + "Inner");

			// switch handle jQuery DOM reference
			this._$Handle = this._$SwitchInner.children(CSS_CLASS + "Handle");

			// checkbox jQuery DOM reference
			this._$Checkbox = $SwitchCont.children("input");
		};

		/* =========================================================== */
		/* Event handlers                                              */
		/* =========================================================== */

		/**
		 * Handle the touch start event happening on the switch.
		 *
		 * @param {jQuery.Event} oEvent The event object.
		 * @private
		 */
		Switch.prototype.ontouchstart = function(oEvent) {
			var oTargetTouch = oEvent.targetTouches[0],
				CSS_CLASS = SwitchRenderer.CSS_CLASS;

			// mark the event for components that needs to know if the event was handled by the Switch
			oEvent.setMarked();

			// only process single touches (only the first active touch point)
			if (sap.m.touch.countContained(oEvent.touches, this.getId()) > 1 ||
				!this.getEnabled() ||

				// detect which mouse button caused the event and only process the standard click
				// (this is usually the left button, oEvent.button === 0 for standard click)
				// note: if the current event is a touch event oEvent.button property will be not defined
				oEvent.button) {

				return;
			}

			// track the id of the first active touch point
			this._iActiveTouchId = oTargetTouch.identifier;

			// note: force ie browsers to set the focus to switch
			jQuery.sap.delayedCall(0, this, "focus");

			// add active state
			this._$Switch.addClass(CSS_CLASS + "Pressed")
						.removeClass(CSS_CLASS + "Trans");

			this._bTempState = this.getState();
			this._iStartPressPosX = oTargetTouch.pageX;
			this._iPosition = this._$SwitchInner.position().left;

			// track movement to determine if the interaction was a click or a tap
			this._bDragging = false;
		};

		/**
		 * Handle the touch move event on the switch.
		 *
		 * @param {jQuery.Event} oEvent The event object.
		 * @private
		 */
		Switch.prototype.ontouchmove = function(oEvent) {

			// mark the event for components that needs to know if the event was handled by the Switch
			oEvent.setMarked();

			// note: prevent native document scrolling
			oEvent.preventDefault();

			var oTouch,
				iPosition,
				fnTouch = sap.m.touch;

			if (!this.getEnabled() ||

				// detect which mouse button caused the event and only process the standard click
				// (this is usually the left button, oEvent.button === 0 for standard click)
				// note: if the current event is a touch event oEvent.button property will be not defined
				oEvent.button) {

				return;
			}

			// only process single touches (only the first active touch point),
			// the active touch has to be in the list of touches
			jQuery.sap.assert(fnTouch.find(oEvent.touches, this._iActiveTouchId), "missing touchend");

			// find the active touch point
			oTouch = fnTouch.find(oEvent.changedTouches, this._iActiveTouchId);

			// only process the active touch
			if (!oTouch ||

				// note: do not rely on a specific granularity of the touchmove event.
				// On windows 8 surfaces, the touchmove events are dispatched even if
				// the user doesn’t move the touch point along the surface.
				oTouch.pageX === this._iStartPressPosX) {

				return;
			}

			// interaction was not a click or a tap
			this._bDragging = true;

			iPosition = ((this._iStartPressPosX - oTouch.pageX) * -1) + this._iPosition;

			// RTL mirror
			if (sap.ui.getCore().getConfiguration().getRTL()) {
				iPosition = -iPosition;
			}

			this._slide(iPosition);
		};

		/**
		 * Handle the touch end event on the switch.
		 *
		 * @param {jQuery.Event} oEvent The event object.
		 * @private
		 */
		Switch.prototype.ontouchend = function(oEvent) {

			// mark the event for components that needs to know if the event was handled by the Switch
			oEvent.setMarked();

			var oTouch,
				fnTouch = sap.m.touch,
				assert = jQuery.sap.assert,
				bState = this.getState();

			if (!this.getEnabled() ||

				// detect which mouse button caused the event and only process the standard click
				// (this is usually the left button, oEvent.button === 0 for standard click)
				// note: if the current event is a touch event oEvent.button property will be not defined
				oEvent.button) {

				return;
			}

			// only process single touches (only the first active touch)
			assert(this._iActiveTouchId !== undefined, "expect to already be touching");

			// find the active touch point
			oTouch = fnTouch.find(oEvent.changedTouches, this._iActiveTouchId);

			// process this event only if the touch we're tracking has changed
			if (oTouch) {

				// the touchend for the touch we're monitoring
				assert(!fnTouch.find(oEvent.touches, this._iActiveTouchId), "touchend still active");

				// remove active state
				this._$Switch.removeClass(SwitchRenderer.CSS_CLASS + "Pressed");

				// change the state
				this.setState(this._bDragging ? this._bTempState : !this._bTempState);

				if (bState !== this.getState()) {
					bState = this.getState();

					// fire the change event after the CSS transition is completed
					jQuery.sap.delayedCall(Switch._TRANSITIONTIME, this, function() {
						this.fireChange({ state: bState });
					});
				}
			}
		};

		/**
		 * Handle the touchcancel event on the switch.
		 *
		 * @param {jQuery.Event} oEvent The event object.
		 * @private
		 */
		Switch.prototype.ontouchcancel = Switch.prototype.ontouchend;

		/**
		 *  Handle when the space or enter key are pressed.
		 *
		 * @param {jQuery.Event} oEvent The event object.
		 * @private
		 */
		Switch.prototype.onsapselect = function(oEvent) {
			var bState;

			if (this.getEnabled()) {

				// mark the event for components that needs to know if the event was handled by the Switch
				oEvent.setMarked();

				// note: prevent document scrolling when space keys is pressed
				oEvent.preventDefault();

				this.setState(!this.getState());

				bState = this.getState();

				// fire the change event after the CSS transition is completed
				jQuery.sap.delayedCall(Switch._TRANSITIONTIME, this, function() {
					this.fireChange({ state: bState });
				});
			}
		};

		/* =========================================================== */
		/* API method                                                  */
		/* =========================================================== */

		/**
		 * Change the switch state between on and off.
		 *
		 * @param {boolean} bState
		 * @public
		 * @return {sap.m.Switch} this to allow method chaining.
		 */
		Switch.prototype.setState = function(bState) {
			this.setProperty("state", bState, true);
			this._setDomState(this.getState());
			return this;
		};

		return Switch;

	}, /* bExport= */ true);<|endoftext|>


<commit_before>module.exports = {

  token: (req, res) => {
    var token = req.params.token
    var hub = sails.hooks.insteon.hub()
    hub.smartThingsToken = token
    hub.save(function (err) {
      if (err) {
        return res.serverError(err)
      }
      hub.loadSmartThingsEndpoints(token)
      return res.json({ hub: hub })
    })
  }
}
<commit_msg>Revert<commit_after>module.exports = {

  token: (req, res) => {
    var token = req.params.token
    Hub.update({}, {smartThingsToken: token}).exec((err, record) => {
      if (err) {
        return res.serverError(err)
      } else {
        var hub = sails.hooks.insteon.hub()
        hub.smartThingsToken = token
        hub.loadSmartThingsEndpoints(token)
        return res.json({ hub: record })
      }
    })
  }
}
<|endoftext|>


<commit_before>const mongoose = require('mongoose');
const logger = require('../../lib/logger');
const coordsUtil = require('../../lib/coords_util');
const conf = require('../../config/config.js');

const enterpriseInternationalPublicModel = mongoose.model('EnterpriseInternationalPublic');
const enterpriseInternationalPrivateFieldsModel = mongoose.model('EnterpriseInternationalPrivateFields');
const enterpriseLogoModel = mongoose.model('EnterpriseLogo');
const enterpriseAdapter = require('./enterprise.adapter');
const SUPPORTED_LANGUAGES = require('../helpers/language/constants').SUPPORTED_LANGUAGES;
const DEFAULT_LANGUAGE = require('../helpers/language/constants').DEFAULT_LANGUAGE;
const SUPPORTED_IMAGE_TYPES = ['image/png', 'image/gif', 'image/jpeg', 'image/svg+xml'];

const ENTERPRISE_CACHE_CONTROL = conf.get('enterpriseCacheControl');

function locationParamToPointObject(locationSearch) {
  let [longStr, latStr] = locationSearch.split(',');
  let long = parseFloat(longStr);
  let lat = parseFloat(latStr);
  if (!coordsUtil.isValidCoords(long, lat)) {
    return undefined;
  }
  let point = { type : 'Point', coordinates : [long,lat] };
  return point;
}

function processDirectoryResults(res, dbEnterprises, language, page, pages) {
  if (!dbEnterprises) {
    res.status(200).json({});
    return;
  }

  let transformedEnterprises = enterpriseAdapter.transformDbEnterprisesToApiFormatForLanguage(dbEnterprises, language);
  res.set('Cache-Control', 'max-age=' + ENTERPRISE_CACHE_CONTROL);
  res.status(200).json({
    enterprises: transformedEnterprises,
    page: page,
    pages: pages
  });
}

function performLocationSearch(res, locationSearch, limit, offset, language) {
  let point = locationParamToPointObject(locationSearch);
  if (!point) {
    res.status(400).json({'message': 'Invalid location parameter'});
    return;
  }

  enterpriseInternationalPublicModel.aggregate(
    [
      { '$geoNear': {
        'near': point,
        'spherical': true,
        'distanceField': 'dis'
      }},
      { '$skip': offset },
      { '$limit': limit }
    ])
  .then(dbEnterprises => {
    processDirectoryResults(res, dbEnterprises, language);
  })
  .catch(err => {
    logger.error('Error finding enterprises ' + err);
    res.status(500).json({'message': err});
  });
}

function performBrowseDirectory(res, limit, offset, language) {
  let sortValue = {};
  sortValue[language + '.lowercase_name'] = 1;
  enterpriseInternationalPublicModel
    .find()
    .sort(sortValue)
    .limit(limit)
    .skip(offset)
    .then(dbEnterprises => processDirectoryResults(res, dbEnterprises, language))
    .catch(err => {
      logger.error('Error browsing enterprises ' + err);
      res.status(500).json({'message': err});
    });
}

module.exports.getAllEnterprisesPublic = function(req, res) {
  let query;

  let search = req.swagger.params.q.value;
  let locationSearch = req.swagger.params.at.value;

  let limit = req.swagger.params.count.value || 25;
  let page = req.swagger.params.page.value || 1;

  let lang = getLanguage(req);

  if (locationSearch) {
    performLocationSearch(res, locationSearch, limit, offset, lang);
    return;
  }

  if (!search) {
    performBrowseDirectory(res, limit, offset, lang);
    return;
  }

  let queryOptions = {
    limit: limit,
    page: page
  };

  enterpriseInternationalPublicModel.paginate(query, queryOptions)
    .then(results => {
      let dbEnterprises = results.docs;

      processDirectoryResults(res, dbEnterprises, lang, results.page, results.pages);
    })
    .catch(err => {
      logger.error('Error finding enterprises ' + err);
      res.status(500).json({'message': err});
    });
};

function getLanguage(req) {
  let lang = DEFAULT_LANGUAGE;
  if (req.swagger.params.lang &&
      req.swagger.params.lang.value &&
      SUPPORTED_LANGUAGES.indexOf(req.swagger.params.lang.value) > -1) {
    lang = req.swagger.params.lang.value;
  }
  return lang;
}

module.exports.getOneEnterprisePublic = function(req, res) {

  let id = req.swagger.params.id.value;
  let lang = getLanguage(req);

  enterpriseInternationalPublicModel
    .findById(id)
    .then(dbEnterprise => {
      if (!dbEnterprise) {
        return Promise.reject({NotFoundError: true});
      }

      try {
        let tranformedEnterprise = enterpriseAdapter.transformDBIntlEnterpriseToApiFormatForLanguage(dbEnterprise, lang);
        res.set('Cache-Control', 'max-age=' + ENTERPRISE_CACHE_CONTROL);
        res.status(200).json(tranformedEnterprise);
      } catch (e) {
        return Promise.reject(e);
      }
    })
    .catch(err => {
      if (err.NotFoundError) {
        logger.info('Enterprise not found for id ', id);
        res.status(404).json({'message': 'Enterprise not found for id ' + id});
        return;
      }
      logger.error('Error finding enterprise', id, ':', err);
      res.status(500).json({'message': err});
    });
};

module.exports.createEnterprise = function(req, res) {
  let enterprise = req.swagger.params.Enterprise.value;
  let publicEnterprise;
  let privateEnterprise;
  try {
    publicEnterprise = enterpriseAdapter.transformCompleteEnterpriseToInternationalPublicDBFormat(enterprise);
    privateEnterprise = enterpriseAdapter.transformCompleteEnterpriseToInternationalPrivateDBFormat(enterprise);
  } catch (e) {
    res.status(500).json({'message': e});
    return;
  }

  let dbPrivateEnterpriseInfo;
  enterpriseInternationalPrivateFieldsModel.create(privateEnterprise)
    // create public enterprise info
    .then(dbPrivateEnterprise => {
      dbPrivateEnterpriseInfo = dbPrivateEnterprise;
      publicEnterprise['private_info'] = dbPrivateEnterprise['_id'];
      return enterpriseInternationalPublicModel.create(publicEnterprise);
    })
    .then( dbPublicEnterprise => {
      // update private db entry with pointer to public entry
      enterpriseInternationalPrivateFieldsModel.findByIdAndUpdate(
        dbPublicEnterprise['private_info'],
        {$set: {enterprise_id: dbPublicEnterprise['_id']}},
        function(err) {
          if (err) {
            Promise.reject(err);
          }
          // create api response
          let apiEnterprise = enterpriseAdapter.transformDbIntlEnterpriseToApiIntlFormat(dbPublicEnterprise);
          enterpriseAdapter.appendPrivateInfo(apiEnterprise, dbPrivateEnterpriseInfo);
          logger.info(`Enterprise created (name=${apiEnterprise[DEFAULT_LANGUAGE]['name']} id=${apiEnterprise['id']})`);
          res.status(201).json(apiEnterprise);
        }
      );
    })
    .catch(err => {
      logger.error('Error creating enterprise in db ', err, enterprise);
      res.status(400).json({'message': err});
    });
};

module.exports.deleteEnterprise = function(req, res) {
  let id = req.swagger.params.id.value;
  enterpriseInternationalPublicModel
    .findById(id)
    .then(dbEnterprise => {
      if (!dbEnterprise) {
        return Promise.reject({NotFoundError: true});
      }
      return Promise.resolve(dbEnterprise);
    })
    .then(dbEnterprise => {
      return enterpriseInternationalPrivateFieldsModel.remove({ _id: dbEnterprise['private_info'] });
    })
    .then(() => {
      return enterpriseLogoModel.remove({enterpriseId : id});
    })
    .then(() => {
      return enterpriseInternationalPublicModel.remove({_id : id});
    })
    .then(() => {
      res.status(200).json({});
    })
    .catch(err => {
      if (err.NotFoundError) {
        logger.info('Enterprise not found for id ', id);
        res.status(404).json({'message': 'Enterprise not found for id ' + id});
        return;
      }
      logger.error('Error deleting enterprise', id, ':', err);
      res.status(500).json({'message': err});
    });
};

module.exports.editEnterprise = function(req, res) {
  let id = req.swagger.params.id.value;
  let mergeRequest = req.swagger.params.EnterpriseMerge.value;

  enterpriseInternationalPublicModel
    .findById(id)
    .then(dbEnterprise => {
      if (!dbEnterprise) {
        return Promise.reject({NotFoundError: true});
      }
      return Promise.resolve(dbEnterprise);
    })
    .then(dbEnterprise => {
      let mergedEnterprise = enterpriseAdapter.applyMerge(dbEnterprise, mergeRequest);
      return enterpriseInternationalPublicModel.findOneAndUpdate({_id: dbEnterprise._id}, mergedEnterprise);
    })
    .then(result => {
      if (!result) {
        res.status(500).json({'message': 'Failed to update db'});
        return;
      }
      res.status(200).json({});
    })
    .catch(err => {
      if (err.NotFoundError) {
        logger.info('Enterprise not found for id ', id);
        res.status(404).json({'message': 'Enterprise not found for id ' + id});
        return;
      }
      logger.error('Error updating enterprise', id, ':', err);
      res.status(500).json({'message': err});
    });
};

module.exports.getEnterpriseAdmins = function(req, res) {
  let id = req.swagger.params.id.value;
  enterpriseInternationalPrivateFieldsModel
    .findOne({enterprise_id: id})
    .then(dbEnterprise => {
      if (!dbEnterprise) {
        return Promise.reject({NotFoundError: true});
      }
      res.status(200).json({admin_emails: dbEnterprise.admin_emails});
    })
    .catch(err => {
      if (err.NotFoundError) {
        logger.info('Enterprise admin info not found for id ', id);
        res.status(404).json({'message': 'Enterprise admin info not found for id ' + id});
        return;
      }
      logger.error('Error finding enterprise admins', id, ':', err);
      res.status(500).json({'message': err});
    });
};

module.exports.editEnterprisePrivateFields = function(req, res) {
  let id = req.swagger.params.id.value;
  let mergeRequest = req.swagger.params.EnterpriseMerge.value;

  enterpriseInternationalPrivateFieldsModel
    .findOne({enterprise_id: id})
    .then(dbEnterprise => {
      if (!dbEnterprise) {
        return Promise.reject({NotFoundError: true});
      }
      return Promise.resolve(dbEnterprise);
    })
    .then(dbEnterprise => {
      let mergedEnterprise = enterpriseAdapter.applyMerge(dbEnterprise, mergeRequest);
      return enterpriseInternationalPrivateFieldsModel.findOneAndUpdate({_id: dbEnterprise._id}, mergedEnterprise);
    })
    .then(result => {
      if (!result) {
        res.status(500).json({'message': 'Failed to update db'});
        return;
      }
      res.status(200).json({});
      return Promise.resolve(null);
    })
    .catch(err => {
      if (err.NotFoundError) {
        logger.info('Enterprise admin info not found for id ', id);
        res.status(404).json({'message': 'Enterprise admin info not found for id ' + id});
        return;
      }
      logger.error('Error updating enterprise admins', id, ':', err);
      res.status(500).json({'message': err});
    });
};

module.exports.getEnterpriseLogo = function(req, res) {
  let id = req.swagger.params.id.value;
  enterpriseLogoModel
    .findOne({enterpriseId : id})
    .then( dbLogo => {
      if (!dbLogo) {
        return Promise.reject({NotFoundError: true});
      }

      res.set('Content-Type', dbLogo.contentType);
      res.set('Cache-Control', 'max-age=' + ENTERPRISE_CACHE_CONTROL);
      res.status(200).send(dbLogo.image);
    })
    .catch( err => {
      if (err.NotFoundError) {
        logger.info('Enterprise logo not found for id ', id);
        res.status(404).json({'message': 'Enterprise logo not found for id ' + id});
        return;
      }
      logger.error('Error finding enterprise logo', id, ':', err);
      res.status(500).json({'message': err});
    });
};

function validateLogoFileType(contentType, res) {
  contentType = contentType.toLowerCase();
  if (!SUPPORTED_IMAGE_TYPES.includes(contentType)) {
    res.status(400).json({
      message: 'Specified content type is not supported. Supported values: ' +
      SUPPORTED_IMAGE_TYPES
    });
    return false;
  }
  return true;
}

module.exports.createEnterpriseLogo = function(req, res) {
  let id = req.swagger.params.id.value;
  let logoParam = req.swagger.params.logo.value;
  let contentType = logoParam.content_type;
  if (!validateLogoFileType(contentType, res)) {
    return;
  }

  let dbLogo = {
    enterpriseId: new mongoose.mongo.ObjectId(id),
    image: Buffer.from(logoParam.logo, 'base64'),
    contentType: contentType
  };

  enterpriseLogoModel
    .create(dbLogo)
    .then( () => {
      res.status(201).send({});
    })
    .catch( err => {
      logger.error('Error creating enterprise logo', id, ':', err);
      res.status(500).json({'message': err});
    });
};

module.exports.editEnterpriseLogo = function(req, res) {
  let id = req.swagger.params.id.value;
  let logoParam = req.swagger.params.logo.value;
  let contentType = logoParam.content_type;
  if (!validateLogoFileType(contentType, res)) {
    return;
  }

  let updatedLogo = {
    enterpriseId: new mongoose.mongo.ObjectId(id),
    image: Buffer.from(logoParam.logo, 'base64'),
    contentType: contentType
  };

  enterpriseLogoModel
    .find({enterpriseId : id})
    .then(dbLogo => {
      if (!dbLogo) {
        return Promise.reject({NotFoundError: true});
      }
      return Promise.resolve(dbLogo);
    })
    .then(() => {
      return enterpriseLogoModel.findOneAndUpdate({enterpriseId : id}, updatedLogo);
    })
    .then(() => {
      res.status(200).json({});
    })
    .catch(err => {
      if (err.NotFoundError) {
        logger.info('Enterprise logo not found for id ', id);
        res.status(404).json({'message': 'Enterprise logo not found for id ' + id});
        return;
      }
      logger.error('Error updating enterprise logo', id, ':', err);
      res.status(500).json({'message': err});
    });
};

module.exports.deleteEnterpriseLogo = function(req, res) {
  let id = req.swagger.params.id.value;
  enterpriseLogoModel
    .find({enterpriseId : id})
    .then(dbLogo => {
      if (!dbLogo) {
        return Promise.reject({NotFoundError: true});
      }
      return Promise.resolve(dbLogo);
    })
    .then(() => {
      return enterpriseLogoModel.remove({enterpriseId : id});
    })
    .then(() => {
      res.status(200).json({});
    })
    .catch(err => {
      if (err.NotFoundError) {
        logger.info('Enterprise logo not found for id ', id);
        res.status(404).json({'message': 'Enterprise logo not found for id ' + id});
        return;
      }
      logger.error('Error deleting enterprise logo', id, ':', err);
      res.status(500).json({'message': err});
    });
};
<commit_msg>Fix 'browse' button and query-less search<commit_after>const mongoose = require('mongoose');
const logger = require('../../lib/logger');
const coordsUtil = require('../../lib/coords_util');
const conf = require('../../config/config.js');

const enterpriseInternationalPublicModel = mongoose.model('EnterpriseInternationalPublic');
const enterpriseInternationalPrivateFieldsModel = mongoose.model('EnterpriseInternationalPrivateFields');
const enterpriseLogoModel = mongoose.model('EnterpriseLogo');
const enterpriseAdapter = require('./enterprise.adapter');
const SUPPORTED_LANGUAGES = require('../helpers/language/constants').SUPPORTED_LANGUAGES;
const DEFAULT_LANGUAGE = require('../helpers/language/constants').DEFAULT_LANGUAGE;
const SUPPORTED_IMAGE_TYPES = ['image/png', 'image/gif', 'image/jpeg', 'image/svg+xml'];

const ENTERPRISE_CACHE_CONTROL = conf.get('enterpriseCacheControl');

function locationParamToPointObject(locationSearch) {
  let [longStr, latStr] = locationSearch.split(',');
  let long = parseFloat(longStr);
  let lat = parseFloat(latStr);
  if (!coordsUtil.isValidCoords(long, lat)) {
    return undefined;
  }
  let point = { type : 'Point', coordinates : [long,lat] };
  return point;
}

function processDirectoryResults(res, dbEnterprises, language, page, pages) {
  if (!dbEnterprises) {
    res.status(200).json({});
    return;
  }

  let transformedEnterprises = enterpriseAdapter.transformDbEnterprisesToApiFormatForLanguage(dbEnterprises, language);
  res.set('Cache-Control', 'max-age=' + ENTERPRISE_CACHE_CONTROL);
  res.status(200).json({
    enterprises: transformedEnterprises,
    page: page,
    pages: pages
  });
}

function performLocationSearch(res, locationSearch, limit, offset, language) {
  let point = locationParamToPointObject(locationSearch);
  if (!point) {
    res.status(400).json({'message': 'Invalid location parameter'});
    return;
  }

  enterpriseInternationalPublicModel.aggregate(
    [
      { '$geoNear': {
        'near': point,
        'spherical': true,
        'distanceField': 'dis'
      }},
      { '$skip': offset },
      { '$limit': limit }
    ])
  .then(dbEnterprises => {
    processDirectoryResults(res, dbEnterprises, language);
  })
  .catch(err => {
    logger.error('Error finding enterprises ' + err);
    res.status(500).json({'message': err});
  });
}

function performBrowseDirectory(res, limit, page, language) {
  let sortValue = {};
  sortValue[language + '.lowercase_name'] = 1;

  let queryOptions = {
    limit: limit,
    page: page,
    sort: sortValue
  };

  enterpriseInternationalPublicModel.paginate("", queryOptions)
    .then(results => {
      let dbEnterprises = results.docs;

      processDirectoryResults(res, dbEnterprises, language, results.page, results.pages);
    })
    .catch(err => {
      logger.error('Error browsing enterprises ' + err);
      res.status(500).json({'message': err});
    });
}

module.exports.getAllEnterprisesPublic = function(req, res) {
  let search = req.swagger.params.q.value;
  let locationSearch = req.swagger.params.at.value;

  let limit = req.swagger.params.count.value || 25;
  let page = req.swagger.params.page.value || 1;

  let lang = getLanguage(req);

  if (locationSearch) {
    performLocationSearch(res, locationSearch, limit, offset, lang);
    return;
  }

  if (!search) {
    performBrowseDirectory(res, limit, page, lang);
    return;
  }

  let queryOptions = {
    limit: limit,
    page: page
  };

  let query = {
    '$text': {
      '$search': search
    }
  };

  enterpriseInternationalPublicModel.paginate(query, queryOptions)
    .then(results => {
      let dbEnterprises = results.docs;

      processDirectoryResults(res, dbEnterprises, lang, results.page, results.pages);
    })
    .catch(err => {
      logger.error('Error finding enterprises ' + err);
      res.status(500).json({'message': err});
    });
};

function getLanguage(req) {
  let lang = DEFAULT_LANGUAGE;
  if (req.swagger.params.lang &&
      req.swagger.params.lang.value &&
      SUPPORTED_LANGUAGES.indexOf(req.swagger.params.lang.value) > -1) {
    lang = req.swagger.params.lang.value;
  }
  return lang;
}

module.exports.getOneEnterprisePublic = function(req, res) {

  let id = req.swagger.params.id.value;
  let lang = getLanguage(req);

  enterpriseInternationalPublicModel
    .findById(id)
    .then(dbEnterprise => {
      if (!dbEnterprise) {
        return Promise.reject({NotFoundError: true});
      }

      try {
        let tranformedEnterprise = enterpriseAdapter.transformDBIntlEnterpriseToApiFormatForLanguage(dbEnterprise, lang);
        res.set('Cache-Control', 'max-age=' + ENTERPRISE_CACHE_CONTROL);
        res.status(200).json(tranformedEnterprise);
      } catch (e) {
        return Promise.reject(e);
      }
    })
    .catch(err => {
      if (err.NotFoundError) {
        logger.info('Enterprise not found for id ', id);
        res.status(404).json({'message': 'Enterprise not found for id ' + id});
        return;
      }
      logger.error('Error finding enterprise', id, ':', err);
      res.status(500).json({'message': err});
    });
};

module.exports.createEnterprise = function(req, res) {
  let enterprise = req.swagger.params.Enterprise.value;
  let publicEnterprise;
  let privateEnterprise;
  try {
    publicEnterprise = enterpriseAdapter.transformCompleteEnterpriseToInternationalPublicDBFormat(enterprise);
    privateEnterprise = enterpriseAdapter.transformCompleteEnterpriseToInternationalPrivateDBFormat(enterprise);
  } catch (e) {
    res.status(500).json({'message': e});
    return;
  }

  let dbPrivateEnterpriseInfo;
  enterpriseInternationalPrivateFieldsModel.create(privateEnterprise)
    // create public enterprise info
    .then(dbPrivateEnterprise => {
      dbPrivateEnterpriseInfo = dbPrivateEnterprise;
      publicEnterprise['private_info'] = dbPrivateEnterprise['_id'];
      return enterpriseInternationalPublicModel.create(publicEnterprise);
    })
    .then( dbPublicEnterprise => {
      // update private db entry with pointer to public entry
      enterpriseInternationalPrivateFieldsModel.findByIdAndUpdate(
        dbPublicEnterprise['private_info'],
        {$set: {enterprise_id: dbPublicEnterprise['_id']}},
        function(err) {
          if (err) {
            Promise.reject(err);
          }
          // create api response
          let apiEnterprise = enterpriseAdapter.transformDbIntlEnterpriseToApiIntlFormat(dbPublicEnterprise);
          enterpriseAdapter.appendPrivateInfo(apiEnterprise, dbPrivateEnterpriseInfo);
          logger.info(`Enterprise created (name=${apiEnterprise[DEFAULT_LANGUAGE]['name']} id=${apiEnterprise['id']})`);
          res.status(201).json(apiEnterprise);
        }
      );
    })
    .catch(err => {
      logger.error('Error creating enterprise in db ', err, enterprise);
      res.status(400).json({'message': err});
    });
};

module.exports.deleteEnterprise = function(req, res) {
  let id = req.swagger.params.id.value;
  enterpriseInternationalPublicModel
    .findById(id)
    .then(dbEnterprise => {
      if (!dbEnterprise) {
        return Promise.reject({NotFoundError: true});
      }
      return Promise.resolve(dbEnterprise);
    })
    .then(dbEnterprise => {
      return enterpriseInternationalPrivateFieldsModel.remove({ _id: dbEnterprise['private_info'] });
    })
    .then(() => {
      return enterpriseLogoModel.remove({enterpriseId : id});
    })
    .then(() => {
      return enterpriseInternationalPublicModel.remove({_id : id});
    })
    .then(() => {
      res.status(200).json({});
    })
    .catch(err => {
      if (err.NotFoundError) {
        logger.info('Enterprise not found for id ', id);
        res.status(404).json({'message': 'Enterprise not found for id ' + id});
        return;
      }
      logger.error('Error deleting enterprise', id, ':', err);
      res.status(500).json({'message': err});
    });
};

module.exports.editEnterprise = function(req, res) {
  let id = req.swagger.params.id.value;
  let mergeRequest = req.swagger.params.EnterpriseMerge.value;

  enterpriseInternationalPublicModel
    .findById(id)
    .then(dbEnterprise => {
      if (!dbEnterprise) {
        return Promise.reject({NotFoundError: true});
      }
      return Promise.resolve(dbEnterprise);
    })
    .then(dbEnterprise => {
      let mergedEnterprise = enterpriseAdapter.applyMerge(dbEnterprise, mergeRequest);
      return enterpriseInternationalPublicModel.findOneAndUpdate({_id: dbEnterprise._id}, mergedEnterprise);
    })
    .then(result => {
      if (!result) {
        res.status(500).json({'message': 'Failed to update db'});
        return;
      }
      res.status(200).json({});
    })
    .catch(err => {
      if (err.NotFoundError) {
        logger.info('Enterprise not found for id ', id);
        res.status(404).json({'message': 'Enterprise not found for id ' + id});
        return;
      }
      logger.error('Error updating enterprise', id, ':', err);
      res.status(500).json({'message': err});
    });
};

module.exports.getEnterpriseAdmins = function(req, res) {
  let id = req.swagger.params.id.value;
  enterpriseInternationalPrivateFieldsModel
    .findOne({enterprise_id: id})
    .then(dbEnterprise => {
      if (!dbEnterprise) {
        return Promise.reject({NotFoundError: true});
      }
      res.status(200).json({admin_emails: dbEnterprise.admin_emails});
    })
    .catch(err => {
      if (err.NotFoundError) {
        logger.info('Enterprise admin info not found for id ', id);
        res.status(404).json({'message': 'Enterprise admin info not found for id ' + id});
        return;
      }
      logger.error('Error finding enterprise admins', id, ':', err);
      res.status(500).json({'message': err});
    });
};

module.exports.editEnterprisePrivateFields = function(req, res) {
  let id = req.swagger.params.id.value;
  let mergeRequest = req.swagger.params.EnterpriseMerge.value;

  enterpriseInternationalPrivateFieldsModel
    .findOne({enterprise_id: id})
    .then(dbEnterprise => {
      if (!dbEnterprise) {
        return Promise.reject({NotFoundError: true});
      }
      return Promise.resolve(dbEnterprise);
    })
    .then(dbEnterprise => {
      let mergedEnterprise = enterpriseAdapter.applyMerge(dbEnterprise, mergeRequest);
      return enterpriseInternationalPrivateFieldsModel.findOneAndUpdate({_id: dbEnterprise._id}, mergedEnterprise);
    })
    .then(result => {
      if (!result) {
        res.status(500).json({'message': 'Failed to update db'});
        return;
      }
      res.status(200).json({});
      return Promise.resolve(null);
    })
    .catch(err => {
      if (err.NotFoundError) {
        logger.info('Enterprise admin info not found for id ', id);
        res.status(404).json({'message': 'Enterprise admin info not found for id ' + id});
        return;
      }
      logger.error('Error updating enterprise admins', id, ':', err);
      res.status(500).json({'message': err});
    });
};

module.exports.getEnterpriseLogo = function(req, res) {
  let id = req.swagger.params.id.value;
  enterpriseLogoModel
    .findOne({enterpriseId : id})
    .then( dbLogo => {
      if (!dbLogo) {
        return Promise.reject({NotFoundError: true});
      }

      res.set('Content-Type', dbLogo.contentType);
      res.set('Cache-Control', 'max-age=' + ENTERPRISE_CACHE_CONTROL);
      res.status(200).send(dbLogo.image);
    })
    .catch( err => {
      if (err.NotFoundError) {
        logger.info('Enterprise logo not found for id ', id);
        res.status(404).json({'message': 'Enterprise logo not found for id ' + id});
        return;
      }
      logger.error('Error finding enterprise logo', id, ':', err);
      res.status(500).json({'message': err});
    });
};

function validateLogoFileType(contentType, res) {
  contentType = contentType.toLowerCase();
  if (!SUPPORTED_IMAGE_TYPES.includes(contentType)) {
    res.status(400).json({
      message: 'Specified content type is not supported. Supported values: ' +
      SUPPORTED_IMAGE_TYPES
    });
    return false;
  }
  return true;
}

module.exports.createEnterpriseLogo = function(req, res) {
  let id = req.swagger.params.id.value;
  let logoParam = req.swagger.params.logo.value;
  let contentType = logoParam.content_type;
  if (!validateLogoFileType(contentType, res)) {
    return;
  }

  let dbLogo = {
    enterpriseId: new mongoose.mongo.ObjectId(id),
    image: Buffer.from(logoParam.logo, 'base64'),
    contentType: contentType
  };

  enterpriseLogoModel
    .create(dbLogo)
    .then( () => {
      res.status(201).send({});
    })
    .catch( err => {
      logger.error('Error creating enterprise logo', id, ':', err);
      res.status(500).json({'message': err});
    });
};

module.exports.editEnterpriseLogo = function(req, res) {
  let id = req.swagger.params.id.value;
  let logoParam = req.swagger.params.logo.value;
  let contentType = logoParam.content_type;
  if (!validateLogoFileType(contentType, res)) {
    return;
  }

  let updatedLogo = {
    enterpriseId: new mongoose.mongo.ObjectId(id),
    image: Buffer.from(logoParam.logo, 'base64'),
    contentType: contentType
  };

  enterpriseLogoModel
    .find({enterpriseId : id})
    .then(dbLogo => {
      if (!dbLogo) {
        return Promise.reject({NotFoundError: true});
      }
      return Promise.resolve(dbLogo);
    })
    .then(() => {
      return enterpriseLogoModel.findOneAndUpdate({enterpriseId : id}, updatedLogo);
    })
    .then(() => {
      res.status(200).json({});
    })
    .catch(err => {
      if (err.NotFoundError) {
        logger.info('Enterprise logo not found for id ', id);
        res.status(404).json({'message': 'Enterprise logo not found for id ' + id});
        return;
      }
      logger.error('Error updating enterprise logo', id, ':', err);
      res.status(500).json({'message': err});
    });
};

module.exports.deleteEnterpriseLogo = function(req, res) {
  let id = req.swagger.params.id.value;
  enterpriseLogoModel
    .find({enterpriseId : id})
    .then(dbLogo => {
      if (!dbLogo) {
        return Promise.reject({NotFoundError: true});
      }
      return Promise.resolve(dbLogo);
    })
    .then(() => {
      return enterpriseLogoModel.remove({enterpriseId : id});
    })
    .then(() => {
      res.status(200).json({});
    })
    .catch(err => {
      if (err.NotFoundError) {
        logger.info('Enterprise logo not found for id ', id);
        res.status(404).json({'message': 'Enterprise logo not found for id ' + id});
        return;
      }
      logger.error('Error deleting enterprise logo', id, ':', err);
      res.status(500).json({'message': err});
    });
};
<|endoftext|>


<commit_before>function preparePermits(rows, before = null, after = null) {
  if (rows.length === 0) return [];
  let curPermit = null;
  let curContractors = {};
  let curComments = {};
  const fResults = [];
  // We get a row per unique contractor per unique comment id, so we have
  // to filter down to just the unique information.
  rows.forEach(itm => {
    if (curPermit === null || curPermit.permit_number !== itm.permit_num) {
      curPermit = {
        permit_number: itm.permit_num,
        permit_group: itm.permit_group,
        permit_type: itm.permit_type,
        permit_subtype: itm.permit_subtype,
        permit_category: itm.permit_category,
        permit_description: itm.permit_description,
        applicant_name: itm.applicant_name,
        applied_date: itm.applied_date,
        status_current: itm.status_current,
        status_date: itm.status_date,
        civic_address_id: itm.civic_address_id,
        address: itm.address,
        created_by: itm.created_by,
        building_value: itm.building_value,
        job_value: itm.job_value,
        total_project_valuation: itm.total_project_valuation,
        total_sq_feet: itm.total_sq_feet,
        fees: itm.fees,
        paid: itm.paid,
        balance: itm.balance,
        invoiced_fee_total: itm.invoiced_fee_total,
        x: itm.x,
        y: itm.y,
        contractor_names: [],
        contractor_license_numbers: [],
        comments: [],
      };
      curContractors = {};
      curComments = {};
      fResults.push(curPermit);
    }
    if (itm.contractor_name !== null &&
        !curContractors.hasOwnProperty(itm.contractor_license_number)) {
      curContractors[itm.contractor_name] = true;
      curPermit.contractor_names.push(itm.contractor_name);
      curPermit.contractor_license_numbers.push(itm.contractor_license_number);
    }
    if (itm.comment_seq_number !== null &&
        !curComments.hasOwnProperty(itm.comment_seq_number)) {
      curPermit.comments.push({
        comment_seq_number: itm.comment_seq_number,
        comment_date: itm.comment_date,
        comments: itm.comments,
      });
      curComments[itm.comment_seq_number] = true;
    }
  });

  const final = fResults.filter((item) => {
    let keep = true;
    if (after || before) {
      const date1 = new Date(item.applied_date);
      if (after && date1 < new Date(`${after} 00:00:00 GMT-0500`)) {
        keep = false;
      }
      if (keep && before && date1 > new Date(`${before} 00:00:00 GMT-0500`)) {
        keep = false;
      }
    }
    return keep;
  });
  return final;
}

function preparePermitTasks(rows) {
  if (rows.length === 0) return [];
  return rows.map(itm => {
    return {
      permit_number: itm.permit_num,
      permit_group: itm.permit_group,
      permit_type: itm.permit_type,
      permit_subtype: itm.permit_subtype,
      permit_category: itm.permit_category,
      permit_description: itm.permit_description,
      process_code: itm.process_code,
      task: itm.task,
      task_status: itm.task_status,
      current_status_date: itm.current_status_date,
      step_number: itm.step_number,
      relation_sequence_id: itm.relation_sequence_id,
      parent_task_name: itm.parent_task_name,
      user_name: itm.user_name,
      user_id: itm.user_id,
      user_department: itm.user_department,
      due_date: itm.due_date,
      record_date: itm.record_date,
      comments: itm.comments,
      is_completed: itm.is_completed === 'Y',
      is_active: itm.is_active === 'Y',
      assigned_date: itm.assigned_date,
      assigned_user: itm.assigned_user,
      assigned_department: itm.assigned_department,
      process_history_sequence_number: itm.process_history_sequence_number,
      record_id: itm.record_id,
    };
  });
}

const stdQuery = 'SELECT A.permit_num, A.permit_group, A.permit_type, '
              + 'A.permit_subtype, A.permit_category, A.permit_description, '
              + 'A.applicant_name, A.applied_date, A.status_current, A.status_date, '
              + 'A.created_by, A.building_value, A.job_value, A.total_project_valuation, '
              + 'A.total_sq_feet, A.fees, A.paid, A.balance, A.invoiced_fee_total, '
              + 'A.civic_address_id, A.address, A.contractor_name, '
              + 'A.contractor_license_number, A.longitude as x, A.latitude as y, '
              + 'B.comment_seq_number, B.comment_date, B.comments ';
const resolvers = {
  Query: {
    firstReviewSLASummary(obj, args, context) {
      const pool = context.pool;
      let tasks = null;
      let q = 'select * from amd.dsd_first_review_sla_summary';
      if (args.tasks) {
        args.tasks.forEach(t => {
          tasks = (tasks === null) ? `'${t}'` : `${tasks}, '${t}'`;
        });
        q += ` where task in (${tasks})`;
      }
      return pool.query(q)
      .then(result => {
        if (result.rows.length === 0) return [];
        return result.rows.map(item => {
          const total = Number(item.met_sla) + Number(item.past_sla);
          const pct = 100.0 * Number(item.met_sla) / total;
          return {
            task: item.task,
            met_sla: item.met_sla,
            past_sla: item.past_sla,
            met_sla_percent: pct.toPrecision(5),
            month: item.month,
            year: item.year,
          };
        });
      })
      .catch(err => {
        if (err) {
          console.log(`Error in firstReviewSLASummary: ${JSON.stringify(err)}`);
        }
        return [];
      });
    },
    permits(obj, args, context) {
      const qargs = [];
      let query = `${stdQuery}`
      + 'FROM amd.permits_xy_view AS A '
      + 'LEFT JOIN amd.mda_permit_comments AS B on A.permit_num = B.permit_num ';
      if (args.permit_numbers && args.permit_numbers.length > 0) {
        qargs.push(args.permit_numbers);
        query += 'WHERE A.permit_num = ANY ($1) ';
      } else if (args.before || args.after) {
        const dateField = (args.date_field === 'status_date') ? 'status_date' : 'applied_date';
        let nextParam = '$1';
        query += 'where ';
        if (args.before) {
          query += `${dateField} < $1 `;
          nextParam = '$2';
          if (args.after) query += 'and ';
          qargs.push(args.before);
        }
        if (args.after) {
          query += `${dateField} > ${nextParam} `;
          qargs.push(args.after);
        }
      }
      query += 'ORDER BY A.permit_num DESC, B.comment_seq_number ASC ';
      return context.pool.query(query, qargs)
      .then((result) => {
        return preparePermits(result.rows);
      })
      .catch((err) => {
        throw new Error(`Got an error in permits: ${JSON.stringify(err)}`);
      });
    },
    permits_by_address(obj, args, context) {
      const logger = context.logger;
      const radius = args.radius ? Number(args.radius) : 10; // State plane units are feet
      let query = `${stdQuery}`
      + 'from amd.permits_xy_view as A '
      + 'left outer join amd.coa_bc_address_master as M '
      + 'on ST_Point_Inside_Circle(ST_SetSRID(ST_Point(A.address_x, A.address_y),2264), M.address_x, M.address_y, $2) ' // eslint-disable-line max-len
      + 'LEFT JOIN amd.mda_permit_comments AS B on A.permit_num = B.permit_num '
      + 'where M.civicaddress_id = $1 '
      + "AND A.permit_group <> 'Services'"; // Future function name change - ST_PointInsideCircle
      const qargs = [String(args.civicaddress_id), radius];
      let nextParam = '$3';
      if (args.before !== undefined) {
        qargs.push(`'${args.before}'`);
        query += `and applied_date < ${nextParam} `;
        nextParam = '$4';
      }
      if (args.after !== undefined) {
        qargs.push(`'${args.after}'`);
        query += `and applied_date > ${nextParam} `;
      }
      query += 'ORDER BY A.permit_num DESC, B.comment_seq_number ASC ';

      return context.pool.query(query, qargs)
      .then(result => {
        return preparePermits(result.rows, args.before, args.after);
      })
      .catch((err) => {
        logger.error(`Got an error in permits_by_address: ${err}`);
        throw new Error(`Got an error in permits_by_address: ${err}`);
      });
    },
    permits_by_street(obj, args, context) {
      const logger = context.logger;
      const radius = (args.radius) ? Number(args.radius) : 100; // State plane units are feet
      if (args.centerline_ids.length <= 0) return [];
      const query = 'SELECT A.*, M.address_full as address FROM amd.permits_along_streets_fn($1, $2) AS A ' // eslint-disable-line max-len
      + 'LEFT JOIN amd.coa_bc_address_master as M ON A.civic_address_id::INT = M.civicaddress_id '
      + "WHERE permit_group <> 'Services'"
      + 'ORDER BY permit_num DESC, comment_seq_number ASC ';

      return context.pool.query(query, [args.centerline_ids, radius])
      .then(result => {
        return preparePermits(result.rows, args.before, args.after);
      })
      .catch((err) => {
        if (err) {
          logger.error(`Got an error in permits_by_street: ${err}`);
          throw new Error(err);
        }
      });
    },
    permits_by_neighborhood(obj, args, context) {
      const logger = context.logger;
      if (args.nbrhd_ids.length <= 0) return [];
      const query = 'SELECT A.*, M.address_full as address '
      + 'FROM amd.permits_by_neighborhood_fn($1) AS A '
      + 'LEFT JOIN amd.coa_bc_address_master as M ON A.civic_address_id::INT = M.civicaddress_id '
      + "WHERE permit_group <> 'Services' "
      + 'ORDER BY permit_num DESC, comment_seq_number ASC ';
      return context.pool.query(query, [args.nbrhd_ids])
      .then(result => {
        return preparePermits(result.rows, args.before, args.after);
      })
      .catch((err) => {
        if (err) {
          logger.error(`Got an error in permits_by_neighborhood: ${err}`);
          throw new Error(err);
        }
      });
    },
    firstReviewSLAItems(obj, args, context) {
      const pool = context.pool;
      return pool.query(
        'SELECT * from amd.dsd_first_review_sla'
      )
      .then((result) => {
        if (result.rows.length === 0) return null;
        const p = result.rows;
        return p;
      })
      .catch((err) => {
        if (err) {
          console.log(`Got an error in firstReviewSLAItems: ${JSON.stringify(err)}`);
        }
      });
    },
    permit_tasks(obj, args, context) {
      const qargs = [];
      let query = 'SELECT * FROM amd.permit_tasks AS A ';
      if (args.permit_numbers && args.permit_numbers.length > 0) {
        qargs.push(args.permit_numbers);
        query += 'WHERE A.permit_num = ANY ($1) ';
      } else if (args.before || args.after) {
        const dateField = args.date_field || 'current_status_date';
        let nextParam = '$1';
        query += 'where ';
        if (args.before) {
          query += `${dateField} < $1 `;
          nextParam = '$2';
          if (args.after) query += 'and ';
          qargs.push(args.before);
        }
        if (args.after) {
          query += `${dateField} > ${nextParam} `;
          qargs.push(args.after);
        }
      }
      query += 'ORDER BY A.permit_num DESC ';
      return context.pool.query(query, qargs)
      .then((result) => {
        return preparePermitTasks(result.rows);
      })
      .catch((err) => {
        throw new Error(`Got an error in permit_tasks: ${JSON.stringify(err)}`);
      });
    },
  },

  Permit: {
    comments(obj, args, context) { // eslint-disable-line no-unused-vars
      return obj.comments;
    },
  },
};

module.exports = resolvers;
<commit_msg>Removed reference to mda_permit_comments table<commit_after>function preparePermits(rows, before = null, after = null) {
  if (rows.length === 0) return [];
  let curPermit = null;
  let curContractors = {};
  let curComments = {};
  const fResults = [];
  // We get a row per unique contractor per unique comment id, so we have
  // to filter down to just the unique information.
  rows.forEach(itm => {
    if (curPermit === null || curPermit.permit_number !== itm.permit_num) {
      curPermit = {
        permit_number: itm.permit_num,
        permit_group: itm.permit_group,
        permit_type: itm.permit_type,
        permit_subtype: itm.permit_subtype,
        permit_category: itm.permit_category,
        permit_description: itm.permit_description,
        applicant_name: itm.applicant_name,
        applied_date: itm.applied_date,
        status_current: itm.status_current,
        status_date: itm.status_date,
        civic_address_id: itm.civic_address_id,
        address: itm.address,
        created_by: itm.created_by,
        building_value: itm.building_value,
        job_value: itm.job_value,
        total_project_valuation: itm.total_project_valuation,
        total_sq_feet: itm.total_sq_feet,
        fees: itm.fees,
        paid: itm.paid,
        balance: itm.balance,
        invoiced_fee_total: itm.invoiced_fee_total,
        x: itm.x,
        y: itm.y,
        contractor_names: [],
        contractor_license_numbers: [],
        comments: [],
      };
      curContractors = {};
      curComments = {};
      fResults.push(curPermit);
    }
    if (itm.contractor_name !== null &&
        !curContractors.hasOwnProperty(itm.contractor_license_number)) {
      curContractors[itm.contractor_name] = true;
      curPermit.contractor_names.push(itm.contractor_name);
      curPermit.contractor_license_numbers.push(itm.contractor_license_number);
    }
    if (itm.comment_seq_number !== null &&
        !curComments.hasOwnProperty(itm.comment_seq_number)) {
      curPermit.comments.push({
        comment_seq_number: itm.comment_seq_number,
        comment_date: itm.comment_date,
        comments: itm.comments,
      });
      curComments[itm.comment_seq_number] = true;
    }
  });

  const final = fResults.filter((item) => {
    let keep = true;
    if (after || before) {
      const date1 = new Date(item.applied_date);
      if (after && date1 < new Date(`${after} 00:00:00 GMT-0500`)) {
        keep = false;
      }
      if (keep && before && date1 > new Date(`${before} 00:00:00 GMT-0500`)) {
        keep = false;
      }
    }
    return keep;
  });
  return final;
}

function preparePermitTasks(rows) {
  if (rows.length === 0) return [];
  return rows.map(itm => {
    return {
      permit_number: itm.permit_num,
      permit_group: itm.permit_group,
      permit_type: itm.permit_type,
      permit_subtype: itm.permit_subtype,
      permit_category: itm.permit_category,
      permit_description: itm.permit_description,
      process_code: itm.process_code,
      task: itm.task,
      task_status: itm.task_status,
      current_status_date: itm.current_status_date,
      step_number: itm.step_number,
      relation_sequence_id: itm.relation_sequence_id,
      parent_task_name: itm.parent_task_name,
      user_name: itm.user_name,
      user_id: itm.user_id,
      user_department: itm.user_department,
      due_date: itm.due_date,
      record_date: itm.record_date,
      comments: itm.comments,
      is_completed: itm.is_completed === 'Y',
      is_active: itm.is_active === 'Y',
      assigned_date: itm.assigned_date,
      assigned_user: itm.assigned_user,
      assigned_department: itm.assigned_department,
      process_history_sequence_number: itm.process_history_sequence_number,
      record_id: itm.record_id,
    };
  });
}

const stdQuery = 'SELECT A.permit_num, A.permit_group, A.permit_type, '
              + 'A.permit_subtype, A.permit_category, A.permit_description, '
              + 'A.applicant_name, A.applied_date, A.status_current, A.status_date, '
              + 'A.created_by, A.building_value, A.job_value, A.total_project_valuation, '
              + 'A.total_sq_feet, A.fees, A.paid, A.balance, A.invoiced_fee_total, '
              + 'A.civic_address_id, A.address, A.contractor_name, '
              + 'A.contractor_license_number, A.longitude as x, A.latitude as y, '
              + 'B.comment_seq_number, B.comment_date, B.comments ';
const resolvers = {
  Query: {
    firstReviewSLASummary(obj, args, context) {
      const pool = context.pool;
      let tasks = null;
      let q = 'select * from amd.dsd_first_review_sla_summary';
      if (args.tasks) {
        args.tasks.forEach(t => {
          tasks = (tasks === null) ? `'${t}'` : `${tasks}, '${t}'`;
        });
        q += ` where task in (${tasks})`;
      }
      return pool.query(q)
      .then(result => {
        if (result.rows.length === 0) return [];
        return result.rows.map(item => {
          const total = Number(item.met_sla) + Number(item.past_sla);
          const pct = 100.0 * Number(item.met_sla) / total;
          return {
            task: item.task,
            met_sla: item.met_sla,
            past_sla: item.past_sla,
            met_sla_percent: pct.toPrecision(5),
            month: item.month,
            year: item.year,
          };
        });
      })
      .catch(err => {
        if (err) {
          console.log(`Error in firstReviewSLASummary: ${JSON.stringify(err)}`);
        }
        return [];
      });
    },
    permits(obj, args, context) {
      const qargs = [];
      let query = `${stdQuery}`
      + 'FROM amd.permits_xy_view AS A '
      + 'LEFT JOIN amd.permit_comments AS B on A.permit_num = B.permit_num ';
      if (args.permit_numbers && args.permit_numbers.length > 0) {
        qargs.push(args.permit_numbers);
        query += 'WHERE A.permit_num = ANY ($1) ';
      } else if (args.before || args.after) {
        const dateField = (args.date_field === 'status_date') ? 'status_date' : 'applied_date';
        let nextParam = '$1';
        query += 'where ';
        if (args.before) {
          query += `${dateField} < $1 `;
          nextParam = '$2';
          if (args.after) query += 'and ';
          qargs.push(args.before);
        }
        if (args.after) {
          query += `${dateField} > ${nextParam} `;
          qargs.push(args.after);
        }
      }
      query += 'ORDER BY A.permit_num DESC, B.comment_seq_number ASC ';
      return context.pool.query(query, qargs)
      .then((result) => {
        return preparePermits(result.rows);
      })
      .catch((err) => {
        throw new Error(`Got an error in permits: ${JSON.stringify(err)}`);
      });
    },
    permits_by_address(obj, args, context) {
      const logger = context.logger;
      const radius = args.radius ? Number(args.radius) : 10; // State plane units are feet
      let query = `${stdQuery}`
      + 'from amd.permits_xy_view as A '
      + 'left outer join amd.coa_bc_address_master as M '
      + 'on ST_Point_Inside_Circle(ST_SetSRID(ST_Point(A.address_x, A.address_y),2264), M.address_x, M.address_y, $2) ' // eslint-disable-line max-len
      + 'LEFT JOIN amd.permit_comments AS B on A.permit_num = B.permit_num '
      + 'where M.civicaddress_id = $1 '
      + "AND A.permit_group <> 'Services'"; // Future function name change - ST_PointInsideCircle
      const qargs = [String(args.civicaddress_id), radius];
      let nextParam = '$3';
      if (args.before !== undefined) {
        qargs.push(`'${args.before}'`);
        query += `and applied_date < ${nextParam} `;
        nextParam = '$4';
      }
      if (args.after !== undefined) {
        qargs.push(`'${args.after}'`);
        query += `and applied_date > ${nextParam} `;
      }
      query += 'ORDER BY A.permit_num DESC, B.comment_seq_number ASC ';

      return context.pool.query(query, qargs)
      .then(result => {
        return preparePermits(result.rows, args.before, args.after);
      })
      .catch((err) => {
        logger.error(`Got an error in permits_by_address: ${err}`);
        throw new Error(`Got an error in permits_by_address: ${err}`);
      });
    },
    permits_by_street(obj, args, context) {
      const logger = context.logger;
      const radius = (args.radius) ? Number(args.radius) : 100; // State plane units are feet
      if (args.centerline_ids.length <= 0) return [];
      const query = 'SELECT A.*, M.address_full as address FROM amd.permits_along_streets_fn($1, $2) AS A ' // eslint-disable-line max-len
      + 'LEFT JOIN amd.coa_bc_address_master as M ON A.civic_address_id::INT = M.civicaddress_id '
      + "WHERE permit_group <> 'Services'"
      + 'ORDER BY permit_num DESC, comment_seq_number ASC ';

      return context.pool.query(query, [args.centerline_ids, radius])
      .then(result => {
        return preparePermits(result.rows, args.before, args.after);
      })
      .catch((err) => {
        if (err) {
          logger.error(`Got an error in permits_by_street: ${err}`);
          throw new Error(err);
        }
      });
    },
    permits_by_neighborhood(obj, args, context) {
      const logger = context.logger;
      if (args.nbrhd_ids.length <= 0) return [];
      const query = 'SELECT A.*, M.address_full as address '
      + 'FROM amd.permits_by_neighborhood_fn($1) AS A '
      + 'LEFT JOIN amd.coa_bc_address_master as M ON A.civic_address_id::INT = M.civicaddress_id '
      + "WHERE permit_group <> 'Services' "
      + 'ORDER BY permit_num DESC, comment_seq_number ASC ';
      return context.pool.query(query, [args.nbrhd_ids])
      .then(result => {
        return preparePermits(result.rows, args.before, args.after);
      })
      .catch((err) => {
        if (err) {
          logger.error(`Got an error in permits_by_neighborhood: ${err}`);
          throw new Error(err);
        }
      });
    },
    firstReviewSLAItems(obj, args, context) {
      const pool = context.pool;
      return pool.query(
        'SELECT * from amd.dsd_first_review_sla'
      )
      .then((result) => {
        if (result.rows.length === 0) return null;
        const p = result.rows;
        return p;
      })
      .catch((err) => {
        if (err) {
          console.log(`Got an error in firstReviewSLAItems: ${JSON.stringify(err)}`);
        }
      });
    },
    permit_tasks(obj, args, context) {
      const qargs = [];
      let query = 'SELECT * FROM amd.permit_tasks AS A ';
      if (args.permit_numbers && args.permit_numbers.length > 0) {
        qargs.push(args.permit_numbers);
        query += 'WHERE A.permit_num = ANY ($1) ';
      } else if (args.before || args.after) {
        const dateField = args.date_field || 'current_status_date';
        let nextParam = '$1';
        query += 'where ';
        if (args.before) {
          query += `${dateField} < $1 `;
          nextParam = '$2';
          if (args.after) query += 'and ';
          qargs.push(args.before);
        }
        if (args.after) {
          query += `${dateField} > ${nextParam} `;
          qargs.push(args.after);
        }
      }
      query += 'ORDER BY A.permit_num DESC ';
      return context.pool.query(query, qargs)
      .then((result) => {
        return preparePermitTasks(result.rows);
      })
      .catch((err) => {
        throw new Error(`Got an error in permit_tasks: ${JSON.stringify(err)}`);
      });
    },
  },

  Permit: {
    comments(obj, args, context) { // eslint-disable-line no-unused-vars
      return obj.comments;
    },
  },
};

module.exports = resolvers;
<|endoftext|>


<commit_before>/******************************************
 * Form Handlers and page                 *
 * generators for TSSAA WebApp Fat Client *
 *****************************************/
var Credentials = {
	username: "",
	secret: ""
};

$.fn.serializeObject = function () {
	var o = {};
	var a = this.serializeArray();

	$.each(a, function() {
		if (o[this.name] !== undefined) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

function generateAuthHeader(creds) {
	var nonce = generateNonce(16);
	var nonce64 = base64encode(nonce);

	var created = ISODateString(new Date());

	var digest = b64_sha1(nonce + created + creds.secret);

	var x_wsse_header = "UsernameToken Username=\""
		+ creds.user + "\", PasswordDigest=\""
		+ digest + "\", Nonce=\""
		+ nonce64 + "\", Created=\""
		+ created + "\"";

	return {'X-WSSE': x_wsse_header};
}

/**
 * AJAX convenience wrapper
 * @param uri target uri for request
 * @param args object comprised of args for ajax call
 */
function service_call(uri, args) {
	if (!args.hasOwnProperty('creds')) {
		args.creds = Credentials;
	}

	$.ajax(uri, {
		//type: args.hasOwnProperty("request_params") ? "POST" : "GET",
		type: 'POST',
		// JSON.stringify will return undefined if args.request_params is undef
		//data: ,//JSON.stringify(args.request_params),
		beforeSend: function (xhr) {
			xhr.setRequestHeader(generateAuthHeader(args.creds));
		},
		success: on_success,
		error: console.err(err),
		complete: on_complete,
	});

	function on_success (response, textStatus, jqXHR) {
		console.log("log: on_success: " + textStatus);

		data = JSON.parse(response);

		if (data.status === "success") {
			// TODO check if payload prop
			args.on_success(data.payload);
		} else {
			// TODO exception definitions
			args.on_failure(textStatus, data.exception);
		}
	}

	function on_failure (jqXHR, textStatus, errorThrown) {
		console.log("log: on_failure: " + textStatus);

		if (args.on_failure) {
			args.on_failure(textStatus, errorThrown);
		} else {
			// Do nothing
		}
	}

	function on_complete (jqXHR, textStatus) {
		console.log("log: on_complete: " + textStatus);

		if (args.on_complete) {
			args.on_complete(jqXHR, textStatus);
		} else {
			// Do nothing
		}
	}
	return false;
}

/**
 * Login form ajax callback
 * TODO session management handled here?
 */
function loginSuccess(login_response) {
	$("h2#options_welcome_banner strong").text(login_response.payload);
	$.mobile.changePage($("#options_page"), {
		transition: "slideup",
		reverse: true,
	});
}

/**
 * DB Dialog ajax success callback
 */
function popDBDialog(response) {
	$("#response").text("Success! New school added!");
	$.mobile.changePage("#db_confirm_dialog");
}

/**
 * School List response handler
 * generates ul of schools returned from DB
 */
function generateSchoolList(school_data) {
	var schools_html = [];

	for (school in school_data) {
		school = school_data[school];
		var button = 'Edit This School';

		var block = '

' +
			school.name + '

Phone: ' +
			school.phone + '

Address: ' +
			school.address + '
' + button + '
';
		schools_html.push(block);
	}

	$('div#school_list').html(schools_html.join(''));

	$('div#school_list').on('click', 'a.edit_school', function (e) {
		var index = $(this).attr("ks_school_id");
		var school = school_data[index];
		$.each($("form#edit_school_form input"), function() {
			var key = $(this).attr("name");
			$(this).attr("value", school[key]);
		});
		editSchoolEntity(school);
	});
	$.mobile.changePage($("#school_list_page"));
};

function editSchoolEntity(school) {
	$("#edit_school_form").on("submit", function (e) {
		var form_data = $("#edit_school_form").serializeObject();
		if( !form_data.id){
			form_data.id = school.id;
		}

		service_call("app_dev.php/update_school", {
			request_params: form_data,
			on_success: function () {$.mobile.changePage("#school_list_page")}
		});

		return false;
	});

	$.mobile.changePage("#edit_school_dialog", {
		transistion: "pop"
	});

}

$(document).on("pageinit", function(e, obj) {
	/**
	 * Login form handler
	 */
	$("#login_page").on("submit", function(e, obj) {
		var args = {};
		args.creds = {
			user: $("#login_input").val(),
			password: $("#pass_input").val()
		};
		console.info(args.creds, "creds");

		service_call("app_dev/login", args);
		console.info('post service_call');

		return false;
	});

	/**
	 * Add school form ajax handler
	 */
	$('#add_school_submit').on('click', function(e, obj) {
		var  formData = $('#add_school_form').serializeObject();

		service_call("app_dev.php/add_school", {
			request_params: formData,
			on_success: popDBDialog
		});

		return false;
	});
});

/**
 * Get school list ajax handler
 */
$(document).on("pagebeforechange", function(e, obj) {
	var url= $.mobile.path.parseUrl(obj.toPage);

	if ( url.hash  === "#school_list_page") {
		service_call("app_dev.php/get_school_list", {
			on_success: generateSchoolList
		});

		e.preventDefault();
	};
});

<commit_msg>log serialized object<commit_after>/******************************************
 * Form Handlers and page                 *
 * generators for TSSAA WebApp Fat Client *
 *****************************************/
var Credentials = {
	username: "",
	secret: ""
};

$.fn.serializeObject = function () {
	var o = {};
	var a = this.serializeArray();

	$.each(a, function() {
		if (o[this.name] !== undefined) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

function generateAuthHeader(creds) {
	var nonce = generateNonce(16);
	var nonce64 = base64encode(nonce);

	var created = ISODateString(new Date());

	var digest = b64_sha1(nonce + created + creds.secret);

	var x_wsse_header = "UsernameToken Username=\""
		+ creds.user + "\", PasswordDigest=\""
		+ digest + "\", Nonce=\""
		+ nonce64 + "\", Created=\""
		+ created + "\"";

	return {'X-WSSE': x_wsse_header};
}

/**
 * AJAX convenience wrapper
 * @param uri target uri for request
 * @param args object comprised of args for ajax call
 */
function service_call(uri, args) {
	if (!args.hasOwnProperty('creds')) {
		args.creds = Credentials;
	}

	$.ajax(uri, {
		//type: args.hasOwnProperty("request_params") ? "POST" : "GET",
		type: 'POST',
		// JSON.stringify will return undefined if args.request_params is undef
		//data: ,//JSON.stringify(args.request_params),
		beforeSend: function (xhr) {
			xhr.setRequestHeader(generateAuthHeader(args.creds));
		},
		success: on_success,
		error: console.err(err),
		complete: on_complete,
	});

	function on_success (response, textStatus, jqXHR) {
		console.log("log: on_success: " + textStatus);

		data = JSON.parse(response);

		if (data.status === "success") {
			// TODO check if payload prop
			args.on_success(data.payload);
		} else {
			// TODO exception definitions
			args.on_failure(textStatus, data.exception);
		}
	}

	function on_failure (jqXHR, textStatus, errorThrown) {
		console.log("log: on_failure: " + textStatus);

		if (args.on_failure) {
			args.on_failure(textStatus, errorThrown);
		} else {
			// Do nothing
		}
	}

	function on_complete (jqXHR, textStatus) {
		console.log("log: on_complete: " + textStatus);

		if (args.on_complete) {
			args.on_complete(jqXHR, textStatus);
		} else {
			// Do nothing
		}
	}
	return false;
}

/**
 * Login form ajax callback
 * TODO session management handled here?
 */
function loginSuccess(login_response) {
	$("h2#options_welcome_banner strong").text(login_response.payload);
	$.mobile.changePage($("#options_page"), {
		transition: "slideup",
		reverse: true,
	});
}

/**
 * DB Dialog ajax success callback
 */
function popDBDialog(response) {
	$("#response").text("Success! New school added!");
	$.mobile.changePage("#db_confirm_dialog");
}

/**
 * School List response handler
 * generates ul of schools returned from DB
 */
function generateSchoolList(school_data) {
	var schools_html = [];

	for (school in school_data) {
		school = school_data[school];
		var button = 'Edit This School';

		var block = '

' +
			school.name + '

Phone: ' +
			school.phone + '

Address: ' +
			school.address + '
' + button + '
';
		schools_html.push(block);
	}

	$('div#school_list').html(schools_html.join(''));

	$('div#school_list').on('click', 'a.edit_school', function (e) {
		var index = $(this).attr("ks_school_id");
		var school = school_data[index];
		$.each($("form#edit_school_form input"), function() {
			var key = $(this).attr("name");
			$(this).attr("value", school[key]);
		});
		editSchoolEntity(school);
	});
	$.mobile.changePage($("#school_list_page"));
};

function editSchoolEntity(school) {
	$("#edit_school_form").on("submit", function (e) {
		var form_data = $("#edit_school_form").serializeObject();
		if( !form_data.id){
			form_data.id = school.id;
		}

		service_call("app_dev.php/update_school", {
			request_params: form_data,
			on_success: function () {$.mobile.changePage("#school_list_page")}
		});

		return false;
	});

	$.mobile.changePage("#edit_school_dialog", {
		transistion: "pop"
	});

}

$(document).on("pageinit", function(e, obj) {
	/**
	 * Login form handler
	 */
	$("#login_page").on("submit", function(e, obj) {
		var args = {};
		args.creds = {
			user: $("#login_input").val(),
			password: $("#pass_input").val()
		};
		console.info(serializeObject(args.creds, "creds"));

		service_call("app_dev/login", args);
		console.info('post service_call');

		return false;
	});

	/**
	 * Add school form ajax handler
	 */
	$('#add_school_submit').on('click', function(e, obj) {
		var  formData = $('#add_school_form').serializeObject();

		service_call("app_dev.php/add_school", {
			request_params: formData,
			on_success: popDBDialog
		});

		return false;
	});
});

/**
 * Get school list ajax handler
 */
$(document).on("pagebeforechange", function(e, obj) {
	var url= $.mobile.path.parseUrl(obj.toPage);

	if ( url.hash  === "#school_list_page") {
		service_call("app_dev.php/get_school_list", {
			on_success: generateSchoolList
		});

		e.preventDefault();
	};
});

<|endoftext|>


<commit_before>/** @jsx REACT.DOM */
import React from 'react';
import Header from './header';
import TrackList from './track-list';
import ControlPanel from './control-panel';
import Queso from '../models/queso';
import Track from '../models/track';

export default React.createClass({
  queso: new Queso(),

  componentWillMount: function () {
    this.queso.addTrack(new Track({
      id: 0,
      title: 'fire',
      type: 'MIDI'
    }));
    this.queso.addTrack(new Track({
      id: 1,
      title: 'beats',
      type: 'AUDIO'
    }));

    this.queso.on('TRACK_SELECTED', this._onChange);
  },

  getQueso: function () {
    return {queso: this.queso};
  },

  getInitialState: function () {
    return this.getQueso();
  },

  _onChange: function () {
    this.setState(this.getQueso());
  },

  render: function () {
    return (

        <TrackList queso={this.state.queso} />
        <ControlPanel track={this.state.queso.selectedTrack} />

    );
  }
});
<commit_msg>remove that default audio track cause probably no audio tracks<commit_after>/** @jsx REACT.DOM */
import React from 'react';
import Header from './header';
import TrackList from './track-list';
import ControlPanel from './control-panel';
import Queso from '../models/queso';
import Track from '../models/track';

export default React.createClass({
  queso: new Queso(),

  componentWillMount: function () {
    this.queso.addTrack(new Track({
      id: 0,
      title: 'fire',
      type: 'MIDI'
    }));

    this.queso.on('TRACK_SELECTED', this._onChange);
  },

  getQueso: function () {
    return {queso: this.queso};
  },

  getInitialState: function () {
    return this.getQueso();
  },

  _onChange: function () {
    this.setState(this.getQueso());
  },

  render: function () {
    return (

        <TrackList queso={this.state.queso} />
        <ControlPanel track={this.state.queso.selectedTrack} />

    );
  }
});
<|endoftext|>